[英]Pass variable string command to powershell -Command
我需要運行這個從另一個腳本讀取的命令。
$command = "$arr = @($input)
$arr.count
Write-Host $arr[0]"
"Classical Music for When You are on a Deadline." | & cmd /C powershell -Command {$command}
所以我通過 pipe 得到了一些東西,然后我在我的字符串命令中使用它。 該代碼不起作用,因為$command
未擴展為調用中的字符串,因此在啟動的 powershell 命令中未知。
這些按預期工作,但命令不是從字符串中獲取的:
"Classical Music for When You are on a Deadline." | & cmd /C powershell -Command {Invoke-Expression "Write-Host $input"}
# No: System.Management.Automation.Runspaces.PipelineReader`1+<GetReadEnumerator>d__20[System.Object]
# "Classical Music for When You are on a Deadline." | & cmd /C powershell -Command {Write-Host $input}
"Classical Music for When You are on a Deadline." | & cmd /C powershell -Command {$arr = @($input)
$arr.count
Write-Host $arr[0]}
{ $command }
不會將字符串$command
的值轉換為腳本塊- 它只是創建一個引用名為$command
的變量的腳本塊。
[scriptblock]::Create()
另外,不要通過cmd /c
調用powershell.exe
- 通常沒有必要。
所以:
$command = '$arr = @($input)
$arr.count
Write-Host $arr[0]'
"Classical Music for When You are on a Deadline." |
powershell ([scriptblock]::Create($command)) # -Command is implied.
筆記:
以上是您問題中最后一次解決方案嘗試的動態的、基於變量的等價物。
在 PowerShell 的 CLI 中使用腳本塊而不是字符串——這只是 PowerShell內部的一個選項——通常更可取,原因如下:
換句話說:雖然powershell -Command $command
可以使用特定的示例字符串,但如果字符串包含"
字符,它將失敗,總是在 Windows PowerShell 中,並且至少達到 PowerShell(核心)7.2.x。
退一步說:既然你已經在 PowerShell 中運行了,就沒有必要再創建一個實例作為子進程了,這是很昂貴的。
$command = '$arr = @($input)
$arr.count
Write-Host $arr[0]'
# Invoke the dynamically created script block directly.
"Classical Music for When You are on a Deadline." |
& ([scriptblock]::Create($command))
筆記:
您可以使用 Invoke-Expression cmdlet 在 PowerShell 中將變量字符串作為命令運行。例如: Invoke-Expression $commandString
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.