4

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";
}
Clijsters
  • 4,031
  • 1
  • 27
  • 37
Rahul Gupta
  • 201
  • 2
  • 4
  • 10
  • @Clijsters thanks for making it more readable. I will make sure, next time i post a question will post it in correct, ordered and fashioned manner. – Rahul Gupta May 16 '18 at 17:54

2 Answers2

6

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"
junkangli
  • 1,152
  • 7
  • 14
  • Indeed: Just to spell out the difference: `/c` executes the given command and then _exits_, `/k` keeps the session open. – mklement0 May 09 '23 at 14:04
0
Start-Process 'cmd' -Credential $cred -ArgumentList "/c $command" -WorkingDirectory $startingDirectory
truedge
  • 1
  • 3
  • Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?** – Jeremy Caney Jun 09 '23 at 00:51
  • You should add explanation. – Super Kai - Kazuya Ito Jun 09 '23 at 09:28