使用PowerShell远程访问cmd



我需要使用在我的计算机上运行的PowerShell脚本在远程计算机的cmd上运行几个bcdedit命令。我可以创建一个PSSession,但我不确定如何在远程计算机上运行cmd。当我在"Invoke Command"行中运行代码时,我会得到一个错误Connection to remote server failed with the following error message: Access is denied.当我刚运行Invoke Command时,系统会提示我输入ScriptBlock,但当我这样做时,我还会得到另一个错误:;无法绑定参数"ScriptBlock"无法转换";cmd/c"bcdedit/copy{current}/d";描述"}System.String类型的值转换为System.Management.Automation.ScriptBlock 类型

我以前从未使用过PowerShell。我需要在几个小时内完成这项工作,而我现在完全一无所知。

Enable-PSRemoting -Force
Set-Item WSMan:localhostClientTrustedHosts $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元字符的讨论和列表,请参阅此答案
  • 如果连接到远程计算机时出错,这意味着您的用户帐户没有足够的权限远程连接,或者目标计算机没有设置为PowerShell远程处理

    • 请注意,Enable-PSRemoting -Force必须在目标(服务器(机器上运行,而不是在calling[客户端]机器上运行。

    • 请参阅概念性about_Remote_Troubleshooting主题。

    • Restart-Computercmdlet的-ComputerName参数不使用PowerShell远程处理,因此它成功不这一事实意味着PowerShell远程处理(例如通过Invoke-Command(可以工作。

当我刚运行Invoke-Command时,系统会提示我输入ScriptBlock

PowerShell对未在命令行上指定的强制参数值的自动提示功能有严重限制,无法提示脚本块的参数值就是其中之一-请参阅GitHub问题#4068;然而,这个额外的问题是真实问题的附带问题。

感谢所有的建议,我能够通过在调用命令和重新启动计算机命令中添加-Credential来修复错误:

#problematic code
Invoke-Command -ComputerName $ip -Credential $cred -ScriptBlock {cmd /c 'bcdedit /copy {current} /d "Description"'}
Restart-Computer -ComputerName $ip -Credential $cred -Force

最新更新