user1926332
user1926332

Reputation: 715

issue with scheduling a powershell script in task scheduler windows 2008 server

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

The script would delete the files and folders older than x days and would create an output log.

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 was trying to use

Powershell -file "c:\Powershell\Filedeletion_logs_test.ps1"

via batch to run the powershell.

I've tried to check the commands in Powershell/? but did not find any suitable logging command working for my script.

Can anyone please help?

Upvotes: 2

Views: 2441

Answers (2)

Leptonator
Leptonator

Reputation: 3499

Can't you do the same thing with SCHTASKS?

http://ss64.com/nt/schtasks.html

You should be able to pipe a list of servers through a TYPE command and add the tasks to the server set.

For example:

http://www.robvanderwoude.com/ntadmincommands.php

FOR /F %%A IN (servers.txt) DO (
SCHTASKS /CREATE /S %%A /U "system" /P "" /TN "Powershell Task" /TR "Powershell -file \"c:\my folder\script.ps1\"" 
)

Upvotes: 0

chamele0n
chamele0n

Reputation: 105

You do not need a separate batch file that runs the powershell in the task schedule. All you need is this nice tutorial. It is detailed step by step, but is very easy to setup. http://community.spiceworks.com/how_to/show/17736-run-powershell-scripts-from-task-scheduler

Upvotes: 0

Related Questions