Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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";
}
like image 943
Rahul Gupta Avatar asked Sep 13 '25 19:09

Rahul Gupta


2 Answers

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"
like image 107
junkangli Avatar answered Sep 15 '25 13:09

junkangli


Start-Process 'cmd' -Credential $cred -ArgumentList "/c $command" -WorkingDirectory $startingDirectory
like image 24
truedge Avatar answered Sep 15 '25 15:09

truedge