Сценарий Powershell не запустится, если я не скопирую содержимое в новый файл - PullRequest
1 голос
/ 04 мая 2020
• 1000 у меня нет доступа к программному обеспечению для мониторинга для этой краткосрочной необходимости). Я настроил его как рабочий процесс, который берет список серверов и выполняет foreach -Parallel Test-NetConnection. Я использовал рабочий процесс и параметр -Parallel, чтобы уменьшить время выполнения. Результаты добавляются в таблицу, которая выводится и сохраняется как переменная вне рабочего процесса, а затем отправляется мне по электронной почте.

Сначала все работало нормально. Я настроил запланированную задачу и провел несколько тестов с хорошими и плохими именами серверов, чтобы убедиться, что они работают правильно. Сегодня я захожу, и ссылка прервана, а электронной почты нет. История показывала выполненные задачи каждый час. Я попытался открыть сценарий в ISE и получил следующую ошибку, когда попытался запустить его:

Произошла ошибка при вызове участников отслеживания, из-за чего экземпляр был прерван. Подробнее см. Внутреннее исключение. + CategoryInfo: InvalidResult: (:) [], OperationCanceledException + FullyQualifiedErrorId: JobStateFailed

Я пытался добавить сообщение catch $ _. Exception.innerException.message, но не смог получить никакого результата от скрипта (он все еще только что выдал ошибку выше).

ОДНАКО ; если я скопирую / вставлю все содержимое скрипта в новый файл, он будет работать так, как ожидалось. Я даже скопировал плохой файл .ps1 на свою рабочую станцию ​​и смог воспроизвести то же поведение (не удается с ошибкой отслеживания участников, но скопируйте / вставьте код в новый файл, и он работает), поэтому он не похож на компьютер конкретный c вопрос. Кроме того, если я сохраню «плохой» файл под новым именем, он останется «плохим». Разрешения для «плохих» и «хороших» файлов идентичны.

Итак, пока у меня есть обходной путь, воссоздав файл с помощью копии / вставки скрипта, поскольку я не знаю, почему он сломался в первом место, я не знаю, повторится ли он снова. Кто-нибудь знает, что может вызвать такое поведение?

Санитарный код ниже:

Workflow Test-Connection 
{
$AnyFailures = "No" #Initially set failure toggle to "No" so no email alert is sent unless the toggle is switched by a failure in one or more of the tests.
$MyTime = Get-Date -UFormat "%Y-%m-%d %H:%M:%S %Z"
<#
Edit ComputerName variable list to add or remove computers to be monitored for RDP, SFTP, and SCP access (Ports 3389, 22).
Entries should be double quoted and comma separated. Either IP address or FQDN can be used.
Example: $ComputerName = "192.168.0.1", "testcomputer.domain"
#>
    $ComputerName = "1.2.3.4", "2.3.4.5", "3.4.5.6", "4.5.6.7", "5.6.7.8"
<#
Edit WebsiteName variable list to add or remove websites to be monitored for HTTPS access (Port 443).
Entries should be double quoted and comma separated. Do not include the protocol identifier from the URL "HTTPS://".
Example: $WebsiteName = "www.google.com", "yahoo.com"
#>
    $WebsiteName = "website.com", "website2.com", "website3.com", "website4.com"

    #Test Computers for RDP (port 3389) connectivity.
    foreach -Parallel ($Computer in $ComputerName)
    {
        sequence 
        {
        $Port = 3389
        $Test = (Test-NetConnection -Port $Port -ComputerName $Computer )
        If ($Test.TcpTestSucceeded -eq $True) 
            {
            $Status = "Success on RDP on port $Port"
            }
        Else 
            {
            $Status = "Failure on RDP on port $Port"
            $WORKFLOW:AnyFailures = "Yes" # Trigger Email if there are any failures.
            }
        #Write Status output to an object to be used to create a table at the end of the script.
        $Obj = New-Object -Type PSObject -Property @{
            Server = $Computer
            Status = $Status
            }
        $Obj
        }
    }

    #Test Computers for SFTP/SCP (port 22) connectivity.
     foreach -Parallel ($Computer in $ComputerName) 
    {
        sequence 
        {
        $Port = 22
        $Test = (Test-NetConnection -Port $Port -ComputerName $Computer )
        If ($Test.TcpTestSucceeded -eq $True) 
            {
            $Status = "Success on FTPS/SCP on port $Port"
            }
        Else 
            {
            $Status = "Failure on FTPS/SCP on port $Port"
            $WORKFLOW:AnyFailures = "Yes" # Trigger Email if there are any failures.
            }
        #Write Status output to an object to be used to create a table at the end of the script.
        $Obj = New-Object -Type PSObject -Property @{
            Server = $Computer
            Status = $Status
            }
        $Obj
        }
    }

    #Test Websites for HTTPS (port 443) connectivity.
    foreach -Parallel ($Website in $WebsiteName) 
    {
        sequence 
        {
        $Port = 443
        $Test = (Test-NetConnection -Port $Port -ComputerName $Website )
        If ($Test.TcpTestSucceeded -eq $True) 
            {
            $Status = "Success on HTTPS on port $Port"
            }
        Else 
            {
            $Status = "Failure on HTTPS on port $Port"
            $WORKFLOW:AnyFailures = "Yes" # Trigger Email if there are any failures.
            }
        #Write Status output to an object to be used to create a table at the end of the script.
        $Obj = New-Object -Type PSObject -Property @{
            Server = $Website
            Status = $Status
            }
        $Obj
        }
    }
}
$MyTable = Test-Connection | Select -Property Server, Status | Format-Table -AutoSize
$EmailTable = $MyTable | Out-String


    IF ($MyTable | Out-String -Stream | Select-String -Pattern "Failure on")
    {
$MyTime = Get-Date -UFormat "%Y-%m-%d %H:%M:%S %Z"
$smtpserver = "emailserver.example"
$from = "emailaddress@example.com"
$to = "to-email@example.com"
$subject = "Connection Test Has Failed"
$body = “One or more automated connection tests failed at $MyTime. `n `n Please review the table below for details. `n $EmailTable `n `n `n `n This email was generated from a scheduled task titled 'My-sheduled-task' running on SERVER.Example on an hourly schedule."
Send-MailMessage -smtpserver $smtpserver -from $from -to $to -subject $subject -body $body -port 25
 }
...