Powershell

20K

Solutions

8K

Contributors

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.

Share tech news, updates, or what's on your mind.

Sign up to Post

I have several hundred sites on my SharePoint 2013 farm that I need to set to "No Access" by locking the site collection.  What I would like to do, is use a PowerShell script to read the list of URL's from a text file, loop through each one, and lock the site collection.  This is what I have so far, but need some assistance on getting it completed:

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
 
$Sites = Get-Content -Path e:\scripts\SitesToLock.txt
 
ForEach ($site in $Sites) 
{
  Set-SPSite -Identity $site.Url -LockState "NoAccess" }

Open in new window

0
Starting with Angular 5
LVL 20
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Hello - I have the below script working OK. it creates an object and actions some things for IE.

all works in this script

 
"Starting Internet Explorer in Background"
$ie = New-Object -com InternetExplorer.Application
$ie.visible=$true
$uri = 'https://MYWEBSITEIP/ossim/session/login.php#analysis/alarms/alarms'
#$ie.FullScreen = $true
$ie.TheaterMode = $true
$ie.navigate("$uri")
"Bypassing SSL Certificate Error Page";
start-sleep -s 5;
$sslbypass=$ie.Document.getElementsByTagName("a") | where-object {$_.id -eq "overridelink"}
$sslbypass.click()

Open in new window


but as soon as I try to click the logon button that's where my problems start... I have tried multiple ways to click it and it comes up with the error below the code. I know I only need to click login once but I tried C_login and F_login as these were the elements I could see on the webpage. tried other variants. but my error makes me thing its more than just the name wrong.

 
"Starting Internet Explorer in Background"
$ie = New-Object -com InternetExplorer.Application
$ie.visible=$true
$uri = 'https://MYWEBSITEIP/ossim/session/login.php#analysis/alarms/alarms'
#$ie.FullScreen = $true
$ie.TheaterMode = $true
$ie.navigate("$uri")
"Bypassing SSL Certificate Error Page";
start-sleep -s 5;
$sslbypass=$ie.Document.getElementsByTagName("a") | where-object {$_.id -eq "overridelink"}
$sslbypass.click()
$loginclick=($ie.document.getElementsByName("c_login") |select -first 1).click()
$loginclick=($ie.document.getElementsByName("f_login") |select -first 1).click()

Open in new window


