Invoke-Command 远程会话:无法验证参数

3

我写了一个脚本来重新启动远程服务器上的几个ASP.NET网站:

$computerName = #...
$password = #...
$secureStringPassword = ConvertTo-SecureString -AsPlainText -Force -String $password
$userName = #...
$credential= New-Object System.Management.Automation.PSCredential ($userName, $secureStringPassword)
$websiteNames = #..., #..., #...

Get-PSSession -ComputerName $computerName -Credential $credential | Remove-PSSession 

$psSession = New-PSSession -ComputerName $computerName -Credential $credential

Invoke-Command -Session $psSession -ScriptBlock { $websiteNames | foreach{ Stop-Website -Name $_ } }
Invoke-Command -Session $psSession -ScriptBlock { $websiteNames | foreach{ Start-Website -Name $_ } }

$psSession | Remove-PSSession 

由于某些原因,我的Invoke-Command不能正常运行,我收到了以下错误消息:

无法验证参数“Name”的参数。该参数为空。提供一个有效值作为参数,然后再次尝试运行命令。

当在Enter-PSSession之后运行命令时,在-ScriptBlock中运行它可以正常工作,但会有-Name参数的混乱。有什么办法可以解决这个问题吗?请帮忙指导。
2个回答

5
远程会话无法访问您在本地定义的变量。您可以使用$using:variable引用它们。
Invoke-Command -Session $psSession -ScriptBlock { $using:websiteNames | foreach{ Stop-Website -Name $_ } }
Invoke-Command -Session $psSession -ScriptBlock { $using:websiteNames | foreach{ Start-Website -Name $_ } }

更多关于远程变量的信息,请参见 about_remote_variables 的帮助文档:

get-help about_remote_variables -Full

0

实际上只需要将参数传递给-ScriptBlock-ArgumentList,并使用$args在函数块内引用它:

Invoke-Command -Session $psSession -ScriptBlock { $args | foreach{ Stop-Website -Name $_ } } -ArgumentList $websiteNames
Invoke-Command -Session $psSession -ScriptBlock { $args | foreach{ Start-Website -Name $_ } } -ArgumentList $websiteNames

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接