2016-01-13 2 views
0

Попытка написать скрипт PowerShell, который делает следующее:PowerShell Service - Выход Чтение Некорректное

  1. Посмотрите на сервис существования
  2. Если найден, проверьте состояние службы
  3. состояние службы
  4. Report
  5. Если сервис статус не начат стартовый сервис
  6. Пожаловаться на сервисное обслуживание

Issue: Если я запустил сценарий один раз, окончательный статус службы скажет, но сообщение напечатано до того, как оно не сможет запустить службу. Если я снова запустил скрипт, он перевернет флоп и скажет, что служба запущена, но окончательный статус остановлен.

Текущий код:

# Setting variables 

$date = Get-Date # setting date 
$LogFile = "$env:UserProfile\Desktop\Log.txt" # setting log file - change as needed 
$ServiceName = "Spooler" # setting service name - change as needed 
$arrService = Get-Service -Name $ServiceName 
$arrServiceCheck = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue -ErrorVariable NoService 


<# =============== DO NOT CHANGE ANYTHING BELOW THIS POINT =============== #> 

# Creating functions for re-use throughout script 

function CurrentServiceStatus { 
    Write-Output "Status of '$ServiceName' service:" | Out-File $LogFile -append 
    Get-Service $ServiceName | Select Name,DisplayName,Status | Format-List | Out-File $LogFile -append 
} 

# Starting script operation 

Write-Output "=========================================================================" | Out-File $LogFile 
Write-Output " Starting '$ServiceName' Service Monitor Script on $date" | Out-File $LogFile -append 
Write-Output "=========================================================================" | Out-File $LogFile -append 
Write-Output " " | Out-File $LogFile -append 

# Looking for service. If service was found, checking it's status. If status is not running, starting the service. 

if ($arrServiceCheck){ 
    Write-Output "'$ServiceName' service found on $env:ComputerName..." | Out-File $LogFile -append 
    Write-Output " " | Out-File $LogFile -append 

    ServiceStatus 

    if ($arrService.Status -ne "Running"){ 
     Start-Service $ServiceName | Out-File $LogFile -append 
    } 

    if ($arrService.Status -eq "Running"){ 
     Write-Output "$date - '$ServiceName' started..." | Out-File $LogFile -append 
     Write-Output " " | Out-File $LogFile -append 
     ServiceStatus 
    } 
    else{ 
     Write-Output "Error: '$ServiceName' service could not be started..." | Out-File $LogFile -append 
     Write-Output " " | Out-File $LogFile -append 
     ServiceStatus 
    } 
} 

# If service was not found, making note of it to log file 

if ($NoService){ 
    Write-Output " " | Out-File $LogFile -append 
Write-Output $NoService[0].exception.message | Out-File $LogFile -append 
    Write-Output " " | Out-File $LogFile -append 
} 

# Completing running of script 

Write-Output "=========================================================================" | Out-File $LogFile -append 
Write-Output " Finished '$ServiceName' Service Monitor Script on $date" | Out-File $LogFile -append 
Write-Output "=========================================================================" | Out-File $LogFile -append 
Write-Output " " | Out-File $LogFile -append 
Write-Output " " | Out-File $LogFile -append 

Вот мой выход ...

Run 1:

========================================================================= 
    Starting 'Spooler' Service Monitor Script on 01/13/2016 12:06:49 
========================================================================= 

'Spooler' service found on MW762OXI5K7M8D... 

Current status of 'Spooler' service: 


Name  : Spooler 
DisplayName : Print Spooler 
Status  : Stopped 



01/13/2016 12:06:49 - 'Spooler' started... 

Final status of 'Spooler' service: 


Name  : Spooler 
DisplayName : Print Spooler 
Status  : Stopped 



========================================================================= 
    Finished 'Spooler' Service Monitor Script on 01/13/2016 12:06:49 
========================================================================= 

Run 2:

