使用远程会话调用命令:无法验证参数上的参数

Eho*_*ret 3 powershell remote-access

我编写了一个脚本来重新启动远程服务器上的一些 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 
Run Code Online (Sandbox Code Playgroud)

由于某些原因我Invoke-Command无法正常运行,出现以下错误消息:

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

当命令在 a 之后运行时,Enter-PSSession它在 a 中工作正常,-ScriptBlock但它有点搞乱了-Name参数,知道如何解决这个问题吗?

Mik*_*elo 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 $_ } }
Run Code Online (Sandbox Code Playgroud)

帮助中的更多信息about_remote_variables

get-help about_remote_variables -Full
Run Code Online (Sandbox Code Playgroud)