【发布时间】:2021-09-12 03:41:07
【问题描述】:
我需要使用在我的计算机上运行的 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 中执行此操作时,为什么还要调用 cmd?
-ScriptBlock { bcdedit /copy {current} /d "Description" } -
因为 bcdedit /copy {current} /d "Description" 在 powershell 中不起作用。它只适用于 cmd
-
应该可以,powershell显然可以运行任何exe文件。但可能你需要引用
{},因为这些是特殊字符:-ScriptBlock { bcdedit /copy{current}` /d "Description" }` -
很高兴您发现了您的特定远程问题,如您自己的回答中所解释的那样,但由于该解决方案特定于您的环境 - 并且只是一个 i> 基于您问题中描述的症状的可能解决方案 - 这并不是那么有帮助(并且需要将
-Credential参数传递给Restart-Computer也与您的问题相矛盾)。因此,我鼓励您accept 提供一般背景和故障排除信息的答案。
标签: powershell cmd powershell-remoting cmdlet