我已经看到批处理宏不工作-但它没有解决我的问题。
基本上,我看到:
- 将命令的输出设置为变量(带有管道)
- 使用MS批处理文件将程序输出分配给变量
…我想,让我试试。
首先,我把它保存在一个test.bat
文件中:
powershell -command "$proc = Start-Process notepad.exe -passthru ; Write-Output $proc.id"
pause
我双击这个test.bat
,得到:
C:tmp>powershell -command "$proc = Start-Process notepad.exe -passthru ; Write-Output $proc.id"
10968
C:tmp>pause
Press any key to continue . . .
那么,好的,它工作了。
然后我决定将上面的代码包装在一个"批处理宏"中。-所以test.bat
变成:
%$set% TESTPID="powershell -command "$proc = Start-Process notepad.exe -passthru ; Write-Output $proc.id""
echo TESTPID %TESTPID%
pause
现在当我双击这个test.bat
时,它不起作用,我得到:
C:tmp>TESTPID="powershell -command "$proc = Start-Process notepad.exe -passthru ; Write-Output $proc.id""
'TESTPID' is not recognized as an internal or external command,
operable program or batch file.
C:tmp>echo TESTPID
TESTPID
C:tmp>pause
Press any key to continue . . .
这就好像%$set%
被解释为一个变量,因此被视为空,然后执行该行的其余部分…
那么,我哪里出错了-我可以得到这个"批处理宏"在这种情况下起作用,如果是,怎么起作用?
好的,事实证明,这是我应该复制的整个函数-否则我被说服%$set%
是一个特殊的内置批处理命令…
@echo off
call :initMacro
%$set% TESTPID="powershell -command "$proc = Start-Process notepad.exe -passthru ; Write-Output $proc.id""
echo TESTPID %TESTPID[0]%
pause
:initMacro
if "!!"=="" (
echo ERROR: Delayed Expansion must be disabled while defining macros
(goto) 2>nul
(goto) 2>nul
)
(set LF=^
%=empty=%
)
(set n=^^^
%=empty=%
)
set $set=FOR /L %%N in (1 1 2) dO IF %%N==2 ( %n%
setlocal EnableDelayedExpansion %n%
for /f "tokens=1,* delims== " %%1 in ("!argv!") do ( %n%
endlocal %n%
endlocal %n%
set "%%~1.Len=0" %n%
set "%%~1=" %n%
if "!!"=="" ( %n%
%= Used if delayed expansion is enabled =% %n%
setlocal DisableDelayedExpansion %n%
for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %n%
if "!!" NEQ "" ( %n%
endlocal %n%
) %n%
setlocal DisableDelayedExpansion %n%
set "line=%%O" %n%
setlocal EnableDelayedExpansion %n%
set pathExt=: %n%
set path=; %n%
set "line=!line:^=^^!" %n%
set "line=!line:"=q"^""!" %n%
call set "line=%%line:^!=q""^!%%" %n%
set "line=!line:q""=^!" %n%
set "line="!line:*:=!"" %n%
for /F %%C in ("!%%~1.Len!") do ( %n%
FOR /F "delims=" %%L in ("!line!") Do ( %n%
endlocal %n%
endlocal %n%
set "%%~1[%%C]=%%~L" ! %n%
if %%C == 0 ( %n%
set "%%~1=%%~L" ! %n%
) ELSE ( %n%
set "%%~1=!%%~1!!LF!%%~L" ! %n%
) %n%
) %n%
set /a %%~1.Len+=1 %n%
) %n%
) %n%
) ELSE ( %n%
%= Used if delayed expansion is disabled =% %n%
for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %n%
setlocal DisableDelayedExpansion %n%
set "line=%%O" %n%
setlocal EnableDelayedExpansion %n%
set "line="!line:*:=!"" %n%
for /F %%C in ("!%%~1.Len!") DO ( %n%
FOR /F "delims=" %%L in ("!line!") DO ( %n%
endlocal %n%
endlocal %n%
set "%%~1[%%C]=%%~L" %n%
) %n%
set /a %%~1.Len+=1 %n%
) %n%
) %n%
) %n%
set /a %%~1.Max=%%~1.Len-1 %n%
) %n%
) else setlocal DisableDelayedExpansion^&set argv=
当我双击.bat文件时,我得到:
TESTPID 17704
Press any key to continue . . .
…