For PowerShell logic to run from one location against multiple servers, ensure Enable-PSRemoting is run on each of the servers you want to run commands against remotely. Once that is enabled, use Invoke-Command to run PowerShell commands and other executable files on remote servers.
Ensure PSRemoting is enabled on each server by running Enable-PSRemoting -Force
on each of the servers one time, via Group Policy or startup scripts, or however you normally do that in your environment.
Create a list of the servers you want to run the command against to do the cleanup either by putting an array list in the scripted logic or in a text file and using that to create an array via get-content.
So for the server list the two options are...
- Put the list of servers in the script itself
$Servers = @("Server1","Server2.domain.com","Server4.otherdomain.com");
- Have a text file with the servers in it and use
Get-Content
in the script to get the list
Script
Clear-Host
Set-ExecutionPolicy RemoteSigned
$Servers = @("Server1","Server2.domain.com","Server4.otherdomain.com");
###$Servers = Get-Content "\\Server\Share\Folder\Lists\ServerCleanupList.txt"
$Now = Get-Date
$Days = "30"
$TargetFolder = "C:\Older"
$Extension = "*.*"
$LastWrite = $Now.AddDays(-$Days)
$Servers | %{
Invoke-Command -ComputerName $_ -ScriptBlock {
$Files = Get-ChildItem $Using:TargetFolder -Include $Using:Extension -Recurse | Where {$_.LastWriteTime -le $Using:LastWrite}
$Files | %{If($_.FullName){$_.FullName | Remove-Item -Force}}
C:\Windows\System32\forfiles.exe /p "C:\Older" /s /d -30 /c "cmd /c del @file"
} -AsJob;
};
Using Invoke-Command
with the -AsJob
parameter executes the command on the remote system as a background job, and then moves on doing the same for each subsequent server in the list.
Supporting Resources
- Enable-PSRemoting
Invoke-Command
-ScriptBlock scriptblock
The commands to run.
Enclose the commands in curly braces { }
to
create a script block. This parameter is required.
By default, any
variables in the command are evaluated on the remote computer. To
include local variables in the command, use -ArgumentList
or in
PowerShell 3.0+ use the prefix $using:
before the local variable to be
passed e.g. { echo $using:mylocalVar }
Get-Content