这可能听起来有点傻,因为我并不是一个普通的批处理脚本程序员。
如何扩展字符串内的任何环境变量并将最终扩展的输出存储到另一个变量中,如下所示:
@echo off
set P1="%SYSTEMROOT%\Temp"
echo %%P1%%
这应该会在退出前打印“C:\Windows\Temp”。如果我先将脚本提升为管理员,然后运行相同的代码,这也应该有效,如下所示:
@echo off
net file 1>nul 2>nul && goto :RunAsAdmin^
|| powershell -ex unrestricted -Command "Start-Process -Verb RunAs -FilePath '%comspec%' -ArgumentList '/c %~fnx0 %*'"
goto :eof
:RunAsAdmin
set P1="%systemroot%\Temp"
echo %%P1%%
应打印与上面相同的输出。有人能帮我找出我做错的地方吗?
PS 我问这个问题是因为我想通过在变量中声明路径并在下面的命令中重用该变量来智能地清除系统临时目录:
set P1="%systemroot%\Temp" && del /f /s /q %%P1%%\*.* && rd /s /q %%P1%%\*
答案1
- 只需替换....
1)%comspec%
+-ArgumentList '/c
+%~fnx0 %
到:
Start-Process $env:windir\system32\cmd.exe -Verb RunAs -Argument $env:cmd_arg
2)您的电源外壳命令不需要引号,请删除它们
%__APPDIR__%\WindowsPowerShell\v1.0\powershell.exe -ex unrestricted -Command Start-Process $env:windir\system32\cmd.exe -Verb RunAs -Argument $env:cmd_arg
3)从中删除引号/半引号'/c %~fnx0 %*'
并替换为$env:cmd_arg
4)对于%%P1%%
,尝试使用:
cmd /v /c "echo !P1!"
call echo/ %P1%
echo/ %P1%
echo= %P1%
echo[ %P1%
echo( %P1%
echo. %P1%
@echo off && setlocal EnableDelayedExpansion
title <nul && Title ...\%~nx0
%__APPDIR__%mode.com con: cols=99 lines=3
for %%i in (%*)do set "_arg=!_arg! "%%~i" "
set "cmd_arg= /v /c "%~fnx0" !_arg!" && %__APPDIR__%Net.exe file 2>nul >nul && (
goto :RunAsAdmin
) || (
color 9f & echo/ Running your PowerShel cmdlets...
set "_ps1=%__APPDIR__%\WindowsPowerShell\v1.0\powershell.exe"
!_ps1! -ex unrestricted -Command Start-Process $env:windir\system32\cmd.exe -Verb RunAs -Argument $env:cmd_arg
echo/ Press any key to exit... && %__APPDIR__%timeout.exe -1 >nul & endlocal && goto :EOF
)
echo/ If you see this, sorry it doesn't work... && goto :EOF
:RunAsAdmin
%__APPDIR__%mode.com 99,25 && color 0A
echo/If you see this one, it works sr. Admin^!!...
title <nul && Title ...\%~nx0
rem :: do your admin tasks here....
echo/ Press any key to exit... && %__APPDIR__%timeout.exe -1 >nul
endlocal && goto :EOF