当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 将时间跨度转换为重复模式

作者:精品下载站 日期:2024-12-14 07:45:58 浏览:14 分类:玩电脑

将时间跨度转换为重复模式


在 Petri.com 上,我最近发布了一篇关于创建支持重复间隔的每日或每周计划 PowerShell 作业的后续文章。简短的答案是使用计划任务 cmdlet。在 Petri 文章中,我谈到需要对时间跨度使用特殊的字符串格式。它在 MSDN 上有记录。

解决这个问题并不是特别困难,但我认为使用 PowerShell 函数将时间跨度转换为这种格式会很方便。

Function ConvertTo-RepetitionPattern {
<#
.Synopsis
Convert a timespan to an XML repetition pattern
.Description
When creating scheduled tasks, repetition duration and intervals must be set using a special XML format.

P<days>DT<hours>H<minutes>M<seconds>S

The minimum time allowed is 1 minute and the maximum is 31 days.
.Example
PS C:\> new-timespan -Minutes 10 | ConvertTo-RepetitionPattern
PT10M
.Example
PS C:\> ConvertTo-RepetitionPattern "0:1:10:0"
PT1H10M
.Link
https://msdn.microsoft.com/en-us/library/windows/desktop/aa382117%28v=vs.85%29.aspx#properties
.Link
New-Timespan
#>
[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory,HelpMessage = "Enter a timespan",
ValueFromPipeline)]
[ValidateScript({$_.totalminutes -ge 1 -AND $_.totaldays -le 31})]
[timespan]$Timespan
)

Begin {
    Write-Verbose "Starting $($MyInvocation.Mycommand)"
    [string]$pattern = "P"  
} #begin

Process {
    Write-Verbose "Converting $Timespan"
    if ($Timespan.Days -gt 0) {
        Write-Verbose "$($timespan.days) Days"
        $Pattern+= "{0}D" -f $Timespan.Days
    }
    #insert T separater
    $Pattern+="T"

    if ($Timespan.Hours -gt 0) {
    Write-Verbose "$($timespan.hours) Hours"
        $Pattern+= "{0}H" -f $Timespan.hours
    }
    if ($Timespan.Minutes -gt 0) {
    Write-Verbose "$($timespan.Minutes) Minutes"
        $Pattern+= "{0}M" -f $Timespan.Minutes
    }
    if ($Timespan.Seconds -gt 0) {
        Write-Verbose "$($timespan.seconds) Seconds"
        $Pattern+= "{0}S" -f $Timespan.Seconds
    }

    #write the result to the pipeline
    $pattern
}
End {
    Write-Verbose "Ending $($MyInvocation.Mycommand)"
} #end

} #end function

从技术上讲,该模式将支持任何时间跨度,但由于计划任务使用的模式必须在 1 分钟到 31 天之间,因此我将其添加为验证参数。该函数只是根据日期时间元素的数量(即小时、分钟和秒)构建最终字符串。

希望此功能可以更轻松地自动化计划的作业和任务流程。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