chatmandu
chatmandu

Reputation: 19

Create .bat file to run powershell 'as user' and then execute .ps1 file

I need to create a .bat file that can run a powershell script using a specific account.

This command will run powershell as the user:

runas /user:domain\user "C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe"

The user is prompted to enter the account password and powershell launches.

Is there a way to have it automatically run a ps1 file once authentication is completed?

C:\Temp\script.ps1 

Thanks.

** Edit **

As per the comments, I have changed to powershell.exe.

This command isn't working.

runas /user:domain\user "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -file C:\Temp\script.ps1

It returns a RUNAS error and doesn't ask for the user's password.

Upvotes: 0

Views: 82

Answers (1)

mklement0
mklement0

Reputation: 439822

  • In order to execute PowerShell commands from a command line launched from outside PowerShell, you must use powershell.exe, the Windows PowerShell CLI.

    • By contrast, powershell_ise.exe is the executable of the obsolescent Windows PowerShell ISE. While it offers a CLI (startup parameters) too, they only support opening script files for editing, not for execution.
  • A command line passed to runas.exe for execution as a different user must be specified as a single string (argument); that is, enclose both the target executable and its arguments in "..."

Therefore (full path to powershell.exe omitted for brevity):

runas /user:domain\user "powershell.exe -File C:\Temp\script.ps1"

Note:

  • If necessary, place -ExecutionPolicy RemoteSigned before -File in order to ensure that execution of the script is permitted, namely in case the execution policy in effect for the target user prevents script execution, but note that this process-level override won't work if the execution policy is controlled via GPOs (Group Policy Objects); see this answer for details.

  • Should the command line to pass require embedded " chars. (e.g. for a *.ps1 path that contains spaces), escape them as \".

Upvotes: 1

Related Questions