#Powershell Check if Running

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!"}

Comments

  1. Hi, thank you!

    i made a function out of your code. $PID contain already the process id of the running process.

    function is_process_still_running(){

    #Name of the Script (FileName)
    $AppName = $MyInvocation.ScriptName

    #PID of running script
    #$PID = ([System.Diagnostics.Process]::GetCurrentProcess()).id
    #$PID already contain the current PID -> standard variable and protected

    #Who is the user running the script
    $UID = ([System.Security.Principal.WindowsIdentity]::GetCurrent()).Name.split(“\”)[-1];

    #all powershell processes running on this pc
    $PS_Processes = get-wmiobject win32_process|where{$_.name -eq “powershell.exe”}|select name,processid,commandline,@{n=”owner”; e={$_.getowner().user}}

    #filter the processe-list depending on $UID , $AppName and $PID
    $xRunning = $PS_Processes | where {($_.owner -eq $UID) -AND ($_.commandline -like “*$AppName*”) -AND ($_.processid -ne $PID)};

    if( -NOT [string]::IsNullOrEmpty($xRunning) ){
    return $true
    }else{
    return $false
    }
    }

Leave a Reply

%d bloggers like this: