SQL Server Agent running powershell commands

  • Hi All,

    I am trying to run the following powershell script as a job from SQL server Agent (2008 R2), however, I

    get:

    "Unable to start execution of step 2 (reason: The job step contains tokens. For SQL Server 2005 Service Pack 1 or later, you must use the appropriate ESCAPE_xxx macro to update job steps containing tokens before the job can run.). The step failed."

    I run other jobs as Type "powershell" defined steps with variables which works fine, but I cannot get my head around which bit is the "Token". All help appreciated.

    Thanks,

    Colin.

    $source_dir = "B:\Database_Backups"

    $target_dir = "\\machine-b\backup_Database_Backups"

    foreach ($i in Get-ChildItem $source_dir)

    {

    if ($i.CreationTime -gt ($(Get-Date).AddDays(-2)))

    {

    Copy-Item $i.FullName $target_dir

    }

    }

  • I think the $ sign is misleading SQL Server Agent, as he thinks it is a job token, while in fact it is a powershell variable.

    http://msdn.microsoft.com/en-us/library/ms175575.aspx

    Need an answer? No, you need a question
    My blog at https://sqlkover.com.
    MCSE Business Intelligence - Microsoft Data Platform MVP

  • That was very helpful link...solved my problem and my job is running smoothly now .

    thanks

  • What was the actual solution?

  • Put the date to a variable first it is the Get-Date that seems to be the problem in my example above.

    $source_dir = "B:\Database_Backups"

    $target_dir = "\\machine-b\Database_Backups"

    $d = Get-Date

    Get-ChildItem $source_dir\*.* -include *.bak, *.trn | where {$_.CreationTime -gt ($d.AddDays(-1))} | Copy-Item -Destination $target_dir

  • Thank you! It works for me to ($d = Get-Date).

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply