Steven
Steven

Reputation: 2558

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.

Upvotes: 1

Views: 2265

Answers (3)

David Brabant
David Brabant

Reputation: 43459

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

Upvotes: 2

BartekB
BartekB

Reputation: 8650

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

Upvotes: 1

dbenham
dbenham

Reputation: 130809

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

Upvotes: 3

Related Questions