Powershell 循环到从当前日期起减去15天
我正在尝试找出调用需要日期范围参数(例如:20130801-20130815)的exe的最佳方式,然后循环它,使其减少15天,并使用新的日期范围调用exe 我曾想过使用do-until,但我不确定如何使用(powershell/编程的新功能),但我确定这远远不是正确的方法:)。我刚刚开始了解这一点,因此提前感谢您的帮助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
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
始终返回字符串)。通过返回对象,可以将其送入管道(使用管道|
)
myWrite 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)