【问题标题】:How to get last day of specified month in powershell如何在powershell中获取指定月份的最后一天
【发布时间】:2017-10-27 18:20:09
【问题描述】:

我需要从指定的前一个月的最后一天。 我有一个字符串(文件名),它的末尾包含一个日期。我需要捕获日期(已经完成)并获取上个月的最后一个日期。例如字符串是“proemail vytvoreni_9.2017 2017-10-16”,所以我需要得到 2017 年 9 月 30 日。这就是我现在所拥有的:

$Report = Read-Host "File name"
$Date = [datetime]$Report.Substring($Report.get_Length()-10)
$Last_month = $Date.AddMonths(-1)
$Date_text = $Last_month.ToString().Substring(3,7)
$month_year = ($Date_text.Split("."))
$days_count = [datetime]::DaysInMonth($month_year[1],$month_year[0])
$days_count = $days_count.ToString()
$month = $month_year[0]
$year = $month_year[1]
$Date_limit = [DateTime]($month,$days_count,$year)

一切正常,除了最后一行,返回此错误:无法将“System.Object[]”类型的“System.Object[]”值转换为“System.DateTime”类型。我尝试通过 .ToString() 方法将 $month 和 $year 转换为字符串,但没有帮助

【问题讨论】:

    标签: powershell date


    【解决方案1】:
    (Get-Date).AddDays(-$(Get-Date).Day)
    
    Saturday, September 30, 2017 2:36:19 PM
    
    
    ((Get-Date).AddDays(-$(Get-Date).Day)).Day
    
    30
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    【解决方案2】:
    $filename = "proemail vytvoreni_9.2017 2017-10-16"
    
    # Take the date from the filename
    $sub = $filename.Substring($filename.Length-10)
    
    # make it into a date format
    $filedate = Get-Date -Date $sub
    
    # take that date 2017-10-16 and substracts its own days so in this case substract 16 days, then show me the date
    (($filedate).AddDays(-$filedate.Day)).Date
    

    输出:

    2017 年 9 月 30 日星期六 0:00:00

    【讨论】:

      猜你喜欢
      • 2011-11-24
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      • 2019-05-03
      相关资源
      最近更新 更多