========================================================================= 
    Starting 'Spooler' Service Monitor Script on 01/13/2016 12:15:58 
========================================================================= 

'Spooler' service found on MW762OXI5K7M8D... 

Current status of 'Spooler' service: 


Name  : Spooler 
DisplayName : Print Spooler 
Status  : Stopped 



'Spooler' service could not be started... 

Final status of 'Spooler' service: 


Name  : Spooler 
DisplayName : Print Spooler 
Status  : Running 



========================================================================= 
    Finished 'Spooler' Service Monitor Script on 01/13/2016 12:15:58 
========================================================================= 

==========================================

Вот исправленный код:

# Setting variables 

$date = Get-Date # setting date 
$LogFile = "$env:UserProfile\Desktop\NXLogMonitor\Logging\NXLogMonitor.txt" # setting log file - change as needed 
$ServiceName = "Spooler" # setting service name - change as needed 
$arrService = Get-Service -Name $ServiceName 
$arrServiceCheck = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue -ErrorVariable NoService 


<# =============== DO NOT CHANGE ANYTHING BELOW THIS POINT =============== #> 

# Creating functions for re-use throughout script 

function ServiceStatus { 
    Write-Output "Status of '$ServiceName' service:" | Out-File $LogFile -append 
    Get-Service $ServiceName | Select Name,DisplayName,Status | Format-Table -AutoSize | Out-File $LogFile -append 
} 

# Starting script operation 

Write-Output "=========================================================================" | Out-File $LogFile 
Write-Output " Starting '$ServiceName' Service Monitor Script on $date" | Out-File $LogFile -append 
Write-Output "=========================================================================" | Out-File $LogFile -append 
Write-Output " " | Out-File $LogFile -append 

# Looking for service. If service was found, checking it's status. If status is not running, starting the service. 

if ($arrServiceCheck){ 
    Write-Output "'$ServiceName' service found on $env:ComputerName..." | Out-File $LogFile -append 
    Write-Output " " | Out-File $LogFile -append 

    if ($arrService.Status -eq "Running"){ 
     Write-Output "'$ServiceName' is already started..." | Out-File $LogFile -append 
     Write-Output " " | Out-File $LogFile -append 
     ServiceStatus 
    } 

    if ($arrService.Status -ne "Running"){ 
     Write-Output "'$ServiceName' service is not started..." | Out-File $LogFile -append 
     Write-Output " " | Out-File $LogFile -append 

     ServiceStatus 

     $arrService = Start-Service $ServiceName -PassThru 
     if ($arrService.Status -eq "Running"){ 
      Write-Output "$date - '$ServiceName' service started..." | Out-File $LogFile -append 
      Write-Output " " | Out-File $LogFile -append 
      ServiceStatus 
     } 
     elseif ($arrService.Status -ne "Running"){ 
      Write-Output "Error: '$ServiceName' service could not be started..." | Out-File $LogFile -append 
      Write-Output " " | Out-File $LogFile -append 
      ServiceStatus 
     } 
    } 
} 

# If service was not found, making note of it to log file 

if ($NoService){ 
    Write-Output " " | Out-File $LogFile -append 
Write-Output $NoService[0].exception.message | Out-File $LogFile -append 
    Write-Output " " | Out-File $LogFile -append 
} 

# Completing running of script 

Write-Output "=========================================================================" | Out-File $LogFile -append 
Write-Output " Finished '$ServiceName' Service Monitor Script on $date" | Out-File $LogFile -append 
Write-Output "=========================================================================" | Out-File $LogFile -append 
Write-Output " " | Out-File $LogFile -append 
Write-Output " " | Out-File $LogFile -append 

Вот вывод исправленного кода:

========================================================================= 
    Starting 'Spooler' Service Monitor Script on 01/13/2016 13:53:08 
========================================================================= 

'Spooler' service found on MW762OXI5K7M8D... 

'Spooler' is already started... 

Status of 'Spooler' service: 

