我需要从指定的前一个月的最后一天获得。 我有一个字符串(文件名),其中包含一个日期。我需要捕获日期(已经完成)并获取上个月的最后日期。例如,字符串是“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转换为字符串,但它没有帮助
答案 0 :(得分:2)
(Get-Date).AddDays(-$(Get-Date).Day)
Saturday, September 30, 2017 2:36:19 PM
((Get-Date).AddDays(-$(Get-Date).Day)).Day
30
答案 1 :(得分:0)
$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