PowerShell计算跨年度季度末日期返回两个值的问题求助
问题原因
- PowerShell 函数中所有未被捕获的输出都会作为返回值的一部分返回,你在
if ($month -eq 12)代码块中直接执行$year + 1没有赋值给变量,这个计算得到的年份会直接输出,最终和后续switch语句返回的日期一起构成了两个返回值。 - 同时存在逻辑bug:
$year + 1的结果没有赋值给$year变量,switch中12月分支依旧使用原年份计算日期,最终返回的季度末年份也是错误的。
修正方案
直接修改if块的逻辑,把计算后的年份赋值给$year变量,不要直接输出计算结果即可:
Function QuarterEnd($today) { $year = $today.year $month = $today.month if ($month -eq 12) { # 仅赋值不直接输出,避免多余返回值 $year = $year + 1 } Switch ($month) { 1 { Get-Date -Date "$year-03-31T00:00:00" } 2 { Get-Date -Date "$year-03-31T00:00:00" } 3 { Get-Date -Date "$year-06-30T00:00:00" } 4 { Get-Date -Date "$year-06-30T00:00:00" } 5 { Get-Date -Date "$year-06-30T00:00:00" } 6 { Get-Date -Date "$year-09-30T00:00:00" } 7 { Get-Date -Date "$year-09-30T00:00:00" } 8 { Get-Date -Date "$year-09-30T00:00:00" } 9 { Get-Date -Date "$year-12-31T00:00:00" } 10 { Get-Date -Date "$year-12-31T00:00:00" } 11 { Get-Date -Date "$year-12-31T00:00:00" } 12 { Get-Date -Date "$year-03-31T00:00:00" } } }
调用方式
保持原有调用逻辑不变即可:.\quarterdate.ps1; QuarterEnd $(Get-Date)
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

