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

如何用PowerShell构建SMB共享中上月最后周五的Excel文件路径

PowerShell自动获取上月最后周五的SMB共享Excel文件路径

需求说明

  • SMB共享文件夹层级:\\hcohesity05\cohesity_reports\年份(4位)\月份(数字)\日期(MM-DD)
  • 目标文件特征:每月最后一个周五生成的Excel文件,文件名固定后缀为-14-26-48.xlsx,前缀格式为Cohesity_FETB_Report-YYYY-MM-DD

实现代码

# 计算上月最后一个周五的日期
$today = Get-Date
# 获取上月第一天
$lastMonthFirstDay = $today.AddMonths(-1).Date.AddDays(-($today.AddMonths(-1).Day - 1))
# 获取上月最后一天
$lastMonthLastDay = $today.AddDays(-$today.Day).Date
# 从最后一天往前找周五(周五对应数字5,周日为0)
$lastFridayOfLastMonth = $lastMonthLastDay
while ($lastFridayOfLastMonth.DayOfWeek -ne [DayOfWeek]::Friday) {
    $lastFridayOfLastMonth = $lastFridayOfLastMonth.AddDays(-1)
}

# 格式化日期为不同所需格式
$year = $lastFridayOfLastMonth.Year.ToString()
$month = $lastFridayOfLastMonth.Month.ToString()
$dateFolder = $lastFridayOfLastMonth.ToString("MM-dd")
$fileNameDate = $lastFridayOfLastMonth.ToString("yyyy-MM-dd")

# 拼接完整文件路径
$filePath = "\\hcohesity05\cohesity_reports\$year\$month\$dateFolder\Cohesity_FETB_Report-$fileNameDate-14-26-48.xlsx"

# 验证文件存在并导入
if (Test-Path -Path $filePath -PathType Leaf) {
    $oldbk = Import-Excel -Path $filePath
    Write-Host "成功导入文件:$filePath"
} else {
    Write-Error "未找到目标文件:$filePath"
}

代码说明

  • 日期计算逻辑:先定位上月最后一天,再从该日期向前遍历,直到找到周五,确保是当月最后一个周五
  • 路径拼接:根据共享文件夹的层级规则,分别格式化年份、月份、日期文件夹名和文件名中的日期部分,自动拼接完整SMB路径
  • 文件验证:通过Test-Path检查文件是否存在,避免导入失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:30:51