Powershell ForEach-Object {Start-Job -Scriptblock}不填充变量

时间:2017-03-14 19:49:28

标签: 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 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()}}

1 个答案:

答案 0 :(得分:1)

而不是$computer,您需要使用$_

$ _表示管道中的当前项目。

或者你可以这样做:

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-Object上面的$computer行当前是不必要的(它只是输出一个空变量,除非你已经在别处填充了它)。

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

相关问题