Vippy
Vippy

Reputation: 1422

PowerShell: Another instance of Start-Process is already running

There are 2 PowerShell scripts that run at startup, 1 is in my control and the other is out of my control.

Both of our scripts use Start-Process. Strange issue is if both of our Start-Process's happen to execute at the same time, I get the following error from my script:

Start-Process : This command cannot be run due to the error: An instance of the service is already running.

Is there a way to see if another "Start-Process" is already running? I know about "Get-Process" but only shows PowerShell running, not which cmdlet is currently running.

I'm not in favor of NOT using Start-Process.

As a temporary workaround, I've told my script to sleep for 60 seconds, but would rather KNOW when the other Start-Process is done.

Here is my code:

$pw = ConvertTo-SecureString -AsPlainText -Force -String "myPassword"
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "Administrator",$pw

$psArgList = "-ExecutionPolicy Bypass","-file"
$psArgList += $args

Start-Process powershell.exe -Wait -Credential $cred -ArgumentList $psArgList

This allows me to run another PowerShell script with full privileges: as Admin with ExecutionPolicy as Bypass.

Upvotes: 0

Views: 1988

Answers (1)

TheMadTechnician
TheMadTechnician

Reputation: 36332

I would like to suggest an alternative. If you are running this at login, why not run it from the Task Scheduler, and run it as the account that you want to use the credentials for? When creating the task you will want to set a few things.

On the General Tab

  • select the account you want to run the task as
  • tell it to "Run whether user is logged on or not"
  • select "Run with highest privileges"

On the Triggers Tab

  • Create a trigger so that the even happens "At log on" and select what users, or leave it to happen for any user (default)

On the Actions Tab

  • Create an action
  • For the Application simply put powershell.exe (use the full path if you so desire)
  • Enter your arguments in the arguments field, such as "-ExecutionPolicy Bypass -File"

Then just hit OK. It will prompt you for the password for the account that you are trying to run the script as, and Windows will manage it from there.

Upvotes: 1

Related Questions