简体   繁体   English

powershell启动服务失败

[英]powershell Start-Service fails

I have very simple powershell script that starts service remotely. 我有一个非常简单的powershell脚本,可以远程启动服务。

Invoke-Command -Session $session -ScriptBlock { Start-Service "My test service v1" }

works fine but 工作正常但是

$myval="My test service v1"
Invoke-Command -Session $session -ScriptBlock { Start-Service $myval }

fails with 失败了

Cannot validate argument on parameter 'InputObject'. 无法验证参数'InputObject'的参数。 The argument is null or empty. 参数为null或空。 Supply an argument that is not null or empty and then try the command again. 提供非null或空的参数,然后再次尝试该命令。 + CategoryInfo : InvalidData: (:) [Start-Service], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartServiceCommand + PSComputerName : mdfiletest + CategoryInfo:InvalidData :( :) [Start-Service],ParameterBindingValidationException + FullyQualifiedErrorId:ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartServiceCommand + PSComputerName:mdfiletest

To me they are the same. 对我来说他们是一样的。 Why is this not working? 为什么这不起作用? thanks 谢谢

It does not work because when the scriptblock is executed on the remote server, the variable $myval does not exist in session state; 它不起作用,因为当在远程服务器上执行scriptblock时,变量$myval在会话状态中不存在; it only exists on the local (client) side. 它只存在于本地(客户端)端。 The powershell v2/v3 compatible way to do this is: 与PowerShell v2 / v3兼容的方法是:

invoke-command -session $session -scriptblock {
      param($val); start-service $val } -args $myval

Another powershell v3 (only) way is like this: 另一个PowerShell v3(仅)方式是这样的:

invoke-command -session $session -scriptblock { start-service $using:myval }

The $using prefix is a special pseudo-scope which will capture the local variable and try to serialize it and send it remotely. $using前缀是一个特殊的伪范围,它将捕获局部变量并尝试序列化并远程发送。 Strings are always serializable (remotable.) 字符串总是可序列化的(远程)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM