我正在尝试使用下面的批处理文件,该文件在计算机上找到 CD 驱动器,并希望从 CD 启动 powershell 脚本并在此文件夹中运行。这是批处理文件。
@echo off
setlocal
for /f "skip=1 tokens=1,2" %%i in ('wmic logicaldisk get caption^, drivetype') do (if [%%j]==[5] pushd %%i)
cd WIN2k8\Non-Supressed\
start powershell -NoLogo -NoProfile -WindowStyle Maximized -NoExit -ExecutionPolicy Bypass -File .\PatchTest.ps1
echo Press Space Bar to continue
pause
endlocal
答案1
尝试在一个位置使用批处理文件并调用提升的 powershell 脚本
根据我测试和确认的内容,您可以使用以下语法完成您想要执行的操作。我将一些技术融入到您的逻辑中,就像您过去解释的那样,我使用其他 PowerShell 和批处理文件处理解决方案完成此类操作的方式也是如此。
我在变量WIN2k8\Non-Supressed
后面附加了路径%~j
,因此循环将使用变量FOR /F
的完整路径( ),以便稍后使用该变量作为正在执行的 PowerShell 脚本的完整路径。按照此方法无需使用该命令。SET
FPath
PUSHD
我还使用显式CD /D
到 PowerShell 应用程序 Windows 目录,从那里调用 PowerShell,然后从那里传递参数、命令、开关等——使用 PowerShell 脚本的完整路径(即-ExecutionPolicy Bypass -Command "& '%FPath%\PatchTest.ps1'"
)。
批处理脚本示例
@ECHO ON
SETLOCAL
FOR /F "SKIP=1 TOKENS=1,2" %%i IN ('"wmic logicaldisk get caption, drivetype"') DO (IF [%%~j]==[5] SET FPath="%%~i\WIN2k8\Non-Supressed")
SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0
CD /D "%PowerShellDir%"
Powershell -ExecutionPolicy Bypass -Command "& '%FPath%\PatchTest.ps1'"
ECHO Press Space Bar to continue
PAUSE
ENDLOCAL
更多资源
答案2
下列的评论 .bat
脚本应该检查机器上的所有 CD 驱动器和:
如果插入介质和插入的介质包含预期文件夹然后运行升高powershell 会话,将位置更改为此文件夹并从其中运行指定的脚本:
@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
rem set initial values
set "_folder=WIN2k8\Non-Supressed"
set "_folder=content\recipes\cze_CZE" my testing value
SET "_fullPath=" necessary
FOR /F "SKIP=1 TOKENS=1-5" %%i IN ('
"wmic logicaldisk get Caption, DriveType, Size, SystemName, VolumeSerialNumber" ') DO (
rem next test: is CD/DVD? could be omitted using `wmic … Where "DriveType=5" get …`
IF [%%~j]==[5] (
rem next test: medium inserted?
IF NOT [%%~m]==[] (
rem next test: right medium inserted?
if exist "%%~i\%_folder%\" (
SET "_fullPath=%%~i\%_folder%"
)
)
)
)
rem set auxiliary values to keep final `PowerShell` line in a reasonable length
set "_elevate=Start-Process PowerShell -Verb RunAs"
set "_torun=.\PatchTest.ps1"
set "_torun=Get-Childitem 81*;pause" my testing value
set "_arguments='Push-Location -literalPath ''"%_fullPath%"'';%_torun%'"
IF defined _fullPath (
PowerShell %_elevate% -ArgumentList %_arguments%
)
pause
答案3
此批处理将在评估 cd 驱动器之前提升自身(如有必要),然后运行 powershell 脚本。
@echo off
setlocal
::Check if elevated
net file 1>nul 2>&1 || (powershell -ex ByPass -Command ^
"Start-Process -Verb RunAs -FilePath '%comspec%' -ArgumentList '/c %~f0 %*'"
goto :eof
)
:: Put code here that needs elevation
Set "CDPath=\WIN2k8\Non-Supressed\"
Set "Script=PatchTest.ps1"
for /f %%i in (
'wmic logicaldisk where "DriveType=5" get caption^, drivetype^|findstr ":"'
) do IF exist "%%i%CDPath%Script%" Set "CDPath=%%i%CDPath%" & Goto :Found
Echo Can't locate CD drive / script
Pause
Goto :Eof
:Found
PushD "%CDPath%"
start powershell -NoLogo -NoProfile -WindowStyle Maximized -NoExit -Ex Bypass -File .\PatchTest.ps1
echo Press Space Bar to continue
pause
endlocal