任务调度程序powershell脚本永不结束

mcvgt66p  于 2023-03-08  发布在  Shell
关注(0)|答案(4)|浏览(306)

我有一个脚本,手动运行效果很好。但是,当我在“任务计划程序”中计划它时,脚本永远不会结束,所以下次尝试运行时,它会失败,因为前一个示例仍在运行。脚本本身需要几秒钟才能完成第一次或手动运行。以下是脚本:

$source = "\\server1\upload"
$destination = "\\server2\upload"
$logfile = "c:\Scripts\fileMover\log.txt"
$table = Get-ChildItem $source -include *
foreach ($file in $table){
    $filename = $file.FullName
    #write-host $filename
    try
    {
        move-item -LiteralPath $filename -destination $destination -force
        $body = "Successfully moved $filename to $destination"
        $subject = "fileMover Succeeded"
    }
    catch
    {
        $body = "Failed to move $filename to $destination"
        $subject = "fileMover Failed"
    }
    finally
    {
        $body | out-file $logfile -append -width 1000 -encoding ascii
        Send-MailMessage -To "filemoverconfirmations@domain.com" -From "uploader@domain.com" -Subject $subject -SmtpServer "10.1.10.1" -Body $body
        exit
    }
}
exit

使用以下设置计划脚本:

  • 无论用户是否登录都运行(用户帐户已被授予作为批处理程序登录的权限)
  • 以最高权限运行
  • 每日触发,每2分钟
  • 操作:启动程序powershell -文件c:\Scripts\upload.ps1

作为一种解决方法,我将任务配置为在1分钟后自动停止。但是,我担心在某些情况下--比如大量的大文件--脚本可能会在完全完成之前终止。
脚本需要每2分钟运行一次。

e4eetjau

e4eetjau1#

我在尝试直接执行.ps1文件时遇到了这个问题。执行Powershell并将脚本作为参数提供给它。
计划任务操作选项卡:

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

添加参数(可选):
-command & 'E:\PowerShell_scripts\Script_name.ps1’

68bkxrlz

68bkxrlz2#

这听起来可能很傻,但我最初遇到了与其他答案中详细描述的相同的问题-试图直接运行.ps1脚本,而不是通过powershell.exe。自从看到记事本打开后,我就解决了这一部分,但在纠正我的错误后,它仍然报告 Running
解决方案?x1c 0d1x更新

nsc4cvqm

nsc4cvqm3#

对于“Start a program”操作,将powershell列为“Program/script”,并在“Add arguments(optional)”框中输入要运行的脚本的路径。
如果您试图通过直接将PowerShell脚本列为“程序/脚本”来“运行”脚本,则操作永远不会完成,因为记事本是与.ps1扩展关联的默认应用程序(以帮助用户避免意外运行PowerShell脚本),因此它会在记事本中在后台打开脚本,而不是执行脚本。记事本永远不会自行关闭。

pkbketx9

pkbketx94#

1.首先按F5刷新,检查Running状态是否改变。
1.如果program/script填写了脚本路径,应确保 * powershell.exe * 是运行runscript的默认程序。
1.如果不确定,请使用C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe填充程序/脚本
并将**Add arguments(可选)**填充为
-File "C:\Users\Administrator\OneDrive\automation.ps1"

相关问题