Powershell脚本在通过任务计划程序自动运行时创建空zip文件,但在手动运行时有效

时间:2014-08-11 13:00:43

标签: windows powershell zip scheduled-tasks

以下是我的脚本的全文,其中包含业务敏感数据,并替换为通用名称。

function Add-Zip
{
    param([string]$zipfilename)

    if(-not (test-path($zipfilename)))
    {
        set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
        (dir $zipfilename).IsReadOnly = $false  
    }

    $shellApplication = new-object -com shell.application
    $zipPackage = $shellApplication.NameSpace($zipfilename)

    foreach($file in $input) 
    { 
            $zipPackage.CopyHere($file.FullName)
            Start-sleep -milliseconds 500
    }
}

$emailFrom = "server@server.com"
$emailTo = "supportgroup@server.com"
$emailSubject = "Title of script"
$smtpServer = "smtpserver"
$emailBody = "Script: C:\pathtoscript\script.ps1`r`n`r`n"

Try {
    $sourcepath = '\\remotepath1\'
    $destpath = '\\remotepath2\'
    $sourcefiles = $($sourcepath + '*.txt')
    $es = ""
    [regex]$regex = '(Rr)egex\.txt'
    $gci = (Get-ChildItem $sourcefiles | sort LastWriteTime | select -last 1)
    $txtfile = $regex.Matches($gci) | foreach-object {$_.Value}
    $oldtxtfile = Get-Content 'C:\pathtoscript\script.cfg'
    if ($txtfile -eq $oldtxtfile) {
        throw "No new file found."
    }
    echo $txtfile > 'C:\pathtoscript\script.cfg'
    $txt2file = $txtfile.Replace('.txt', '.txt2')
    $zipname = $txtfile.Replace('.txt', '.zip')
    $txtpath = $($sourcepath + $txtfile)
    $txt2path = $($destpath + $txt2file)
    $zippath = $($sourcepath + $zipname)
    get-childitem $txtpath | Add-Zip $zippath
    if ((get-item $zippath).length -lt 5kb) {
        throw $zippath + " is empty."
    }
    $emailBody = "Successfully zipped:`r`n" + $txtpath + " into " + $zippath + "`r`n`r`n"
    move-item $zippath $destpath
    $emailBody = $emailBody + "Successfully moved:`r`n" + $zippath + " to: " + $destpath + "`r`n`r`n"
    echo $es > $txt2path
    $emailSubject = $emailSubject + ' [Success]'
    $emailBody = $emailBody + "Successfully created:`r`n" + $cmppath
}
Catch [system.exception]{
    $emailSubject = $emailSubject + " [Failure]"
    $emailBody = "`r`n*****Exception Caught*****`r`n" + $_.Exception.ToString()
    $emailTo = "ticket@server.com"
}
Finally {
    $emailBody = $emailBody + "`r`n`r`nEnd: " + (Get-Date -format G)

    Send-MailMessage -from $emailFrom -to $emailTo -subject $emailSubject -body $emailBody -smtpserver $smtpServer
    exit
}

这里的想法是这个脚本每个星期一运行,以获取一个文件,该文件在周日通过ftp上传到服务器,压缩它,并创建一个空的伴随文件,以便放在一个不同的位置,在那里它们被选中通过不同的自动化过程。该脚本在手动运行时运行完美,但是,我现在将其设置为在Windows任务计划程序中的每个星期一运行 - 脚本运行,但会抛出位于第47行的空zip例外。如果我手动运行脚本(这需要删除cfg文件的内容),它没有问题。

我不确定有关任务调度程序的哪些信息很重要,所以这里有一些基本信息,如果您需要更多,请问我。

在属性的“常规”选项卡中: 无论用户是否登录,都设置为“运行”。它被设置为以最高权限运行。

对于触发器,它在每个星期一每周运行

操作是以完整的脚本路径作为参数

启动powershell.exe

对于条件,它设置为:如果计算机停止空闲则停止,仅在计算机处于交流电源时启动任务,如果计算机切换到电池电源则停止

设置说:允许任务按需运行,如果任务运行时间超过1小时则停止任务,如果正在运行的任务未在请求时结束,则强制停止

历史记录显示任务已正确执行。

0 个答案:

没有答案