在多台远程计算机上运行Powershell脚本

问题描述

美好的一天。

如果这是一个重复的问题,我深表歉意,但是我所做的研究使我更加困惑。我正在尝试运行以下Powershell脚本来删除某些计算机上的文件夹:

$users = get-childitem c:\users

foreach ($user in $users)
{
$folder = "C:\Users\" + $user + "\AppData\Local\Microsoft\OneDrive"
Remove-Item $folder -Recurse -Force -ErrorAction silentlycontinue
}

该脚本似乎有效。如何在远程计算机列表上使用此脚本?

谢谢。

解决方法

您可以将Invoke-Command cmdlet与ComputerName参数一起使用。示例:

Invoke-Command { $env:ComputerName } -ComputerName SOMEMACHINE
,

dugas指出,您可以使用Invoke-Command通过-ScriptBlock-ComputerName参数执行远程脚本执行。

# Create script block using surrounding {}
$sb = {
$users = Get-Childitem C:\Users -Directory -Name

foreach ($user in $users) {
    $folder = "C:\Users\" + $user + "\AppData\Local\Microsoft\OneDrive"
    Remove-Item $folder -Recurse -Force -ErrorAction silentlycontinue
}
}
# Create array of computer names since -ComputerName accepts an array
$computers = 'computer1','computer2','computer3'

Invoke-Command -ComputerName $computers -ScriptBlock $sb

有许多遍历远程目录的方法。将Get-ChildItem-Directory-Name参数一起使用将仅返回C:\Users下的文件夹名称。

,

如果您使用的是Active Directory域,请不要让脱机计算机,笨拙的计算机等困扰,而请SysAdmin使用组策略首选项创建一次运行计划任务。