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

问题描述 投票:0回答:2

我编写了一个脚本来重新启动远程服务器上的一些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'的参数。参数为null。为参数提供有效值,然后再次尝试运行该命令。

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

powershell remote-access
2个回答
1
投票

远程会话无法访问您在本地定义的变量。它们可以用$using:variable引用

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

0
投票

实际上只需要将参数传递给-ArgumentList-ScriptBlock并使用$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
© www.soinside.com 2019 - 2024. All rights reserved.