[英]Passing Powershell from Cmd with variable evaluation
我想使用以下命令
powershell -command "get-content %CONFIG_FILE% | %{$_ -replace \"APP_PATH=.+\",\"APP_PATH=%APP_DIR%\"}"
但是通過使用批處理腳本中定義的 %CONFIG_FILE% 和 %APP_DIR% 的評估
set CONFIG_FILE=C:\B0_GW.cfg
set APP_DIR=C:\dbg\kernel
當我這樣做時,我目前遇到以下問題:
該字符串缺少終止符:“。
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullQualifiedErrorId : TerminatorExpectedAtEndOfString
有任何想法嗎?
aschipfl在對該問題的評論中提供了關鍵指針:
在批處理文件[1] 中,您必須將要傳遞到目標應用程序的%
字符轉義為%%
。
否則, cmd
將%
解釋為環境變量引用的開始或結束(這部分是在您的命令中設計的;例如, %CONFIG_FILE%
)。
(對於PowerShell,您已經正確地將命令中嵌入的"
字符"
轉義為“ \\"
)。
具體來說, %
在%{...}
你的命令需要部分逸出( %
是PowerShell中的內置別名ForEach-Object
cmdlet的):
powershell -command "get-content %CONFIG_FILE% | %% {$_ -replace \"APP_PATH=.+\",\"APP_PATH=%APP_DIR%\"}"
或者,只需使用 cmdlet 的實際名稱ForEach-Object
,這樣就不需要轉義:
powershell -command "get-content %CONFIG_FILE% | ForEach-Object {$_ -replace \"APP_PATH=.+\",\"APP_PATH=%APP_DIR%\"}"
[1] 遺憾的是, cmd.exe
的命令提示符(在交互式會話中)的行為有所不同 - 請參閱此答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.