Powershell ForEach对象{Start Job-Scriptblock}未填充变量

Powershell ForEach对象{Start Job-Scriptblock}未填充变量,powershell,Powershell,这是我的代码,它可以为OU中的每台计算机工作并创建一个作业,但不会在我的脚本块中填充$computer变量,从而导致此操作失败 我肯定我错过了一些小东西,因为我以前从未在Powershell中创造过就业机会,但在为此工作了一两个小时后,我一直无法弄清楚我错过了什么 #Gets all workstations that need to have software installed, if you don't want to uninstall all of the software from

这是我的代码,它可以为OU中的每台计算机工作并创建一个作业,但不会在我的脚本块中填充$computer变量,从而导致此操作失败

我肯定我错过了一些小东西,因为我以前从未在Powershell中创造过就业机会,但在为此工作了一两个小时后,我一直无法弄清楚我错过了什么

#Gets all workstations that need to have software installed, if you don't want to uninstall all of the software from you will need to use a text document and Get-Content
$computers = Get-ADComputer -Filter * -SearchBase "OU=Workstation Test,OU=Workstations,OU=Workstations,DC=CONTOSO,DC=COM" | Select DNSHostName -ExpandProperty DNSHostname


$Computer
#Use Get-WMIObject to find the IdentifyingNumber
$Computers | ForEach-Object {Start-Job -Name "$Uninstall" -ScriptBlock {(Get-WmiObject -Class Win32_product -ComputerName $Computer -Filter {IdentifyingNumber LIKE '{CD95F661-A5C4-44F5-A6AA-ECDD91C2410B}'}).uninstall()}}

您需要使用
$而不是
$计算机

$\表示管道中的当前项

或者,您可以:

ForEach ($Computer in $Computers) { Invoke-Command -ComputerName $Computer -ScriptBlock {(Get-WmiObject -Class Win32_product -Filter {IdentifyingNumber LIKE '{CD95F661-A5C4-44F5-A6AA-ECDD91C2410B}'}).uninstall()} }
在这里,您将继续在foreach中使用$Computer,因为它现在会被集合中的每个项目填充

另外,仅供参考,当前不需要ForEach对象上方的
$computer
行(它只是输出一个空变量,除非您已经在其他地方填充了它)


编辑:根据评论,我还注意到开始作业似乎是多余的,因为在wmi cmdlet上使用了-computername。Invoke命令是首选命令,因为它使用winrm,所以我在上面的代码中对其进行了修改。

存在的原因是我从我编写的旧脚本中复制了它,并将其放在适当的位置,以便我可以看到当前foreach循环正在使用哪台计算机。这两种方法似乎都不起作用。当我使用原始脚本并将$Computer修改为$\时,仍然会出现错误。无法验证参数“ComputerName”上的参数。参数为null或为空。请提供一个不为null或空的参数,然后重试该命令。我已将此脚本作为Foreach循环正常运行,但速度非常慢,我希望并行运行它们,因此我正在尝试使用作业。目前“SELECTDNSHOSTNAME”工作正常。如果您想并行运行,我认为您需要调用命令-asjob。您还需要阅读receive作业,了解如何在最后收集结果。我认为您应该将$computers传递给该命令,而不是使用foreach。