powershell - Powershell启动服务失败

标签 powershell

我有一个非常简单的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/

相关文章:

security - 通过 Powershell 在 IIS 7.5 中启用模拟

node.js - 如何使用名称前没有 `node` 的 Powershell 执行 node.js 文件?

regex - 从变量中搜索字符串并仅打印其上方的 3 行

powershell - 在 Windows 10 上设置屏幕分辨率

powershell - 为什么使用标志 -Port 587 通过 Send-MailMessage 命令从 PowerShell 发送电子邮件会产生错误?

arrays - Powershell -notin 数组不会触发 if 语句

Powershell:替换文件中特定行上的文本

Powershell将参数值传递给参数并返回

javascript - Electron JS App 仍然有默认图标(使用 electron-windows-store 构建的 .appx 文件)

powershell - 是否可以知道 PowerShell 脚本是从 GUI 还是控制台启动?