我有一个非常简单的Powershell脚本,可以远程启动服务。
Invoke-Command -Session $session -ScriptBlock { Start-Service "My test service v1" }
工作正常,但
$myval="My test service v1"
Invoke-Command -Session $session -ScriptBlock { Start-Service $myval }
失败于
Cannot validate argument on parameter 'InputObject'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again. + CategoryInfo : InvalidData: (:) [Start-Service], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartServiceCommand + PSComputerName : mdfiletest
对我来说,它们是相同的。为什么这不起作用?谢谢
最佳答案
它不起作用,因为在远程服务器上执行脚本块时, session 状态中不存在变量$myval
;它仅存在于本地(客户端)端。与Powershell v2 / v3兼容的方法是:
invoke-command -session $session -scriptblock {
param($val); start-service $val } -args $myval
另一种Powershell v3(仅)方式是这样的:
invoke-command -session $session -scriptblock { start-service $using:myval }
$using
前缀是一个特殊的伪作用域,它将捕获局部变量并尝试对其进行序列化并远程发送。字符串始终可序列化(可删除)。
关于powershell - Powershell启动服务失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14574607/