简体   繁体   中英

PowerShell command in batch script condition

I need a line of script that does something like this:

if (results from PowerShell command not empty) do something

The PowerShell command is basically

powershell -command "GetInstalledFoo"

I tried if (powershell -command "GetInstalledFoo" != "") echo "yes" but get the error -command was unexpected at this time. Is this possible to accomplish? This command will eventually be run as the command to cmd /k .

BartekB's answer works as long as at least one line of output does not start with the FOR /F eol character (defaults to ; ) and does not consist entirely of delimiter characters (defaults to space and tab). With appropriate FOR /F options it can be made to always work.

But here is a simpler (and I believe faster) way to handle multiple lines of output that should always work.

for /f %%A in ('powershell -noprofile -command gwmi win32_process ^| find /v /c ""') do if %%A gtr 0 echo yes

Another alternative is to use a temp file.

powershell -noprofile -command gwmi win32_process >temp.txt
for %%F in (temp.txt) if %%~zF gtr 0 echo yes
del temp.txt

第三种方法:从PowerShell脚本设置环境变量并在批处理文件中对其进行测试?

I guess if won't be the best solution for that. I would use for /f instead:

for /f %R in ('powershell -noprofile -command echo foo') do @echo bar

That should give you 'bar', while this:

for /f %R in ('powershell -noprofile -command $null') do @echo bar

... should not. In actual .bat/ .cmd file you have to double % (%%R)

or better yet, if you don't want to many bar's returned...:

(for /f %R in ('powershell -noprofile -command gwmi win32_process') do @echo bar) | find "bar" > nul && echo worked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM