locked
Trying to run Power shell Script on task schedule RRS feed

  • Question

  • My case is i'm trying to run a power shell script through the task schedule.

    Note if i run the script locally it is working fine but from the task schedule it is not working.

    More information: 

    script function: Password Change Notification

    Task name : test3

    Time to do the task: 9:08 am every day

    the status : running 

    .ps1 file location: under C\windows\system32\

    some actions in the task history after the dated time to run:

    Task Scheduler launched "{3023b1eb-9b29-47b9-ace2-e6083e2f00cc}"  instance of task "\test3" due to a time trigger condition

    2 Task Engine "S-1-5-21-60622444-1628707926-2526327935-500: enviroment\Admin:S4U:LUA"  received a message from Task Scheduler service requesting to launch task "\test3" .

    3 Task Scheduler started "{3023b1eb-9b29-47b9-ace2-e6083e2f00cc}" instance of the "\test3" task for user "enviroment\admin

    4 Task Scheduler launched action ""C:\Windows\System32\Password Change Notification\Password Change Notification.ps1"" in instance "{3023b1eb-9b29-47b9-ace2-e6083e2f00cc}" of task "\test3

    5 Task Scheduler launch task "\test3" , instance "C:\Windows\System32\notepad.exe"  with process ID 5052

    Thursday, February 5, 2015 6:35 AM

All replies

  • Hi Naif Algumaizy,

    How did you configure the task schedule ?

    According to the task history ,it seems that the powershell was opened in the notepad.exe.

    To configure it run as a powershell script ,please check this link:

    Weekend Scripter: Use the Windows Task Scheduler to Run a Windows PowerShell Script(Pay attention to the action part ! )
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/08/11/weekend-scripter-use-the-windows-task-scheduler-to-run-a-windows-powershell-script.aspx

    Best regards

    Friday, February 6, 2015 7:31 AM
  • Hi MeipoXu,

    First of all i would like to thank you for your answer, i followed the URL that you posted already in the previous comment and unfortunately it didn't work, and please find my ps1 file content as typed below and give me your feedback on that.

       

    ################################################################################################################# # Version 1.1 May 2014 # Robert Pearman (WSSMB MVP) # TitleRequired.com # Script to Automated Email Reminders when Users Passwords due to Expire. # # Requires: Windows PowerShell Module for Active Directory # # For assistance and ideas, visit the TechNet Gallery Q&A Page. http://gallery.technet.microsoft.com/Password-Expiry-Email-177c3e27/view/Discussions#content # ################################################################################################################## # Please Configure the following variables.... $smtpServer="outlook. myDomain " $expireindays = 7 $from = "الدعم الفني <ITHelpDesk@myDomain>" $logging = "Enabled" # Set to Disabled to Disable Logging $logFile = "PassExpireNotlog.csv" # ie. c:\mylog.csv $testing = "Enabled" ## "Enabled" # Set to Disabled to Email Users $testRecipient = "MyEmail@MyDomain" $encoding = [System.Text.Encoding]::Unicode $date = Get-Date -format ddMMyyyy # ################################################################################################################### # Check Logging Settings if (($logging) -eq "Enabled") {     # Test Log File Path     $logfilePath = (Test-Path $logFile)     if (($logFilePath) -ne "True")     {         # Create CSV File and Headers         New-Item $logfile -ItemType File         Add-Content $logfile "Date,Name,EmailAddress,DaystoExpire,ExpiresOn,MsgBody"     } } # End Logging Check # Get Users From AD who are Enabled, Passwords Expire and are Not Currently Expired Import-Module ActiveDirectory $users = get-aduser -filter * -SearchScope Subtree -SearchBase "OU=UsersOU,DC=MyDomain,DC=MyrootDomain,DC=MYrootNS" -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress |where {$_.Enabled -eq "True"} | where { $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false } $maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge # Process Each User for Password Expiry foreach ($user in $users) {     $Name = (Get-ADUser $user | foreach { $_.Name})     $emailaddress = $user.emailaddress     $passwordSetDate = (get-aduser $user -properties * | foreach { $_.PasswordLastSet })     $PasswordPol = (Get-AduserResultantPasswordPolicy $user)     # Check for Fine Grained Password     if (($PasswordPol) -ne $null)     {         $maxPasswordAge = ($PasswordPol).MaxPasswordAge     }        $expireson = $passwordsetdate + $maxPasswordAge     $today = (get-date)     $daystoexpire = (New-TimeSpan -Start $today -End $Expireson).Days              # Set Greeting based on Number of Days to Expiry.     # Check Number of Days to Expiry     $messageDays = $daystoexpire     if (($messageDays) -ge "2")     {         $messageDays = "خلال " + "$daystoexpire" + " ايام"     }     elseif (($messageDays) -eq "2")     {         $messageDays = "خلال يومين "     }     else     {         $messageDays = "اليوم."     }     # Email Subject Set Here     $subject="كلمة المرور الخاصة بك ستنتهي $messageDays"        # Email Body Set Here, Note You can use HTML, including Images.     $body =     "<P style='font-family: Arial; font-size: 16pt' />     <center> الاستاذ/ $name ، </center>      <br>     <center> كلمة المرور الخاصة بك ستنتهي $messageDays </center>     <br>     <center> نأمل تغييرها في أقرب فرصة حتي تتمكن من الدخول على النظام </center>     <br>     <center> مع تحيات الادارة العامة لتقنية المعلومات </center>      <br>     </P>"         # If Testing Is Enabled - Email Administrator     if (($testing) -eq "Enabled")     {         $emailaddress = $testRecipient     } # End Testing     # If a user has no email address listed     if (($emailaddress) -eq $null)     {         $emailaddress = $testRecipient         }# End No Valid Email     # Send Email Message     if (($daystoexpire -ge "0") -and ($daystoexpire -lt $expireindays))     {          # If Logging is Enabled Log Details         if (($logging) -eq "Enabled")         {             Add-Content $logfile "$date,$Name,$emailaddress,$daystoExpire,$expireson,$body"          }         # Send Email Message         Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailaddress -subject $subject -body $body -bodyasHTML -priority High -Encoding $encoding                 } # End Send Message   } # End User Processing # End

    Tuesday, February 10, 2015 5:45 AM
  • #################################################################################################################

    # Version 1.1 May 2014
    # Robert Pearman (WSSMB MVP)
    # TitleRequired.com
    # Script to Automated Email Reminders when Users Passwords due to Expire.
    #
    # Requires: Windows PowerShell Module for Active Directory
    #
    # For assistance and ideas, visit the TechNet Gallery Q&A Page. http://gallery.technet.microsoft.com/Password-Expiry-Email-177c3e27/view/Discussions#content
    #
    ##################################################################################################################
    # Please Configure the following variables....
    $smtpServer="outlook.MyDomain"
    $expireindays = 7
    $from = "الدعم الفني <ITHelpDesk@MyDomain>"
    $logging = "Enabled" # Set to Disabled to Disable Logging
    $logFile = "PassExpireNotlog.csv" # ie. c:\mylog.csv
    $testing = "Enabled" ## "Enabled" # Set to Disabled to Email Users
    $testRecipient = "nalgumaizy@MyDomain"
    $encoding = [System.Text.Encoding]::Unicode
    $date = Get-Date -format ddMMyyyy
    #
    ###################################################################################################################

    # Check Logging Settings
    if (($logging) -eq "Enabled")
    {
        # Test Log File Path
        $logfilePath = (Test-Path $logFile)
        if (($logFilePath) -ne "True")
        {
            # Create CSV File and Headers
            New-Item $logfile -ItemType File
            Add-Content $logfile "Date,Name,EmailAddress,DaystoExpire,ExpiresOn,MsgBody"
        }
    } # End Logging Check

    # Get Users From AD who are Enabled, Passwords Expire and are Not Currently Expired
    Import-Module ActiveDirectory
    $users = get-aduser -filter * -SearchScope Subtree -SearchBase "OU=MYUSEROU,DC=MYDOMAIN,DC=MYROOTNS" -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress |where {$_.Enabled -eq "True"} | where { $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false }
    $maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge

    # Process Each User for Password Expiry
    foreach ($user in $users)
    {
        $Name = (Get-ADUser $user | foreach { $_.Name})
        $emailaddress = $user.emailaddress
        $passwordSetDate = (get-aduser $user -properties * | foreach { $_.PasswordLastSet })
        $PasswordPol = (Get-AduserResultantPasswordPolicy $user)
        # Check for Fine Grained Password
        if (($PasswordPol) -ne $null)
        {
            $maxPasswordAge = ($PasswordPol).MaxPasswordAge
        }
      
        $expireson = $passwordsetdate + $maxPasswordAge
        $today = (get-date)
        $daystoexpire = (New-TimeSpan -Start $today -End $Expireson).Days
            
        # Set Greeting based on Number of Days to Expiry.

        # Check Number of Days to Expiry
        $messageDays = $daystoexpire

        if (($messageDays) -ge "2")
        {
            $messageDays = "خلال " + "$daystoexpire" + " ايام"
        }
        elseif (($messageDays) -eq "2")
        {
            $messageDays = "خلال يومين "
        }
        else
        {
            $messageDays = "اليوم."
        }

        # Email Subject Set Here
        $subject="كلمة المرور الخاصة بك ستنتهي $messageDays"
      
        # Email Body Set Here, Note You can use HTML, including Images.
        $body =
        "<P style='font-family: Arial; font-size: 16pt' />
        <center> الاستاذ/ $name ، </center> 
        <br>
        <center> كلمة المرور الخاصة بك ستنتهي $messageDays </center>
        <br>
        <center> نأمل تغييرها في أقرب فرصة حتي تتمكن من الدخول على النظام </center>
        <br>
        <center> مع تحيات الادارة العامة لتقنية المعلومات </center> 
        <br>
        </P>"


       
        # If Testing Is Enabled - Email Administrator
        if (($testing) -eq "Enabled")
        {
            $emailaddress = $testRecipient
        } # End Testing

        # If a user has no email address listed
        if (($emailaddress) -eq $null)
        {
            $emailaddress = $testRecipient    
        }# End No Valid Email

        # Send Email Message
        if (($daystoexpire -ge "0") -and ($daystoexpire -lt $expireindays))
        {
             # If Logging is Enabled Log Details
            if (($logging) -eq "Enabled")
            {
                Add-Content $logfile "$date,$Name,$emailaddress,$daystoExpire,$expireson,$body" 
            }
            # Send Email Message
            Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailaddress -subject $subject -body $body -bodyasHTML -priority High -Encoding $encoding

        } # End Send Message
     
    } # End User Processing
    # End
    Tuesday, February 10, 2015 5:50 AM
  • Hi Naif,

    I tried to run the script as you posted ,but something was wrong with it (The machine is not joined to an AD ).But I think it doesn`t matter because it can run well in your machine . According to your symptom the ps1 file will be opened in the notepad.exe,I made a test .It seems that we should change the ps1 file associations to powershell.

    Control Panel\All Control Panel Items\Default Programs\Associate a file type or protocol with a program(Second option )
    And then navigate to the ps1 file type ,"change program" browser to this path "C:\WINDOWS\system32\WindowsPowerShell\v1.0"and choose "powershell.exe"

    We need`t  add "powershell -file" this time ,just browser to the ps1 file location.

    Best regards


    Tuesday, February 10, 2015 10:21 AM
  • Hi MeipoXu

    after changing the file type, we start our schedule task again we put ps1 trace log and it seems assigning the statement and notify that message send but after track the mailbox there are nothing revived.

    and for your record we i run the ps1 directly it goes well. and we realized that there is issue attend between the ps1 AD statement model and windows task scheduler.

    if you have anything related to this issue pleas share it with us. and thanks in advance.

    BR       

    Wednesday, February 11, 2015 5:58 AM
  • Hi Naif,

    So this time the task schedule run the script as a powershell script (Check the run history)?

    The present situation is that the script won`t run as the expected (manually run well),right ?Maybe it is related to the permission issue .Check this setting :

    Best regards

    Thursday, February 12, 2015 2:00 AM
  • Hi,

    I was able to get it working with the command powershell -file "C:\admin\sendmail.ps1" and "Run with highest priviledges".

    Thanks.

    Friday, November 20, 2015 9:06 AM