我编写了一个脚本来重新启动远程服务器上的一些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
参数,任何想法如何解决这个问题?
远程会话无法访问您在本地定义的变量。它们可以用$using:variable
引用
Invoke-Command -Session $psSession -ScriptBlock { $using:websiteNames | foreach{ Stop-Website -Name $_ } }
Invoke-Command -Session $psSession -ScriptBlock { $using:websiteNames | foreach{ Start-Website -Name $_ } }
实际上只需要将参数传递给-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