Home > database >  Powershell, calling a script as a different user with multiple arguments in ArgumentList
Powershell, calling a script as a different user with multiple arguments in ArgumentList

Time:04-08

I have a cmd script (which will ultiamtely be a Task scheduler triggered task) that needs to start a new Powershell process as a different user to call an additional script, remote.ps1.

Explanation

The hierarchy is as follows:

1.0 - cmd file, runs powershell:

powershell -ExecutionPolicy Bypass -File %SCRIPT_DIR%\credential.ps1

2.1 - credential.ps1 creates a credential object from an encrypted pwd file of other user created via Powershell ISE Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File object

$username = "myuser"
$securestringpwd = Get-Content -Path "C:\Desktop\pwd" | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PSCredential $username, $securestringpwd

2.2 - ...calls a new powershell process at the end, to execute the remote.ps1 script with the additional arguments

$abc = "example1"
$def = "example2"
$dir = "$env:SCRIPT_DIR"

Start-Process powershell.exe -Credential $credential -ArgumentList @('-ExecutionPolicy"Bypass"', '-File"$dir\remote.ps1"', '$abc', '$def')

I have tested and the credential obj does authenticate successfully and creates a new PS process under the new user.

Problem

I cannot seem to figure out a way to launch a new powershell script file and pass in multiple arguments. I think I can't use ExecutionPolicy within an ArgumentList.

Expected result

What would be the correct method in order for me to run the final remote.ps1 script as the new user while also passing in multiple arguments? Thanks in advance.

Platform: Windows Server 2008 R2

Powershell: $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1

CodePudding user response:

What do you have in remote.ps1 ? I was willing to add a single comment but this will hard to read. I'm not sure but this looks like an issue with the missing spaces and wrong quotes. (inside single quote, variables are not interpreted)

If I run this, with correct quote around the variables that needs to be interpreted, or even without quote as a last example (I added another argument "-noexit" to be able to see the output on the screen and manually define the $credential to get rid of the whole .bat etc. which is working):

$credential = Get-Credential
$abc = "example1"
$def = "example2"
$dir = "c:\temp"
Start-Process powershell.exe -Credential $creds -ArgumentList @('-ExecutionPolicy "Bypass"', '-noexit', "-File ""$dir\remote.ps1""", "$abc", $def)

Then, in the c:\temp\remote.ps1 I only have :

whoami
$args

and the output is, as expected:

DOMAIN\username 
example1
exemple2

NB: I ran the first script from a powershell prompt ran with "-version 2"

  • Related