[英]PowerShell command in batch script condition
我需要執行以下操作的腳本行:
if (results from PowerShell command not empty) do something
PowerShell命令基本上是
powershell -command "GetInstalledFoo"
我試過if (powershell -command "GetInstalledFoo" != "") echo "yes"
但此時出現錯誤-command was unexpected at this time.
這有可能實現嗎? 該命令最終將作為cmd /k
的命令運行。
只要輸出的至少一行不以FOR / F eol字符(默認為;
)開頭並且不完全由定界符(默認為空格和制表符)組成,BartekB的答案就可以起作用。 使用適當的FOR / F選項,可以使其始終工作。
但是,這是一種處理多行應始終起作用的更簡單(並且我認為更快)的方法。
for /f %%A in ('powershell -noprofile -command gwmi win32_process ^| find /v /c ""') do if %%A gtr 0 echo yes
另一種選擇是使用臨時文件。
powershell -noprofile -command gwmi win32_process >temp.txt
for %%F in (temp.txt) if %%~zF gtr 0 echo yes
del temp.txt
第三種方法:從PowerShell腳本設置環境變量並在批處理文件中對其進行測試?
我想這是否不是最好的解決方案。 我會用for /f
代替:
for /f %R in ('powershell -noprofile -command echo foo') do @echo bar
那應該給你“酒吧”,而與此同時:
for /f %R in ('powershell -noprofile -command $null') do @echo bar
... 不應該。 在實際的.bat / .cmd文件中,您必須將%(%% R)加倍
或者更好的是,如果您不想返回很多酒吧...:
(for /f %R in ('powershell -noprofile -command gwmi win32_process') do @echo bar) | find "bar" > nul && echo worked
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.