Announcement

Collapse
No announcement yet.

script that generates email - doesnt work

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • script that generates email - doesnt work

    Good morning All!
    I have a script to run a daily backup. It is scheduled on the scheduler and is meant to generate an email upon completion. I know the syntax is correct because when I run it in debug mode the email gets generated properly. I feel like it might be a permissions issue and have tried with different credentials.

    Perhaps, I haven't used the right combination of creds - I'm only human...but what I would really like is the ability to get some logging that will tell me what the issue/error is.

    Here is a snippet of the code:
    if ($bkerror -eq $null)
    {
    # success
    $summary = get-wbsummary
    [string] $emailline1 = "Last backup Time: " + [string]$summary.LastSuccessfulBackupTime
    [string] $emailline2 = "Last backup destination: " + [string]$summary.LastSuccessfulBackupTargetPath
    [string] $emailline3 = "Last backup drives: " + [string]$Volume
    [string]$emailbody = $emailline1 + $emailline2 + $emailline3




    $scriptname = $myinvocation.mycommand

    $emailsubj = $computer + " " + $scriptname + " " + $dayofweek


    send-mailmessage -to "[email protected]" -from "[email protected]" -subject $emailsubj -smtpserver webmail.taxva.com -Body $emailbody
    }

  • #2
    Re: script that generates email - doesnt work

    When you created the schedule task, did you specify a credential and configure the task to access the network? Without a credential, the task can only do things local.

    Another possibility is that your SMTP server requires a credential and when you run the command interactively, it automatically uses your current credential.

    Comment


    • #3
      Re: script that generates email - doesnt work

      Thanks for your reply. I have the task scheduled with an admin account and also specified the credential on the send message command. Can we talk more about that you mean when you say configure it to access the network?

      Not to blast you with too much detail... here is the xml dump of the task:


      - <Triggers>
      - <CalendarTrigger id="1">
      <StartBoundary>2014-10-01T23:50:00</StartBoundary>
      <Enabled>true</Enabled>
      <RandomDelay>P0DT0H0M0S</RandomDelay>
      - <ScheduleByDay>
      <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
      </CalendarTrigger>
      </Triggers>
      - <Principals>
      - <Principal id="Author">
      <UserId>\tacs_admin</UserId>
      <LogonType>Password</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
      </Principal>
      </Principals>
      - <Settings>
      <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
      <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
      <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
      <AllowHardTerminate>true</AllowHardTerminate>
      <StartWhenAvailable>false</StartWhenAvailable>
      <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
      - <IdleSettings>
      <Duration>P0DT0H10M0S</Duration>
      <WaitTimeout>P0DT1H0M0S</WaitTimeout>
      <StopOnIdleEnd>false</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
      </IdleSettings>
      <AllowStartOnDemand>true</AllowStartOnDemand>
      <Enabled>true</Enabled>
      <Hidden>false</Hidden>
      <RunOnlyIfIdle>false</RunOnlyIfIdle>
      <WakeToRun>false</WakeToRun>
      <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
      <Priority>7</Priority>
      </Settings>
      - <Actions Context="Author">
      - <Exec id="StartPowerShellJob">
      <Command>powershell.exe</Command>
      <Arguments>-NoLogo -NonInteractive -WindowStyle Hidden -Command "Import-Module PSScheduledJob; $jobDef = [Microsoft.PowerShell.ScheduledJob.ScheduledJobDefi nition]::LoadFromStore('P1Dailybkupv2', 'C:\Users\tlewis\AppData\Local\Microsoft\Windows\P owerShell\ScheduledJobs'); $jobDef.Run()"</Arguments>
      </Exec>
      </Actions>
      </Task>

      Comment


      • #4
        Re: script that generates email - doesnt work

        The network setting I was thinking of is the require network option you can set as a PowerShell scheduled job option. Have you tried creating a scheduled job to just send an email? That way you can test without having to do the backup. I still think it is a credential issue.

        In the task scheduler when you look at the job, make sure it is set to run whether a user is logged in or not and the do not store password checkbox is NOT checked. If it is that could be the problem.

        then you need to be sure that the account you are using the task is the same as the mail credential.

        What version of PowerShell are you testing with and on what operating system?

        Comment


        • #5
          Re: script that generates email - doesnt work

          Thanks I will try that.

          my version of powershell is 3.0 and I am running this on my server WS2012 (not R2)...

          Comment


          • #6
            Re: script that generates email - doesnt work

            What is the PowerShell execution policy of the server?
            In the scheduled task you may want to add -executionpolicy bypass as a parameter for PowerShell.
            Regards,
            Jeremy

            Network Consultant/Engineer
            Baltimore - Washington area and beyond
            www.gma-cpa.com

            Comment


            • #7
              more info....Re: script that generates email - doesnt work

              Thanks for all the suggestions. I continue to work on this from time to time and I have applied most, if not all, of the suggestions here. Including bypass execution policy.

              I have also been digging into the logs and I think that I have discovered the culprit; although it is not resolved yet!!

              When I look at the powershell logs, I have discovered that I have an issue with the variable that I am using for the subject. As this time, I am not sure that this was the original issue as I have made a few changes but have not had the luxury of testing in between each change to evaluate the impact. Below is the message and I will be working on changing how I populate this variable. Note that I have x'd out user/computer name.


              Log Name: Microsoft-Windows-PowerShell/Operational
              Source: Microsoft-Windows-PowerShell
              Date: 11/6/2014 12:19:11 AM
              Event ID: 4100
              Task Category: Executing Pipeline
              Level: Warning
              Keywords: None
              User: XXXXXX\XXXXXXXXXXXXX
              Computer: PXXXXX1.XXXX.local
              Description:
              Error Message = The specified string is not in the form required for a subject.
              Fully Qualified Error ID = System.ArgumentException,Microsoft.PowerShell.Comm ands.SendMailMessage


              Context:
              Severity = Warning
              Host Name = ServerRemoteHost
              Host Version = 1.0.0.0
              Host ID = 9df39f29-9b67-4a7a-9b44-309b73c72b31
              Engine Version = 3.0
              Runspace ID = 64e8b866-445d-4d7d-bf44-91301e547bda
              Pipeline ID = 1
              Command Name = Send-MailMessage
              Command Type = Cmdlet
              Script Name =
              Command Path =
              Sequence Number = 20
              User = xxxxxxx
              Shell ID = Microsoft.PowerShell


              User Data:


              Event Xml:

              <System>
              <Provider Name="Microsoft-Windows-PowerShell" Guid="{A0C1853B-5C40-4B15-8766-3CF1C58F985A}" />
              <EventID>4100</EventID>
              <Version>1</Version>
              <Level>3</Level>
              <Task>106</Task>
              <Opcode>19</Opcode>
              <Keywords>0x0</Keywords>
              <TimeCreated SystemTime="2014-11-06T05:19:11.221010700Z" />
              <EventRecordID>901938</EventRecordID>
              <Correlation ActivityID="{6ADA5529-F945-0001-4C57-DA6A45F9CF01}" />
              <Execution ProcessID="1748" ThreadID="8208" />
              <Channel>Microsoft-Windows-PowerShell/Operational</Channel>
              <Computer>xxxxxxl</Computer>
              <Security UserID="S-1-5-21-2410829177-3108770923-1566818470-1208" />
              </System>
              <EventData>
              <Data Name="ContextInfo"> Severity = Warning
              Host Name = ServerRemoteHost
              Host Version = 1.0.0.0
              Host ID = 9df39f29-9b67-4a7a-9b44-309b73c72b31
              Engine Version = 3.0
              Runspace ID = 64e8b866-445d-4d7d-bf44-91301e547bda
              Pipeline ID = 1
              Command Name = Send-MailMessage
              Command Type = Cmdlet
              Script Name =
              Command Path =
              Sequence Number = 20
              User = Txxxxxxx
              Shell ID = Microsoft.PowerShell
              </Data>
              <Data Name="UserData">
              </Data>
              <Data Name="Payload">Error Message = The specified string is not in the form required for a subject.
              Fully Qualified Error ID = System.ArgumentException,Microsoft.PowerShell.Comm ands.SendMailMessage
              </Data>
              </EventData>
              </Event>

              Comment


              • #8
                Re: script that generates email - doesnt work

                Try using this as your email subject:
                Code:
                [string]$emailsubj = "$computer $scriptname $dayofweek"
                Regards,
                Jeremy

                Network Consultant/Engineer
                Baltimore - Washington area and beyond
                www.gma-cpa.com

                Comment


                • #9
                  Re: script that generates email - doesnt work

                  Thanks Jeremy. I do have another change to make in the next month or so to send the backup offsite... and I will try your suggestion then.

                  The email is now being generated daily...although there are a few cosmetic changes I would like to work on (sometime in the future).

                  I was happy to find that I could leave the job scheduled and change the source code...without unregistering, etc... so that was nice. I was worried about that. Worked nicely.. just want to say that I did use what I learned from Jeffery Hicks class... "Getting Started with Scheduled Jobs"...

                  Many thanks for all the help!!!

                  Comment

                  Working...
                  X