So I have a number of scripts that run as scheduled tasks. The issue is that some scripts take longer to run and at times I have multiple copies of the same script running. I wanted to stop this. So I knocked up this. Essentially it checks to see if the script that has started is already running, and then it kills the old process, and the script continues.
#AppName is the name of the script $AppName = "Get-PerformanceInfo.ps1" Write-Host "Checking if script is already running" #Get the PID of this script $myPID = ([System.Diagnostics.Process]::GetCurrentProcess()).id Write-Host $myPID #Who is the user running the script $cu = ([System.Security.Principal.WindowsIdentity]::GetCurrent()).Name.split("\")[-1]; #Check to see if the script is already running $xRunning=get-wmiobject win32_process|where{$_.name -eq "powershell.exe"}|select name,processid,commandline,@{n="owner"; e={$_.getowner().user}} | where {($_.owner -eq $cu) -AND ($_.commandline -like "*$AppName*") -AND ($_.processid -ne $myPID)}; #If it's running kill it IF(-NOT [string]::IsNullOrEmpty($xRunning)){Write-Host "Running! Terminating!";$xRunning | FL; $xRunning | forEach{$xpid = $_.processid; $xpid;Stop-Process -id $xpid -force -confirm:$false}}ELSE{Write-Host "Not Running!"}