You cannot call a method on a null-valued expression.
At E:\KEEP\~Scripts\Get Internet Explorer and sign in.ps1:13 char:1
+ $loginclick=($ie.document.getElementsByName("c_login") |select -first ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
 
You cannot call a method on a null-valued expression.
At E:\KEEP\~Scripts\Get Internet Explorer and sign in.ps1:14 char:1
+ $loginclick=($ie.document.getElementsByName("f_login") |select -first ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
1
powershell IE or Firefox open in fullscreen mode.

I am trying to open up a process of IE or Firefox to a specific webpage in full screen mode. when I say full screen I mean the f11 no banners showing. not just windows maximised.

the start-process command is easy to use but I cant figure out how to get it into this full screen mode. the easiest way of doing this in my eyes is using the -K Kiosk option available.

if I run the following cmd from Run it opens as expected: iexplore.exe -K https://www.google.com

how do I achieve the same in powershell?

is it possible to just invoke F11 button and press full screen? as Kiosk mode doesn't allow you to anything but 'close' the session. either solution will work for me.

if a better suggestion is available in Firefox I am open to this as well.
0
Dear experts

I got stuck with the code below, the if ($_.lastwritetime - $2daysago) is wrong, I would like the get-childitems to also search the creationtime, now the $count only count the result.

I would like to make: f ($_.lastwritetime - $2daysago) works. Anyone know how? Thanks

$servers = Import-Csv -Path C:\Scripts\serverlist.csv
$2daysago = (get-date).AddDays(-2)
$out = @()

$result = foreach ($path in $servers) {
	$count = Get-ChildItem $Path.Path -recurse -ErrorAction SilentlyContinue  -exclude "arkiv", "error", "avvisade", "archive", "slask", "Fel", "wei" | Where-Object {!($_.PSIsContainer) <#-and ($_.LastWriteTime -ge $2daysago)#>} | Measure-Object |
		Select-Object -ExpandProperty Count

    If ($count -gt 0) {
                       if ($_.lastwritetime -ge $2daysago) {
                       $normal = 1
                       $Msg = "$($path.DisplayName) File created in 2 days" 
         }
                       if  ($_.lastwritetime -le $2daysago) {
                       $normal = 0
                       $Msg = "Warning: $($path.Path) File created more than 2 days ago" 
         }
     		$out = '' | Select-Object -Property FilesCount, CollectFolder, Note
		$out.FilesCount = $count
		$out.CollectFolder = $path.Path
		$out.Note = $msg 
        $out
	}
}

Open in new window

1
Hi,

Is there way to get this result in Powershell?
$FirefoxVersionCVE then also get its real cve score (now it lists all kinds of cve scores for that firefox
https://www.cvedetails.com/version-search.php?vendor=Mozilla&product=Firefox&version=60
0
How to pull OU data from list of emails in AD. I have a .csv file with just the email address and need to add a column for location. What would be the easiest way to do this in PowerShell?
1
Hey Experts.  I'm trying to do something simple (or so I thought) and wanted to delete out old SQL backup files (*.diff and *.bak).  If I try to manually delete them, I have no problems.  When I try one of the 5 or 6 I found on the web and modified the days/dir path, I get an error:

Remove-Item : Cannot remove item E:\sql backups\WSS_Content_db_201910232200.diff: Access to the path 'E:\sql backups\WSS_Content_db_201910232200.diff' is denied.

I've tried:
$Path = “E:\SQL Backups”
$Daysback = “-45”
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path -Recurse | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item -Recurse

Open in new window


And:
$limit = (Get-Date).AddDays(-45)
$path = "E:\SQL Backups"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $limit } | Remove-Item -Force 

Open in new window


If you have a different script you'd like me to test, go for it.  I'm up for whatever in the heck will get these files deleted out of that dir without manual intervention.  Thank you in advance for your help and time on this!
0
PowerShell experts out there. I have a server with several thousand folders and files which have been touched for a long time.
I would like to get a report on those folders and files. Is there any ps script that you have so I can get a report of those files and folder?
0
Apologies for the basic question,my Googling skills obviously not up to the task!

So, I am trying to list all properties of an object, which include a certain string in the value.
For example, list any AD user properties. for e specific user,  that contain  "John" in the value.

so if I do get-aduser John -propetirs *| how do I filter this so it only returns properties that contain slthe string "John" anywhere in the value?
1
We are migrating some data and would like to change some of the groups, while preserving the rest of the permissions. What is the best approach to do that? At the moment I am thinking something along the lines of

set the permissions manually at the top level - easy

use robocopy to copy only the contents without affecting the  level folder - basically run it at "\\server\folder\subfolder" level - not ideal as I'd have to copy any files at  "\\server\folder\" level separately, and sometimes there are loads for subfolders, so plenty of robocopy instances.

run some sort of a script to get a list of subfolders where due to blocked inheritance the old group still exists and has been copied across by robocopy. maybe some get-acl/set-acl script that finds a group, removes it and adds a separate group in its place.

finally run some script to get a list of files that have manually - not likely but if it is possible, so someone would have done it.


There is a lot of data, so I am trying to use inheritance to do most of the work, and then just mop up the instances of blocked inherritance, rather than run some script against every single file.
0
CompTIA Cloud+
LVL 20
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Hi Experts,

I have a Microsoft Failover Cluster with 2 nodes and a Quorum disk (file share witness). Lately when I've taken one node offline for maintenance the cluster has shutdown all my VM's, I've had to reconnect to the cluster and then my VM's restart and come online. I always test the FSW before I take a node server offline and it always responds. Right now I can no longer trust the cluster. Below are the 2 events recorded...

Critical

File share witness resource 'File Share Witness' failed to arbitrate for the file share '\\<SERVERNAME>\WitnessCluster2'. Please ensure that file share '\\<SERVERNAME>\WitnessCluster2' exists and is accessible by the cluster.

Error

Cluster resource 'File Share Witness' of type 'File Share Witness' in clustered role 'Cluster Group' failed.

Based on the failure policies for the resource and role, the cluster service may try to bring the resource online on this node or move the group to another node of the cluster and then restart it.  Check the resource and group state using Failover Cluster Manager or the Get-ClusterResource Windows PowerShell cmdlet.


How do I stop this happening on my cluster, it does not make sense because the FSW is available and online but as soon as I restart a host node my cluster falls apart and its a real problem when you have 20 VM's that depend on it working.

The 2 nodes are running with Windows Server 2012 R2 Datacenter
The FSW is located on a server running …
0
How to setup powershell parameters?

I'd like the command to do this. Basically,
1) Copy or Delete is used but not both.
2) DaysOld is required with both.

Example:

.\command.ps1 -DaysOld 30 -copy "c:\folder"

Open in new window


...or:

.\command.ps1 -DaysOld 30 -delete "c:\folder"

Open in new window


This is what I have. It kind of works. I don't understand what I'm doing. Is there is a better or correct way to do it:

[CmdletBinding(DefaultParameterSetName='Copy')]
    Param(
        [Parameter(ParameterSetName='Copy',Mandatory=$false,Position=0)]
        [Parameter(ParameterSetName='DaysOld',Mandatory=$false,Position=0)]
        [String]$Copy,

        [Parameter(ParameterSetName='Delete',Mandatory=$false,Position=0)]
        [Parameter(ParameterSetName='DaysOld',Mandatory=$false,Position=0)]
        [String]$Delete,

        [Parameter(ParameterSetName='DaysOld',Mandatory=$false,Position=0)]
        [Int]$DaysOld
    )

Open in new window

0
Dear expert

Please read the code below.
Problem is within the beginning, I want to add $ServerPathC1 and $ServerPathC2 with $list1 and $list2 and add the new list to variable $pathlist and to a foreach on $pathlist.
For exemple:
In text file: c:\folderlist65_27_70.txt I got like
test1\temp
test2\temp
test3\temp
In text file: c:\folderlist04_56.txt I got like
testagain1\temp
testagain2\temp
testagain3\temp
I want to do a $ServerPathC1 + content in list1 so they become: d:\folder1\test1\temp and then add them to $pathlist then from $pathlist do a foreach to it.
Place I stuck with is the foreach, the foreach statement below runs with double result, and its wrong. Anyway to solve this?

Thanks.

$ServerPathC1 = "d:\folder1\" 
$ServerPathC2 = "d:\folder2\"
$list1 = Get-Content 'c:\folderlist65_27_70.txt'
$list2 = Get-Content 'c:\folderlist04_56.txt'
$7daysago = (Get-Date).AddDays(-7)
$Pathlist = @()
$warning = 0

$pathlist = foreach ($1 in $list1) {
foreach ($2 in $list2){
$ServerPathC1 + $1 
$ServerPathC2 + $2 
}
}


$result = ForEach ($path in $Pathlist) {
	$count = Get-ChildItem $path -Exclude 'keep*', 'testfilnamn*', 'tilltestfil*', 'Crend*', 'KFMtest*' |
		Where-Object {!($_.PSIsContainer) -and ($_.LastWriteTime -le $7daysago) -or ($_.Name -like '*failed*')} | Measure-Object |
		Select-Object -ExpandProperty Count
	If ($count -gt 0) {
		
        $warning++
		$out = '' | Select-Object -Property FilesCount, CollectFolder
		$out.FilesCount = $count
	

Open in new window

0
We use folder and server specific AD security groups to manage access  to our shared folders, and need to replace some of the groups as we are migrating them to a new server.

The folder specific groupss  are  ServerA-dir-folder-rw, serverA-dir-folder-ro
The server specific groups is ServerA-dir-rw, ServerA-dir-ro


We need to rename the folder groups to ServerB-dir-folder-rw, serverB-dir-folder-ro - whch attributes should we rename - cn,name,samaccountname,etc?

We need tor replace the server specific groups with ServerB-dir-rw, ServerB-dir-ro - we cannot rename those, as they are still in use on Server A. How do I replace these?
The issue is we have a lot of blocked inheritance down the folder structure, so we cant just replace them at the top level.


Thank you!
0
Dear expert

I would like to add creationtime in the table below:

$Pathlist = Get-Content c:\folderlist.txt
$7daysago = (Get-Date).AddDays(-7)
$warning = 0
$result = ForEach ($path in $Pathlist) {
	$count = Get-ChildItem $path -Exclude 'keep*', 'testfilnamn*', 'tilltestfil*' |
		Where-Object {!($_.PSIsContainer) -and ($_.LastWriteTime -le $7daysago) -or ($_.Name -like '*failed*')} | Measure-Object |
		Select-Object -ExpandProperty Count
	If ($count -gt 0) {
		
        $warning++
		$out = '' | Select-Object -Property FileNumber, FolderList, Creationtime
		$out.FileNumber = $count
		$out.FolderList = $path
        $out.Createtime = ????? 
		$out
	}
}

$result

Open in new window

Is this possible to do? Thanks
0
Dear expert

See script below:

$servers = Get-Content c:\folderlist.txt
$7daysago = (Get-Date).AddDays(-7)
$warning = 0
$result = ForEach ($server in $servers) {
	$count = Get-ChildItem $server -Exclude 'keep*', 'testfilnamn*', 'tilltestfil*' |
		Where-Object {!($_.PSIsContainer) -and ($_.LastWriteTime -le $7daysago) -or ($_.Name -like '*failed*')} | Measure-Object |
		Select-Object -ExpandProperty Count
	If ($count -gt 0) {
    $warning++
    $($count), $($server)
	}
}

$result  | ConvertFrom-String 

Open in new window

I want to create a table of the $result this means column 1 for $count column 2 for $server and rename the column title as: FileNumber and FolderList. I think in the some tries I came as far as the column name was P1 and P2, but didn't know how to change the column name. Please help.
1
In my Office 365 tenant, one of the user changed his password January 5th (I have the proof through an Activity alert I have set sent by Office 365) but the LastPasswordChangeTimestamp  property that I query using PowerShell is still showing the previous date when he changed his password (Sept 24, 2019).

We are using Office 365 alone (our AD is on-premise and fully disconnected).

We have a policy set to have the password expiring after 90 days. The user still have access to his mailbox.

Anybody saw that before? How to fix?
0
Dear experts

Script below list all path inside folderlist.csv this works fine, however I stuck with if I would only show those path which got more than 0, basicly I want to ignore those path with no files in the folder. when I see the $result. How do I do here? Thanks alot.

$servers = Import-Csv -Path c:\folderlist.csv
$7daysago = (get-date).AddDays(-7)
$result = $servers | ForEach-Object {

$count = (Get-ChildItem -Path $_.Path -Exclude keep*, testfilnamn*, tilltestfil* |
Where-Object { !($_.PSIsContainer) -and $_.LastWriteTime -le $7daysago -or $_.Name -like '*failed*'}).count
"$($count) Files in '$($_.Path)'"
}
$result

Open in new window

0
Hi,

I have a log file with output in the following format. I put xxxxxxxx because the log contains sensitive data.
There are multiple sections like this one and all are separated by a blank line.

I wish to receive an e-mail/set an alert when if any of the dates in the log are more than 24 hours ago. Just trying to figure out how to read and compare the dates with the current date.

xxxxxxxx                                            : xxxxxxxx
xxxxxxxx                                            : xxxxxxxx
xxxxxxxx                                            : xxxxxxxx
xxxxxxxx                                            : 1/14/2020 5:30:08 AM
xxxxxxxx                                            : 1/14/2020 5:30:06 AM
xxxxxxxx                                            : 1/14/2020 5:30:04 AM
xxxxxxxx                                            : 1/14/2020 5:30:08 AM

Open in new window


If anyone can get me in the right direction if would be very much appreciated.

Cheers
1
Introduction to R
LVL 20
Introduction to R

R is considered the predominant language for data scientist and statisticians. Learn how to use R for your own data science projects.

I'm trying to write a simple PS script to remove EAS partnerships to a mailbox.  This only needs to be done 1 by 1, but Ideally I could import a CSV for it.  The CSV import I think I can do, but I'm having trouble with the 1 at a time script.  I'm really basic when it comes to PS so I'd appreciate any help - for each and variables are super confusing.  

This is what I have:  
$User = Read-Host -Prompt "Who's Mobile Devices are you going to nuke?  Enter username"
$Devices = Get-MobileDevice -Mailbox $user
ForEach ($Device in $Devices) 
    {
        Remove-MobileDevice $Device
     }
Clear-Variable User,Name,Devices

Open in new window

But I keep getting this:
Cannot process argument transformation on parameter 'Identity'. Cannot convert the "Persons Name\ExchangeActiveSyncDevices\iPad§Q5F3123456KHLAGK41P7VO" value of type 
"Deserialized.Microsoft.Exchange.Data.Directory.SystemConfiguration.MobileDevice" to type "Microsoft.Exchange.Configuration.Tasks.MobileDeviceIdParameter".
    + CategoryInfo          : InvalidData: (:) [Remove-MobileDevice], ParameterBindin...mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Remove-MobileDevice
    + PSComputerName        : outlook.office365.com

Open in new window


Then I'll do
Set-CASMailbox username -ActiveSyncDeviceIDs $null

Open in new window

as a finisher.  

What do you think of this process?  

Since I know you're curious, we just migrated to G-Suite and I want to prevent people from accidentally accessing their 365 mailbox on mobile.
0
Can anyone provide me a link and or a power shell script for Windows Server 2008 that will strip every folders permission away from the top parent?  Currently one of our clients has file permissions so messed up with embedded admin privileges i groups that are located in sub groups of groups that no matter what we try we are not able to adjust permissions properly.   I was thinking of just ripping the entire permissions out and then starting over and handing them down again properly.    Inherited permissions have been removed from the sub folders under the parent but access is so messed up that I am unable to fix this correctly.   Some how the domain administrator login is linking itself to the folders which it normally should, however it is allowing regular domain users the ability to view the folders contents even though they have no permission to the folder.  Whether or not we set the owner of that particular folder with the right permissions it does not matter.  So I am trying to come up with a fast efficient way to fix this since the previous company that managed this client just made up admin groups and gave admin access to groups within groups making it almost impossible to try and pinpoint where the problem is.
0
Powershell script to remove user from all distribution groups
0
Dear expert

Im trying to create a script but stuck. Code below on progress:
$usernames = Get-content 'D:\temp\user.txt' 
$passwords = Get-Content 'D:\temp\pass.txt' | ConvertFrom-SecureString

foreach ($user in $usernames) {
foreach ($pass in $passwords) {
$cred = new-object -typename System.Management.Automation.PSCredential `-argumentlist $user, $pass
$filename = '.\encryption\' + $cred.UserName + '.txt'
$cred.Password | Set-Content $filename
}
}
WriteLog "Encrypted password for user" $cred.UserName "saved to $filename by $env:UserName"

Open in new window

Now the logic are in files pass.txt and user.txt, there are usernames and passwords saved, the password need to randomly to be picked in the list. This i haven't done yet. [random] function is needed, now there are 2 foreach statement, logic: pick every username in usernames variable and randomly pick the password in the password array.encrypt with ConvertFrom-SecureString option, this I did not get to work. Then create a log file with which password it picked... Create log file with which password it picked is not done yet.

Please thanks.
0
I am looking to create a script that will take all users from the disabled OU  and remove all AD group memberships minus domain users so that it doesnt throw an error.
Would this work?

$OUpath = "OU=Disabled,OU=Users,OU=Park_Users_and_Groups,DC=park,DC=net"
$disbaledUsers = Get-ADUser -Filter * -SearchBase $OUpath

foreach ($disableduser in $disabledusers)
{

Remove-ADGroupMember -Identity *


}

Open in new window

0
I need several email lists by distribution group.  I am trying to export the groups out of Exchange 2010 into a csv file to be used in another application.  Can someone help with this?  I understand there is something that can be done in Powershell.
0

Powershell

20K

Solutions

8K

Contributors

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.