问题描述
我需要使用在我的计算机上运行的 PowerShell 脚本在远程计算机的 cmd 上运行几个 bcdedit 命令。我能够创建一个 PSSession,但我不确定如何在远程计算机上运行 cmd。当我在“Invoke-Command”行中运行代码时,出现错误 Connection to Remote Server Failed with the following error message: Access is denied.
当我刚运行 Invoke-Command 时,系统提示我输入 ScriptBlock,但是当我这样做时,我又收到另一个错误: "无法绑定参数 'ScriptBlock' 无法将 System.String 类型的 "cmd /c 'bcdedit /copy {current} /d "Description"'} 值转换为 System.Management.Automation.ScriptBlock 类型
我以前从未使用过 PowerShell。我需要在几个小时内完成这项工作,而我现在完全无能为力。
Enable-PSRemoting -Force
Set-Item WSMan:\localhost\Client\TrustedHosts $ip -Concatenate -Force
$session = New-PSSession -ComputerName $ip -Credential $cred -ConfigurationName $config -UseSSL -Sessionoption $sessopt
#problematic code
Invoke-Command -ComputerName $ip -ScriptBlock {cmd /c 'bcdedit /copy {current} /d "Description"'}
#works fine
Restart-Computer -ComputerName $ip -Force
ping.exe -t $ipaddr | Foreach{"{0}-{1}" -f (Get-Date -f "yyyy/MM/dd HH:mm:ss"),$_}
假设 $ip、$ipaddr、$config、$sessopt 和 $cred 存储有效参数。
解决方法
-
你可以直接在PowerShell中运行
bcedit.exe
,但是因为在PowerShell中{
和}
是元字符,您需要引用标识符,例如{current}
:bcdedit /copy '{current}' /d 'Description'
- 有关 PowerShell 元字符的讨论和列表,请参阅 this answer。
-
如果您在连接到远程计算机时遇到错误,这意味着您的用户帐户要么没有足够的权限来远程连接或 目标计算机未设置为 PowerShell 远程处理。
-
请注意,
Enable-PSRemoting -Force
必须在目标(服务器)机器上运行,而不是在调用(客户端)机器。 -
查看概念性的 about_Remote_Troubleshooting 主题。
-
Restart-Computer
cmdlet 的-ComputerName
参数不使用 PowerShell 远程处理,因此它成功的事实不意味着 PowerShell远程处理,例如通过Invoke-Command
,有效。
-
当我刚运行 Invoke -Command 时,提示我输入 ScriptBlock
PowerShell 对未在命令行中指定的强制 参数值的自动提示功能有严重的限制,无法提示输入 script-block 参数值就是其中之一- 见GitHub issue #4068;但是,这个额外的问题与您的实际问题偶然。
,感谢所有建议,我能够通过将 -Credential 添加到 Invoke-Command 和 Restart-Computer 命令来修复错误:
#problematic code
Invoke-Command -ComputerName $ip -Credential $cred -ScriptBlock {cmd /c 'bcdedit /copy {current} /d "Description"'}
Restart-Computer -ComputerName $ip -Credential $cred -Force