1

我需要运行这 4 个命令来将新映像引导到设备中:

bcdedit /copy {current} /d "Describe"
bcdedit /set {guid} osdevice vhd=somepath 
bcdedit /set {guid} device vhd=somepath
bcdedit /default {$guid} 

为了自动化我的脚本,我想提取作为第一个命令的输出返回的 guid/标识符,并将其作为参数传递给其他 3 个命令。现在,我正在这样做:

$guid = Invoke-Command -ComputerName $comp -Credential $cred -ScriptBlock {cmd /c "bcdedit /copy {current} /d "Describe""}

#output
#$guid = This entry was successfully copied to {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}

$guid = $guid.Replace("This entry was successfully copied to {","")
$guid = $guid.Replace("}","")

$path1 = "xxx/xxxx/...."

#passing the guid and path as inputs
Invoke-Command -ComputerName $comp -Credential $cred -ScriptBlock {cmd /c "bcdedit /set {$guid} osdevice vhd=$path1"}
Invoke-Command -ComputerName $comp -Credential $cred -ScriptBlock {cmd /c "bcdedit /set {$guid} device vhd=$path1"}
Invoke-Command -ComputerName $comp -Credential $cred -ScriptBlock {cmd /c "bcdedit /default {$guid} "}

但是,每次我得到一个错误:

元素数据类型无法识别,或不适用于指定条目。运行“bcdedit /?” 用于命令行帮助。未找到元素

当我在 UI 中手动复制和粘贴路径时,这很好用,但我不确定如何自动化它。

4

1 回答 1

1
  • 正如对您先前问题的回答中所解释的那样,不需要使用cmd /c来调用bcdedit- 所需要的只是引用包含{and的文字参数},因为这些字符在不带引号的情况下在 PowerShell 中具有特殊含义。

    • 通过调用cmd /c不仅效率低下(尽管在实践中这并不重要),而且还会引入引用问题。[1]
  • 传递给远程Invoke-Command -ComputerName ...执行的脚本块,因此无法访问调用者的变量;从调用者的作用域中包含变量值的最简单方法是通过作用域(参见这个答案)。$using:

所以:

$guid = Invoke-Command -ComputerName $comp -Credential $cred -ScriptBlock { 
  bcdedit /copy '{current}' /d "Describe" 
}

# Extract the GUID from the success message, which has the form
# "This entry was successfully copied to {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"
$guid = '{' + ($guid -split '[{}]')[1] + '}'

$path1 = "xxx/xxxx/...."

# Passing the guid and path as inputs, which must
# be done via the $using: scope.
Invoke-Command -ComputerName $comp -Credential $cred -ScriptBlock { 
  bcdedit /set $using:guid osdevice vhd=$using:path1
  bcdedit /set $using:guid vhd=$using:path1
  bcdedit /default $using:guid
}

[1] 例如,cmd /c "bcdedit /copy {current} /d "Describe""不像你认为的那样工作;它必须是cmd /c "bcdedit /copy {current} /d `"Describe`""

于 2021-07-03T01:52:11.097 回答