Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 循环到从当前日期起减去15天_Powershell_Powershell 2.0_Powershell 3.0 - Fatal编程技术网

Powershell 循环到从当前日期起减去15天

Powershell 循环到从当前日期起减去15天,powershell,powershell-2.0,powershell-3.0,Powershell,Powershell 2.0,Powershell 3.0,我正在尝试找出调用需要日期范围参数(例如:20130801-20130815)的exe的最佳方式,然后循环它,使其减少15天,并使用新的日期范围调用exe 我曾想过使用do-until,但我不确定如何使用(powershell/编程的新功能),但我确定这远远不是正确的方法:)。我刚刚开始了解这一点,因此提前感谢您的帮助 do { $startDate = (Get-Date).adddays(-34) $requireddate = some date that is set

我正在尝试找出调用需要日期范围参数(例如:20130801-20130815)的exe的最佳方式,然后循环它,使其减少15天,并使用新的日期范围调用exe

我曾想过使用do-until,但我不确定如何使用(powershell/编程的新功能),但我确定这远远不是正确的方法:)。我刚刚开始了解这一点,因此提前感谢您的帮助

do {

    $startDate = (Get-Date).adddays(-34)
    $requireddate = some date that is set ad-hoc
    $startdate.ToString("yyyyMMdd")

    #[datetime]::parseexact($startdate,"MMddyyyy",$null)

    Call THE EXE at this point with the parameters $startdate and $enddate

    $enddate = $startdate.AddDays(-15) 

    write-host $enddate.ToString("yyyyMMdd")
    }
until ($enddate -eq $requireddate)

有很多方法。如果要使用特定于Powershell的方法(而不是do..until或while(){}),则可以使用管道:

0..15 | %{
  $changingDate = $startdate.AddDays(-$_)
  #do your work with the .exe & $changingDate
  $changingDate
}

您也可以使用For循环来完成您试图实现的目标:

(我把事情分成了一些变量,我发现这在编写函数时很有帮助)

使用
Write Output
意味着返回的内容将作为对象返回(而
Write Host
始终返回字符串)。通过返回对象,可以将其送入管道(使用管道
|

my
Write Output
中的$(
code
)语法意味着在返回字符串(作为对象)之前,将对括号内的内容进行求值

如果您经常使用它,您可以更进一步,使其成为参数化函数:

Function Get-DateRange
{
Param(
[datetime]$startDate,
[int]$endAddDays,
[datetime]$requiredDate
)

    for($i = $startDate; $i -lt $requiredDate; $i = $i.AddDays(1))
    {

        Write-Output "$($i.ToString("yyyyMMdd"))-$($i.AddDays($endAddDays).ToString("yyyyMMdd"))"

    }

}
然后,您可以通过如下方式调用它(一旦加载到会话中):

Get-DateRange -startDate (get-Date).AddDays(-10) -endAddDays 15 -requiredDate (get-Date).AddDays(15)
另外,如果您想编写函数,最好尽量使用典型的Powershell动词。运行
get verb | sort verb
查看整个列表:

Get-DateRange -startDate (get-Date).AddDays(-10) -endAddDays 15 -requiredDate (get-Date).AddDays(15)