首页 > 解决方案 > 创建运行带有参数的 powershell 脚本的计划任务时出现问题

问题描述

我正在尝试将带有参数的 PowerShell 脚本作为计划任务执行。在“启动程序”屏幕上,我有

程序/脚本

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

并在添加参数

-Command "& C:\Test\MoveFiles.ps1 -destinationRoot \\OB-VM-ME-Data\ME-Data\Archived\Test"

我做错了什么?

编辑:附件是有问题的脚本

Param (
    [Parameter(Mandatory=$true)][string]$destinationRoot
)

$path = (Get-Item -Path ".\").FullName

Get-ChildItem $path\* -Include *.bmp, *.svg | Where-Object {
    $_.LastWriteTime -lt (Get-Date).AddDays(-30)
} | ForEach-Object {
    $content = $path + "\" + $_.Name

    $year = (Get-Item $content).LastWriteTime.Year.ToString()
    $monthNumber = (Get-Item $content).LastWriteTime.Month
    $month = (Get-Culture).DateTimeFormat.GetMonthName($monthNumber)

    $destination = $destinationRoot + "\" + $year + "\" + $month 

    New-Item -ItemType Directory -Force -Path $destination

    Move-Item -Path $content -Destination $destination -Force
}

标签: powershell

解决方案


-Command如果要执行 PowerShell 脚本(带或不带参数),请勿使用。改为使用-File。将计划任务的参数列表更改为如下内容:

-File "C:\Test\MoveFiles.ps1" -destinationRoot "\\OB-VM-ME-Data\ME-Data\Archived\Test"

编辑:

我看不出你的脚本有什么本质上的错误。唯一可能证明有问题的是它试图从当前工作目录 ( Get-Item -Path ".\") 中读取文件,这可能是也可能不是您认为的那样。不过,您可以在计划任务设置中配置工作目录,以从等式中删除此变量。

由于计划任务是出了名的难以调试,甚至不清楚实际问题是什么或导致它的原因,您最好的选择可能是遵循我在回答类似问题时概述的调试步骤。


推荐阅读