Schedule powershell script task doesn't Send-MailMessage

I am building a Powershell script to create a company synchronized email signature so I don't have to ask users to manually edit theirs when information changes. It is set up to grab the contents of the signature template file in the shared network drive and combine it with the personal signature located locally on each machine.

My idea was to run this is a scheduled task in an effort to have these updated no later than 24 hours after any potential changes in the template.

If the script fails, it writes to a log and ultimately emails me so I immediately can remedy any problems on a per user basis.

The script runs perfectly, as is, assuming I run it manually . If I run it as a scheduled task in the user's context (still me), it doesn't send the email notification.

I'll link the script, but what about the scheduled task would cause it to behave differently when it comes to the Send-MailMessage?

My environment is a Server 2008r2 domain running on Windows 7 clients.

    ##############################################
    #Script to automatically sync email signatures
    ##############################################

    #Get logged in user - e.g. DOMAIN\user
    $user = $(Get-WMIObject -class Win32_ComputerSystem | select username).username
    #Strip off DOMAIN\
    $user = $user.Substring(8)

    #Define local and network file paths
    $templatePath = "\\files\z\Email Signatures"
    $localPath = "C:\Signature"

    #Grab date last modified for signature template file
    $signatureTemplate = Get-Item -LiteralPath "$templatePath\signature.html"
    $templateLastMod = $signatureTemplate.lastWriteTime.toString("yyyyMMddHHmmss") -as [int64]

    #Grab date last modified for user's current signature
    If((Test-Path "$localPath\$user-signature.html") -eq $true){
        $currentSig = Get-Item -LiteralPath "$localpath\$user-signature.html"
        $currentSigLastMod = $currentSig.lastWriteTime.toString("yyyyMMddHHmmss") -as [int64]
    }
    Else{
        $currentSigLastMod = 00000000
    }

    #If template is newer than signature, generate updated signature
    If ($currentSigLastMod -lt $templateLastMod) {

        $sigPath = "$localPath\$user-signature.html"
        $userInfo = "$localPath\$user.html"

        #If user info doesn't exists, end script
        If ((Test-Path $userInfo) -eq $false) {
            $errorTime = (Get-Date)
            Add-Content "$templatePath\userlog.txt" "$errorTime -- $user.html file for user $user does not exist.  Unable to sync signature file."

            #Set SMTP capable user to send email notification
            $smtpUser = "domain\smtpuser"
            $PWord = ConvertTo-SecureString -String "password" -AsPlainText -Force
            $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $smtpUser, $PWord

            $emailSmtpServer = "mail.domain.com"
            $emailFrom = "noreply@domain.com"
            $emailTo = "admin@domain.com"
            $emailSubject = "Missing personal info: $user"
            $emailBody = "$errorTime -- $user.html file for user $user does not exist.  Unable to sync signature file."

            Send-MailMessage -SmtpServer $emailSmtpServer -Credential $Credential -From $emailFrom -To $emailTo -Subject $emailSubject -Body $emailBody  

            return 
        }
        Else{
            #If current signature already exists, delete it.
            If ((Test-Path $sigPath) -eq $true) {
                Remove-Item -LiteralPath $sigPath
            }
        }

        #Create new signature for user
        New-Item -Path "$localPath" -name "$user-signature.html" -itemtype file 

        #Concatenate template content and user personal info into new signature
        Add-Content "$localPath\$user-signature.html" (Get-Content $signatureTemplate)
        Add-Content "$localPath\$user-signature.html" (Get-Content $userInfo)

    }
    Else {
        return
    }
0
задан 17 November 2015 в 22:56
2 ответа

Могу подтвердить, что добавление Start-Sleep -Seconds 1 в мой сценарий также решило проблему в моем случае. Сегодня несколько часов ломал голову над этой проблемой. Я пробовал обычные вещи:

  • Установлена ​​последняя версия Windows Management Framework 5.1
  • Отключен брандмауэр
  • Nslookup / ping работал с доменом
  • Некоторые экземпляры Windows 7/2008 работали, но некоторые не работали по неизвестным причинам .
  • У клиентов Windows 10 нет проблем с использованием одного и того же скрипта PowerShell / сети

Установка Start-sleep -Seconds 1 до того, как мое Send-Mailmessage решит мою проблему.

0
ответ дан 5 December 2019 в 11:33

Я нашел решение Просто добавил Start-Sleep -Seconds 1 в качестве последней строки и это сработало на меня.

0
ответ дан 5 December 2019 в 11:33

Теги

Похожие вопросы