Invoke-Command -ScriptBlock 将变量与 LIST 一起引入

Invoke-Command -ScriptBlock bringing variable with LIST

提问人:Anirban Banerjee 提问时间:10/6/2022 更新时间:10/6/2022 访问量:195

问:

我正在尝试远程执行脚本以获取服务列表,但排除当前处于停止状态的某些服务。我无法将排除变量作为列表传递。

如果我只是在本地使用它,它可以工作,但在远程调用命令中则不然。

$exclusionList = 'DoSvc', 'gupdate', 'sppsvc', 'dmwappushservice', 'edgeupdate', 'Intel(R) TPM Provisioning Service', 'wscsvc', 'LPlatSvc', 'Net Driver HPZ12', 'gpsvc', 'Pml Driver HPZ12', 'RstMwService'

$so = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck 

Invoke-Command -ComputerName $IP -UseSSL -ScriptBlock { param([string]$eList) get-service -Exclude $eList| where {$_.StartType -eq "Automatic" -and $_.Status -eq "Stopped"} -ArgumentList $exclusionList  } -SessionOption $so -Credential Computer\User01

从 ScriptBlock 中删除$elist可以工作。但我确实想在 sriptblock 中传递排除某些服务的值

PowerShell invoke-command 脚本块

评论

1赞 Dilly B 10/6/2022
请尝试使用 ''' -ArgumentList (,$exclusionList)'''

答:

0赞 Toni 10/6/2022 #1

您尝试从远程计算机访问变量 ($exclusionList)。您可以像执行此操作一样,通过使用参数“-ArgumentList”指定变量或使用 $using 来执行此操作。

访问参数为“-ArgumentList”的变量

Invoke-Command -ComputerName $IP -UseSSL -ScriptBlock {get-service -Exclude $args[0] | where {$_.StartType -eq "Automatic" -and $_.Status -eq "Stopped"} -ArgumentList $exclusionList  } -SessionOption $so -Credential Computer\User01

参数“-Argumentlist”提供的变量可以通过变量 $args 从 ScriptBlock 访问,该变量是一个数组。要访问参数“-Argumentlist”提供的第一个元素,您可以执行“$args[0]”。

MS Docu

或者,您可以使用 $using 从远程计算机访问变量:

Invoke-Command -ComputerName $IP -UseSSL -ScriptBlock {get-service -Exclude $using:exclusionlist | where {$_.StartType -eq "Automatic" -and $_.Status -eq "Stopped"}} -SessionOption $so -Credential Computer\User01

这样,您就不必指定参数“-Argumentlist”。请参阅文档中的$using。