powershellcmdcommand-promptcommand-line-argumentswindows-nt

Run with elevated rights a PowerShell script, with spaces in path, from Windows Command Prompt (CMD)


I tried to launch a long PowerShell script with the name "long name here.ps1" from command prompt. But I am also trying to ensure that it runs as an administrator command in PowerShell. I have all execution policies in PowerShell set accordingly and I used the SS64 Set-ExecutionPolicy command guide for PowerShell to get PowerShell working. But I am trying to use the solution from another Stack Overflow question that talks about running commands as administrator. I am running a batch script that needs to execute a PowerShell script (.ps1) as admin, and I don't mind if the user is prompted by UAC or for the password.

I am currently using the following command:

powershell.exe -command "&{ Start-Process powershell -ArgumentList '-noprofile -file "C:\long name here.ps1"' -verb RunAs}"

I found a similar command in the "Run a Script As Admin" at https://ss64.com/ps/powershell.html. The problem with that code is that my PowerShell script has arguments and a long name with spaces. I have tried many different iterations of this command with no success, and the ones that DON'T work are listed below:

powershell.exe -command "&{ Start-Process powershell -ArgumentList '-noprofile -file C:\long\` name` here.ps1' -verb RunAs}"
powershell.exe -command "&{ Start-Process powershell -ArgumentList '-noprofile -file:"C:\long name here.ps1' -verb RunAs}"

Also, I am completely lost as to how to send arguments to the actual script.


Solution

  • When you use PowerShell.exe -Command you don't need to use quotes. For example, you can run the following:

    PowerShell.exe -Command Get-Service 'wuauserv'
    

    Everything after -Command is interpreted as the command. Note also that double quotes in CMD need escaping with a backslash. Therefore:

    powershell.exe -Command Start-Process PowerShell -ArgumentList '-NoProfile -File \"C:\long name here.ps1\"' -Verb RunAs
    

    If your file has arguments:

    powershell.exe -Command Start-Process PowerShell -ArgumentList '-NoProfile -File \"C:\long name here.ps1\" \"Arg1\" \"Arg2\"' -Verb RunAs