Home > database >  running Powershell in batch file failed because of special character "|"
running Powershell in batch file failed because of special character "|"

Time:02-12

I recently started to some scripts in batch file to do some works but I failed when I tried to get some results from PowerShell then process it.

@echo off
setlocal

set "ps= $FindProcess = Get-Process | Where-Object {$_.MainWindowTitle -like 'VNC viewer'};"
set "ps=%ps% $title = $FindProcess.MainWindowTitle ^| Measure-Object -Line;"
set "ps=%ps% $title.Lines"

echo %ps%
for /f "delims=" %%I in ('powershell "%ps%"') do set "title=%%I"
:: For debugging and get the result
:: for /f "delims=" %%I in ('powershell "%ps%"') do echo %%I

echo %title% number of apps have "VNC viewer" title

but when run it i throw 'Where-Object' is not recognized as an internal or external command, operable program or batch file. and when put ^ before | it result empty %title% and when uncommenting the debug section I shows this error

 $FindProcess = Get-Process | Where-Object {$_.MainWindowTitle -like 'VNC viewer'}; $title = $FindProcess.MainWindowTitle | Measure-Object -Line; $title.Lines
At line:1 char:124
  ...  -like 'VNC viewer'}; $title = $FindProcess.MainWindowTitle ^| Measur ...
                                                                  ~
Unexpected token '^' in expression or statement.
      CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
      FullyQualifiedErrorId : UnexpectedToken
ECHO is off.
 number of apps have "VNC viewer" title

CodePudding user response:

I find out removing echo %ps% and do not putting ^ before | makes it work successfully but still don't know why echo it throws error!

Edited: After reading aschipfl comment I finally understood why. Actually echo %ps% will be parse to echo what-was-is-variable-which-in-this-case-has-|-character and this command also won't work without double quotation :) thank you

  • Related