2012-05-17 110 views
1

我需要一个行脚本,做这样的事情: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的命令运行。

回答

3

BartekB的答案作品只要至少有一行输出不以FOR/FOL字符开始(默认为;),并且不完全由分隔符(缺省为空格和制表符)组成。有了适当的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 
1

我想如果不会是最好的解决方案。我会用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 
2

第三种方法:从PowerShell脚本中设置一个环境变量并在批处理文件中测试它?