运行 由于特殊字符“|”,批处理文件中的 Powershell 失败
running Powershell in batch file failed because of special character "|"
我最近开始使用批处理文件中的一些脚本来完成一些工作,但是当我尝试从 PowerShell 获取一些结果然后对其进行处理时我失败了。
@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
但是当 运行 它我抛出 'Where-Object' is not recognized as an internal or external command, operable program or batch file.
并且当把 ^
放在 |
之前它结果为空 %title%
当取消注释我显示的调试部分时这个错误
$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
我发现删除 echo %ps%
并且不在 |
之前放置 ^
使其成功运行,但仍然不知道为什么 echo 会抛出错误!
已编辑:
阅读 评论后,我终于明白为什么了。实际上 echo %ps%
将被解析为 echo what-was-in-the-variable-which-in-this-case-has-|-character
并且如果没有双引号,此命令也将无法工作:)谢谢
我最近开始使用批处理文件中的一些脚本来完成一些工作,但是当我尝试从 PowerShell 获取一些结果然后对其进行处理时我失败了。
@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
但是当 运行 它我抛出 'Where-Object' is not recognized as an internal or external command, operable program or batch file.
并且当把 ^
放在 |
之前它结果为空 %title%
当取消注释我显示的调试部分时这个错误
$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
我发现删除 echo %ps%
并且不在 |
之前放置 ^
使其成功运行,但仍然不知道为什么 echo 会抛出错误!
已编辑:
阅读 echo %ps%
将被解析为 echo what-was-in-the-variable-which-in-this-case-has-|-character
并且如果没有双引号,此命令也将无法工作:)谢谢