在批处理脚本条件下的PowerShell命令

我需要一些脚本来做这样的事情:

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 / FOL字符开始(默认为; ),并且不完全由分隔字符组成(默认为空格和制表符),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