1

I am trying to run a script on remote using PowerShell. The script starts a service and works perfectly when I execute it using RDP. I try

PS C:\Users\me> Invoke-Command -ComputerName '123.123.123.123' -Credential $cred -ErrorAction stop -ScriptBlock { Start-Process -FilePath 'C:\someDir\StartService.bat' -Verb RunAs }

I get no error message and the script seems to run, but the service does not start. Any idea?

4
  • What happens if you run it with ... -ScriptBlock { C:\someDir\StartService.bat } instead? Commented Jul 19, 2024 at 10:36
  • invoke-command computer1,computer2,computer3 script.ps1 Commented Jul 19, 2024 at 11:24
  • I made it work using a New-PSSession and the used it like Invoke-Command -Session $session .... Commented Jul 19, 2024 at 13:11
  • @AndreasInfo, I'm assuming that the batch file you're trying to invoke runs quickly, so direct invocation is the simplest solution and also more robust solution (you can capture and relay output as well as the process exit code; there's generally rarely a good reason to invoke batch files and external programs with Start-Process - see this answer). The New-PSSession approach is only needed if you want to deliberately start a remote process asynchronously and check for completion later (clean up with Remove-PSSession afterwards). Commented Jul 20, 2024 at 11:10

2 Answers 2

1

Obviously don't know whats in the batch file but; Why use a batchfile if you can start a service directly with powershell useing "start-service"?

Sign up to request clarification or add additional context in comments.

Comments

1

Invoke your batch file directly - and therefore synchronously - in the remote session, which should run with elevation by default:

Invoke-Command -ComputerName '123.123.123.123' -Credential $cred `
               -ErrorAction stop -ScriptBlock { & 'C:\someDir\StartService.bat' }

If you had to use Start-Process - which isn't necessary here - you'd have to additionally use -Wait to ensure that the batch file runs to completion before the Invoke-Command call returns; otherwise, the cmd.exe process running the batch file is aborted.

See this answer for background information.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.