如何在Power Shell中正确增加不同月份中的日期('yyyy-mm-dd') [英] How to increment date ('yyyy-mm-dd') in different months period correctly in Power Shell

查看:89
本文介绍了如何在Power Shell中正确增加不同月份中的日期('yyyy-mm-dd')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我问一下如何在PowerShell中正确地增加日期. 我们想获取指定时期内格式为"yyyy-mm-dd"的日期列表, 将它们传递给其他程序.

Let me ask how to increment date correctly in PowerShell. We'd like to get date list in format 'yyyy-mm-dd' in designated period, to pass them to other programs.

例如,当DateStart ='2018-01-05'和DateEnd ='2018-01-08'时,日期列表应为;

For example, when DateStart='2018-01-05' and DateEnd='2018-01-08', then the date list should be;

2018-01-05
2018-01-06
2018-01-07
2018-01-08

目前,我的脚本可以在同一个月的指定时间段内正常工作,就像上述情况一样,但不能在不同月份使用.

Currently, my script can work as long as the designated period in the same month, like above case, but can't work in different month.

#Get_DateRange.ps1

param(
  [String] $DateStart,     
  [String] $DateEnd
)

# Variables Set
$StartDT = [Datetime]::ParseExact($DateStart,"yyyy-mm-dd",$null).AddDays(-1)
$EndDT   = [Datetime]::ParseExact($DateEnd,"yyyy-mm-dd",$null)

# Return Date List during designated period 
do
 {
  $StartDT = $StartDT.AddDays(1)
  $StartDT.toString("yyyy-mm-dd")
 } While ($StartDT -lt $EndDT)

作为错误的情况,当DateStart ='2018-01-31'和DateEnd ='2018-02-05'时,它仅返回'2018-01-31'.

As wrong case, when DateStart='2018-01-31' and DateEnd='2018-02-05', it only returned '2018-01-31'.

我显然理解我的脚本有问题,但是到目前为止我还不知道.任何建议将不胜感激.

I understand obviously something wrong with my script, but so far I have no idea. Any advice would be appreciated again.

谢谢.

其他信息: 我们想像这样在其他批处理中使用上述脚本;

Additional Info: We'd like to use above script in other batch like this;

FOR /F %%d IN ('%PS_EXE%  -ExecutionPolicy ByPass  -File "Get_DateRange.ps1" -DateStart %EXT_START_DT% -DateEnd %EXT_END_DT%') DO (
@ECHO %FILE_ID%,%%d,%TARGET_DB%,%TARGET_SCHEMA%,%TARGET_TABLE%,'%%d',gz,%TARGET_DB%,%TARGET_TABLE%>>%EXT_FILE_NAME%
)

推荐答案

OK似乎所有yyyy-mm-dd确实存在问题的地方应该是yyyy-MM-dd

OK looks like all that was really wrong with the yyyy-mm-dd should have been yyyy-MM-dd

function Get-Dates(){
    param(
        [String] $DateStart,     
        [String] $DateEnd
    )
    # Variables Set
    $StartDT = [Datetime]::ParseExact($DateStart,"yyyy-MM-dd",$null).AddDays(-1)
    $EndDT   = [Datetime]::ParseExact($DateEnd,"yyyy-MM-dd",$null)
    # Return Date List during designated period 
    While ($StartDT -lt $EndDT){
        $StartDT = $StartDT.AddDays(1)
        $StartDT.toString("yyyy-MM-dd")
    }

}

Get-Dates -DateStart "2018-11-29" -DateEnd "2018-12-03"

返回

2018-11-29
2018-11-30
2018-12-01
2018-12-02
2018-12-03

这篇关于如何在Power Shell中正确增加不同月份中的日期('yyyy-mm-dd')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