I am working on a script which will do the following:
- Check if a service (in this case XboxGipSvc) is running
- If service is running, do nothing
- If service is not running, attempt to start service
- If service fails to start, catch error and log to C:\TEMP\RemediationLog.log
I believe I have done my try/catch block correctly, however even though im getting errors when I run the try block, it does not log $error to the file as expected.
Heres my code:
$Error.Clear()
try{
$Airlock1 = Get-Service -Name XboxGipSvc -ErrorAction Stop
while ($Airlock1.Status -ne "Running"){
Start-Service $Airlock1 -ErrorAction Stop
Write-Host $Airlock1.Status
Write-Host "Service is Starting"
Start-Sleep -Seconds 5
$Airlock1.Refresh()
if ($Airlock1.Status -eq "Running"){Write-Host "Service is now running"}
}
}
catch [Microsoft.PowerShell.Commands.StartServiceCommand]{
{
if ($error -ne $null)
{
$test = Test-Path -path C:\TEMP\RemediationLog.log
if ($test -eq $false){New-Item -Path C:\TEMP\RemediationLog.log}
$error | Out-File -FilePath C:\TEMP\RemediationLog.log -Force -Append
Write-Host $error.Exception[0]
}
}
}