Search code examples
powershellbatch-filerelative-path

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?


Solution

  • 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