We use an external monitor system (i.e. external to PS) that can take certain actions when the monitor fails its test condition. In this particular monitor, I have a batch file that it launches when it fails. The contents of the batch file is below:
@ECHO OFF
set hh=%time:~0,2%
if “%time:~0,1%”==" " set hh=0%hh:~1,1%
set yymmdd=%date:~10,4%%date:~4,2%%date:~7,2%
set yymmdd_hhmmss=%date:~10,4%%date:~4,2%%date:~7,2%-%hh%%time:~3,2%%time:~6,2%
echo %yymmdd_hhmmss% Restarting Service >> d:\scripts\restart_hubtst2b_wrapper.log
START %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -File D:\Scripts\Restart-Service.ps1
I know the external system is launch the BAT because I see the log I’m generating in the batch. However, I don’t see the log that should be generated from the PS script (Restart-Service.ps1).
I’m stumped because the batch file works fine when I run it manually while logged in with the same service account that the monitoring system runs as. The contents of the PS is below. Does anyone have any idea why this batch file would work okay when logged interactively, but fails when the service tries to run it?
Set-StrictMode -Version latest
Function Write-Log
{
Param ([string]$msgString)
(Get-Date -format "yyyy-MM-dd HH.mm.ss.fff") + " :$msgString" | tee -FilePath "D:\Scripts\$logname" -Append
}
Function InitializeLog {
Param ([string]$logPrefixString)
$logname = $logPrefixString + "-" + (Get-Date -Format "yyyyMMdd") + ".log"
return $logname
}
$logname = InitializeLog “serverName_RestartWrapper”
$s = get-service -ComputerName serverName -Include “ServiceName”
Write-Log “INFO: Attempting to stop $($s.name) on serverName”
#$s.Stop()
#$s.WaitForStatus(‘Stopped’)
Write-Log “INFO: Service $($s.name) was successfully stopped on serverName”
Write-Log “INFO: Attempting to start $($s.name) on serverName”
#$s.Start()
#$s.WaitForStatus(‘Running’)
Write-Log “INFO: Service $($s.name) was successfully started on serverName”