You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中判断当月最后一天是否为周五,用函数返回True

判断当月最后一天是否为周五的PowerShell实现

方法一:直接判断当月最后一天的星期(更简洁)

不需要额外获取最后一个周五,直接定位到当月最后一天,检查其星期是否为周五即可:

function Test-LastDayIsFriday {
    param([DateTime]$Date = (Get-Date))
    # 获取当月最后一天的日期对象
    $lastDayDate = [DateTime]::new($Date.Year, $Date.Month, [DateTime]::DaysInMonth($Date.Year, $Date.Month))
    # 判断是否为周五
    return $lastDayDate.DayOfWeek -eq [DayOfWeek]::Friday
}

# 测试示例
Test-LastDayIsFriday  # 检查当前月份
Test-LastDayIsFriday (Get-Date "2025-01-01")  # 2025年1月最后一天是周五,返回True
Test-LastDayIsFriday (Get-Date "2024-06-01")  # 2024年6月最后一天是周一,返回False

方法二:结合你已有的Get-LastFridayOfMonth函数判断

如果要复用你已经实现的获取最后一个周五的函数,只需比较该函数返回的日期与当月最后一天是否相等:

function Get-LastFridayOfMonth([DateTime] $d) {
    $lastDay = new-object DateTime($d.Year, $d.Month,[DateTime]::DaysInMonth($d.Year, $d.Month))
    $diff = ([int] [DayOfWeek]::Friday) - ([int] $lastDay.DayOfWeek)
    if ($diff -gt 0) {
        return $lastDay.AddDays(- (7-$diff))
    } else {
        return $lastDay.AddDays($diff)
    }
}

function Test-LastDayIsFriday {
    param([DateTime]$Date = (Get-Date))
    $lastFriday = Get-LastFridayOfMonth $Date
    $lastDayDate = [DateTime]::new($Date.Year, $Date.Month, [DateTime]::DaysInMonth($Date.Year, $Date.Month))
    # 比较最后一个周五是否等于当月最后一天
    return $lastFriday -eq $lastDayDate
}

# 测试示例
Test-LastDayIsFriday

逻辑说明

  • 方法一直接聚焦核心需求:只要确认当月最后一天的星期是周五即可,步骤更少,性能更优。
  • 方法二利用你已有的函数,通过日期相等性判断,验证最后一个周五是否恰好是当月的最后一天。

内容的提问来源于stack exchange,提问作者Knut W

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 05:30:47