1

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.

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

Third way: set an environment variable from your PowerShell script and test it in your batch file?

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.