Running cmd.exe through start-process but unable to pass the command to cmd.exe

Rahul Gupta picture Rahul Gupta · May 16, 2018 · Viewed 11.1k times · Source

I want to run a groovy script with cmd.exe under a different user.

I have used Start-Process, when the script gets executed it just opens the prompt on the screen with different user but doesn't process the $command.

So my question is "How to pass the command after running cmd.exe with PowerShell?

This is what I have so far:

$username = "abc"
$pwd = ConvertTo -SecureString "xyz" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username $pw

$command = "filepath/.groovy"

try {
    Start-Process 'cmd' -Credential $cred -ArgumentList $command
    Write-Host $LASTEXITCODE
    if($LASTEXITCODE -ne 0) {
        throw "Error occured"
    } else {
        return 0
    }
} catch {
    Write-Error "Error Desc:$_Error.InnerException.Message";
}

Answer

junkangli picture junkangli · May 16, 2018

Based on CMD documentation, you can specify the parameter /c or /k to carry out the command.

Start-Process 'cmd' -Credential $cred -ArgumentList "/c $command"