#	Licensed Materials - Property of IBM
#
#	IBM Cognos Products: btsv
#
#	(C) Copyright IBM Corp. 2016
#
#	US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
#

# Get CARoot since this script locates in $caRoot/bin or $caRoot/bin64.
$curPSScriptRoot = split-path -parent $MyInvocation.MyCommand.Definition
$caRoot = Split-Path -Path $curPSScriptRoot
$logFile   = "$caRoot\logs\forcestop.log"
$caPIDFile = "$caRoot\logs\capids.log"


# Check the existence of $caPIDFile. If yes get content else exit
if ( Test-Path -Path $caPIDFile) {
	$allCAProc = Get-Content $caPIDFile
	if ( !$allCAProc ) {
		exit 0
	}
}
else {
	exit 0
}

# Delete $logFile if it exists
if ( Test-Path -Path $logFile) {
	del $logFile
}

# Get date time for logging
$dateTime = Get-Date -format s

# For each process in $caPIDFile, if it still running and if its name still the same as before, log a message and forcefully stop
$index = 1
foreach ( $aCAProc in $allCAProc ) {
	$aCAPid = $aCAProc.Split(' ')[0]
	$aCAPName = $aCAProc.Split(' ')[1]
	$procInfo = gwmi win32_process | Where-Object { $_.ProcessID -eq $aCAPid } | % { "$($_.ProcessID) $($_.Name) $($_.ParentProcessID) $($_.GetOwner().User)"}
	if ( $procInfo ) {
		if ( $index -eq 1 )  {
			$msg = "$dateTime The following processes will be shutdown forcefully`r`n" | Out-File -append $logFile
			$index = $index + 1
		}
		foreach ($line in $procInfo) {
			$procName = $line.Split(' ')[1]
			if ( ($procName -ne $null) -and ($aCAPName -ne $null) -and ($procName -eq $aCAPName)) {
				$msg = "$line" | Out-File -append $logFile
				stop-process -id $aCAPid -Force 2>&1 | Out-File -append $logFile
			}
		}
	}
}