简体   繁体   中英

PowerShell from a batch file using relative path

I have a batch file that launches a PowerShell script with elevated privileges and bypasses execution policy:

PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File ""C:\Users\Bob\Desktop\New folder\Server.ps1""' -Verb RunAs}";

This works Yea! I want to be able to use relative paths for the file path.

PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File "".\Server.ps1""' -Verb RunAs}";

This fails for some reason. What am I doing wrong?

If your PowerShell script is not present at the location where cmd is pointing to, you will get an error as the relative path searches in that directory. If the PS script is present in the same location of the batch script, you can invoke PS script from the batch as follows:

Powershell "%~dp0Server.ps1"

If PowerShell and batch script locations are variant, first you need to change the directory in the batch before invoking PowerShell script as follows:

cd /d "C:\Users\Bob\Desktop\New Folder\"
Powershell -NoProfile .\Server.ps1
PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -Command "Set-Location \"%~dp0\"; \".\Server.ps1\"' -Verb RunAs}"

The -Verb RunAs forces the new Powershell process to change directory to the system directory. You can use set-location to change it to the batch-file script directory using %~dp0 .

The argument -WorkingDirectory appears to be ignored when -Verb RunAs is used so seems obsolete for this task.

You can view this example to see that current directory or changing directory before the Powershell process has no effect on the new elevated Powershell process:

cd /d "%~dp0"
PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -Command \"Get-Location; Start-Sleep 10\"' -Verb RunAs}"

which outputs:

 Path ---- C:\\Windows\\system32

so you may need to change directory in the elevated Powershell process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM