none
Issue with scheduling a powershell script in task scheduler windows 2008 server

    Question

  • I am trying to run a powershell script on the task scheduler but unable to understand the suitable logging command for my script. I want to get this run on the schedule.

    The script would delete the files and folders older than x days by creating a output log. But i wanted to read them first so i included a what if paramter to test identify the files.

    function Out-Log {
        param (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [string]$message,
        [switch]$Error
        )
        $logPath = $env:TEMP + "\Filedeletion.log"
        $message | Out-File -FilePath $logPath -Append
        }
    trap
    {
        "error:" | Out-Log
        $_.exception.message | Out-Log
        break
    }
    $Error.Clear()
    try
    {
        "Starting" | Out-Log
        $DateToDelete = 1
        $dateLimit = (Get-Date).AddDays(-$DateToDelete)
        $StartFolder = "c:\TEST1"
        Get-ChildItem -Recurse -Force -Path $StartFolder |
            foreach {
                $currentItemIsFolder = $_.PsIsContainer;
                $curentItemIsOld = $_.LastWriteTime -lt $dateLimit
                if ($curentItemIsOld -and (-not $currentItemIsFolder))
                {
                    "Removing '$($_.fullname)'." | Out-Log

                     Remove-Item -Path ($_.fullname) -Force -WhatIf

                }
            }

    }
    finally
    {
        if ($Error)
        {
            "`$error stack:" | Out-Log
              $error | foreach {$_.exception.ToString() |  Out-Log}
        }
        "Stopping" | Out-Log
    }

    I am using Powershell -file "c:\Powershell\Filedeletion_logs_test.ps1" this doesn't seem working in my script.

    I do not have any sort of errors so that i can figure out what is going on ?

    There must be some trick to run this schedule. Microsoft Experts please help me further.

    Monday, March 04, 2013 12:11 PM

Answers

  • Here is a restructure that will eliminate some ambiguity by grouping code more functionally.

    'Starting' | Out-Log
    $DateToDelete = 1
    $dateLimit = (Get-Date).AddDays(-$DateToDelete)
    $StartFolder = "c:\TEST1"
    
    try{
         $files=Get-ChildItem -Recurse -Force -Path $StartFolder -EA Stop| 
              Where-Object{-Not $_.PsIsContainer -and $_.LastWritetime -lt $dateLimit}
         foreach( $fi in $files ){
              "Removing $($fi.fullname)." | Out-Log
              Remove-Item -Path ($fi.fullname) -Force -WhatIf -ea Stop
         }
    }
    catch{
        $_ | Out-Log
    }
    



    ¯\_(ツ)_/¯




    • Edited by jrv Monday, March 04, 2013 4:36 PM
    • Marked as answer by Sys_admin2007 Wednesday, March 06, 2013 6:41 AM
    Monday, March 04, 2013 4:33 PM

All replies

  • Hi,

    I seem to use this tail ...

    -Noninteractive -Noprofile -command "&'C:\Scripts\VMReboots\VMReboots.ps1'"

    Make sure you're executing use has permissions to that location (if it's a different account do a shilft,right click run as different user on powershell and then run your code.)

    J

    Monday, March 04, 2013 12:19 PM
  • Hi John,

    I tried your tail but its not working at my end, I double checked while running on schedule in windows task scheduler.

    powershell -Noninteractive -Noprofile -command "&'c:\Powershell\Filedeletion.ps1'"

    Monday, March 04, 2013 12:43 PM
  • I uploaded an export of my scheduled task here ina  previous thread .. http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/04c34bd5-2b30-44eb-bb42-be9e123e9510

    Try and export yours and to a comparrision ... we run all our tasks like this and have no problems ... perhaps you could create a smaller piece of code with a one line?r "Hello-World" | Out-File c:\Test1\Out.txt

    Monday, March 04, 2013 1:03 PM
  • Hi John,

    Here the issue is not the way i run, we have been running plenty of powershell scripts. when i double click on .bat file the script is running fine and generating a output of files. I would like to run that on schedule (windows task scheduler) something is wrong. which is not allowing the windows task scheduler to respond on schedule. May be i am missing with some additioanal parameters -verbose..I am not sure though but i am guessing...

    Monday, March 04, 2013 1:14 PM
  • try and trap in same construct will not work as intended.  Use only try/catch in Posh 2 and later.

    Your code appears way to complex for such a simple task.  Try restructuring a few lines at a time then see what happens.  AStart with only writing a log record.

    Just run this much until you get the schedule working then add the functions.

    function Out-Log {
         param (
         [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
         [string]$message,
         [switch]$Error
         )
         $logPath = $env:TEMP + "\Filedeletion.log"
         "[$([datetime]::Now.ToString('yyyy-MM-dd'))]$message" | Out-File -FilePath $logPath -Append
    }
    
    Out-Log 'Process executed'


    ¯\_(ツ)_/¯

    Monday, March 04, 2013 4:19 PM
  • Here is a restructure that will eliminate some ambiguity by grouping code more functionally.

    'Starting' | Out-Log
    $DateToDelete = 1
    $dateLimit = (Get-Date).AddDays(-$DateToDelete)
    $StartFolder = "c:\TEST1"
    
    try{
         $files=Get-ChildItem -Recurse -Force -Path $StartFolder -EA Stop| 
              Where-Object{-Not $_.PsIsContainer -and $_.LastWritetime -lt $dateLimit}
         foreach( $fi in $files ){
              "Removing $($fi.fullname)." | Out-Log
              Remove-Item -Path ($fi.fullname) -Force -WhatIf -ea Stop
         }
    }
    catch{
        $_ | Out-Log
    }
    



    ¯\_(ツ)_/¯




    • Edited by jrv Monday, March 04, 2013 4:36 PM
    • Marked as answer by Sys_admin2007 Wednesday, March 06, 2013 6:41 AM
    Monday, March 04, 2013 4:33 PM
  • Your issues with the scheduler cannot be addressed without a copy of the XML exported from the scheduler.

    ¯\_(ツ)_/¯

    Monday, March 04, 2013 4:43 PM
  • I hate to comment after you did such a good job cleaning up his script but I would add one thing.  System has a different execution policy than a user and if whoever set up your GPO didn't account for it it may well be set to restricted.  I add

    -executionpolicy remotesigned -noprofile -noninteractive -file 'FilePath'

    to the arguments on everything I put in task scheduler.  Especially if I'm running it as System. 

    Hope that Helps!


    • Edited by R Jason Morgan Monday, March 04, 2013 9:33 PM Clarifying the Arguments portion ensure that people know where in the Task Scheduler box thost parameters belong.
    Monday, March 04, 2013 9:30 PM
  • Just to clarify on that last point the only portion you really need is the -executionpolicy RemoteSigned

    Monday, March 04, 2013 9:31 PM
  • Thanks Jrv for your suggestions....the script would need to run with some admin credentials along with some modifcations. I have used your modified script as test bed and then later I will combine with functions.
    Wednesday, March 06, 2013 6:41 AM