Name DisplayName Status 
---- ----------- ------ 
Spooler Print Spooler Running 


========================================================================= 
    Finished 'Spooler' Service Monitor Script on 01/13/2016 13:53:08 
========================================================================= 
+1

'$ arrServic e.Status' не будет изменяться между вашими другими операторами if/else, он остается неизменным во всем скрипте. Запустите 'Get-Service' снова вместо проверки и« старой »переменной значение –

ответ

2

Возьмите хороший взгляд на то, что вы делаете в начале:

$arrService = Get-Service -Name $ServiceName 

$arrService.Status в настоящее время отражает состояние службы , прежде чем вы начинаете делать что-нибудь - давайте представим себе, что статус Stopped

Затем, позже в вашем скрипте:

if ($arrService.Status -ne "Running"){ 
    Start-Service $ServiceName | Out-File $LogFile -append 
} 

Эта часть работает должным образом - служба не запускалась при запуске d сценарий, и поэтому он будет запущен сейчас, отлично!

Затем наступает проблематичная часть вашего сценария:

if ($arrService.Status -eq "Running"){ 
     Write-Output "$date - '$ServiceName' started..." | Out-File $LogFile -append 
     Write-Output " " | Out-File $LogFile -append 
     FinalServiceStatus 
} 
else{ 
    Write-Output "Error: '$ServiceName' service could not be started..." | Out-File $LogFile -append 
    Write-Output " " | Out-File $LogFile -append 
    FinalServiceStatus 
} 

С $arrService.Statusеще имеет точно такое же значение, как и раньше (хотя сама услуга может теперь изменила свой статус на Running), то else блок выполняется независимо от того, была ли служба успешно запущена.


Вам нужно позвонить Get-Serviceснова, чтобы получить новое значение сервиса, или (мой личный фаворит) использовать Start-Service -PassThru на «обновить» $arrService переменные:

if($arrService.Status -ne 'Running') 
{ 
    $arrService = Start-Service $ServiceName -PassThru 
} 

if($arrService.Status -eq 'Running') 
{ 
    "Service is running" # although we don't know whether it was just started or already had been 
} 
else 
{ 
    "Service not running, starting must have failed" 
} 
+0

Благодарим вас за это @Mathias. Я заработал с вашей помощью. Полностью пропустил это, но определенно понимаю, как это может быть проблемой. Переключатель -passthru - приятный прикосновение тоже :). Теперь, если бы я мог просто получить форматирование правильно ... – Ilya

+0

Это другой вопрос (не стесняйтесь спрашивать новый). Подсказка: не используйте 'Format-List', он добавляет нежелательные строки перевода. –

+0

Получил. Благодарим вас за помощь в решении самой большой проблемы @Mathias. – Ilya

0

Для тех, кто заинтересован , по предложению Матиаса, вот что мой код в итоге выглядел (насколько это касается логики):

if ($arrServiceCheck){ 
    Write-Output "'$ServiceName' service found on $env:ComputerName..." | Out-File $LogFile -append 
    Write-Output " " | Out-File $LogFile -append 

    if ($arrService.Status -eq "Running"){ 
      Write-Output "'$ServiceName' is already started..." | Out-File $LogFile -append 
      Write-Output " " | Out-File $LogFile -append 
      FinalServiceStatus 
} 

    if ($arrService.Status -ne "Running"){ 
     CurrentServiceStatus 
     $arrService = Start-Service $ServiceName -PassThru 
     if ($arrService.Status -eq "Running"){ 
      Write-Output "$date - '$ServiceName' started..." | Out-File $LogFile -append 
      Write-Output " " | Out-File $LogFile -append 
      FinalServiceStatus 
     } 
     elseif ($arrService.Status -ne "Running"){ 
      Write-Output "Error: '$ServiceName' service could not be started..." | Out-File $LogFile -append 
      Write-Output " " | Out-File $LogFile -append 
      FinalServiceStatus 
     } 
    } 
} 
Смежные вопросы