PoshCode Archive  Artifact [1f88bf60f5]

Artifact 1f88bf60f5dfbae1c9b9e7b706332aabcfa1fbec73dae7eb75a5cfb242739ee0:

  • File Inovke-command-exclusive.ps1 — part of check-in [9cc8c844d0] at 2018-06-10 13:07:33 on branch trunk — This invokes a command exclusively (user: bassamf size: 1539)

# encoding: ascii
# api: powershell
# title: Inovke command exclusive
# description: This invokes a command exclusively
# version: 0.1
# type: function
# author: bassamf
# license: CC0
# function: Invoke-CommandEx
# x-poshcode-id: 2228
# x-archived: 2017-02-18T07:03:23
# x-published: 2011-09-11T20:06:00
#
#
function Invoke-CommandEx
{
	param
	(
		[String] $MutexName = $(throw "Name is required."),
		[ScriptBlock] $Scriptblock = $(throw "Scriptblock is required."),
		[Object[]] $ArgumentList
	)
	$MutexWasCreated = $false;
	$Mutex = $null;
	Write-Host "Waiting to acquire lock [$MutexName]..." -f Cyan
	[System.Reflection.Assembly]::LoadWithPartialName("System.Threading");
	try {
		$Mutex = [System.Threading.Mutex]::OpenExisting($MutexName);
	}catch{
		$Mutex = New-Object System.Threading.Mutex($true,$MutexName,[ref]$MutexWasCreated);
	}
	try {
		if(!$MutexWasCreated){
			$Mutex.WaitOne() | Out-Null;
		}
	}catch{}
	Write-Host "Lock [$MutexName] acquired. Executing..." -f Cyan
#region Execute Powershell V1 compatible
	foreach($arg in $ArgumentList){
		$params += "`"$arg`" ";
	}
	$cmd = @"
	function f{
		$Scriptblock
	}
	f $params
"@;
	Invoke-Expression $cmd
#endregion
	
	# This is powershell v2
	# Invoke-Command -ScriptBlock $Scriptblock -ArgumentList $ArgumentList  
	# We're done, Release lock, even if we exit before releasing the mutex will be abandoned
	Write-Host "Releasing lock [$MutexName]..." -f Cyan
	try {
		$Mutex.ReleaseMutex() | Out-Null;
	}catch{}
}