Prevent multiple instance of application running using Powershell
Introduction
In production environments, it's crucial to ensure that applications run smoothly and efficiently. A common problem is managing multiple instances of the same application, which can lead to conflicts, excessive resource usage and unexpected errors. To solve this problem, we can use a PowerShell script that prevents multiple instances of an application from running simultaneously.
Usefulness of the script in production environments
This PowerShell script is particularly useful in production environments for several reasons :
What exactly does this script do ❓
The script continuously monitors the instances of a specific application (process) and ensures that only one instance remains active. If it detects more than one instance, it automatically terminates any additional instances.
You can use this script also with GPO in Active Directory.
Recommended by LinkedIn
🛑 Note :
PowerShell script :
keep in mind to replace $processName variable with your own process name.
# Process Name
$processName = "Process Name Here"
while($true)
{
try
{
# Get all process with name = process name
$AllProcess = Get-Process $processName -ErrorAction SilentlyContinue
if($AllProcess.count -eq 1)
{
Write-Host "Only one Application instance is running...." -ForegroundColor Green
}
else
{
Write-Host "Total of Process Number is : " $AllProcess.count -ForegroundColor Yellow
# Start Killing other process
$AllProcess | Select-Object -Skip 1 | ForEach-Object {
Stop-Process -Id $_.Id -Force
Write-Host "Application Instance Stopped : $($_.Id)" -ForegroundColor Yellow
}
}
}
catch
{
Write-Host "Error : Please check process name" -ForegroundColor Red
}
# Start sleeping for 15 minutes
Start-Sleep 900
}
Thanks
Aymen EL JAZIRI
System Administrator