Powershell -在多台计算机上同时运行脚本



我正在编写一个脚本,用于清理旧用户帐户和计算机中的一些数据。我想从附件中的pc列表中同时在5台计算机上运行脚本。这可能吗?如果可以,怎么做呢?

[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$host_path = 'Host path'
)
$computer = Get-Content "$host_path"
foreach ($computer in $computer){
Invoke-Command -ComputerName $computer -ScriptBlock { Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special) -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-30))}| Remove-WmiObject }
Invoke-Command -ComputerName $computer -ScriptBlock { Remove-Item -Path C:Windowsccmcache* -Confirm:$false -Force -Recurse -Debug }
Invoke-Command -ComputerName $computer -ScriptBlock { Remove-Item -Path C:ProgramData1ENomadBranch* -Confirm:$false -Force -Recurse -Debug }
}
<代码>

您可以一次将多个计算机名称传递给-ThrottleLimit以实现此目的:

$computerNames = Get-Content $host_path
$batchSize = 5
while($computerNames.Count -gt 0){
# Pull the first N names from the list
$nextBatch = @($computerNames |Select -First $batchSize)
# Then overwrite the list with any elements _after_ the first N names
$computerNames = @($computerNames |Select -Skip $batchSize)
Write-Host "Executing remote command against $($nextBatch.Count) computers: [$($nextBatch.ForEach({"'$_'"}) -join ', ')]"
# Invoke remoting command against the batch of computer names
Invoke-Command -ComputerName $nextBatch -ScriptBlock { 
Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special) -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-30))}| Remove-WmiObject
Remove-Item -Path C:Windowsccmcache* -Confirm:$false -Force -Recurse -Debug
Remove-Item -Path C:ProgramData1ENomadBranch* -Confirm:$false -Force -Recurse -Debug
}
}

如果你想"chunk"一次将N台机器上的计算机名列表分批处理,您可以这样做:

[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$host_path = 'Host path'
)
# The default value for ThrottleLimit is 5, but I put it here to show syntax.
# Throttle is the number of concurrent runspaces to use. (ex: do 5 objects at a time)
Get-Content $host_path | Foreach-Object -ThrottleLimit 5 -Parallel -ScriptBlock {
Invoke-Command -ComputerName $_ -ScriptBlock { 
Get-WMIObject -class Win32_UserProfile | Where-Object {(!$_.Special) -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-30))}| Remove-WmiObject
Remove-Item -Path C:Windowsccmcache* -Confirm:$false -Force -Recurse -Debug
Remove-Item -Path C:ProgramData1ENomadBranch* -Confirm:$false -Force -Recurse -Debug
}
}

如果您使用的是PowerShell 7。X,您可以执行以下操作。

PP_5这将一次运行X个循环,X是您的5值,默认为CC_4。

同样,这只在PowerShell 7中可用,而不向后兼容Windows PowerShell。

最新更新