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

PowerShell读取含日期格式化的文件路径无法解析的问题求助

解决PowerShell读取带日期表达式的文件路径不解析问题

问题核心是Get-Content读取的是纯文本字符串,不会自动解析其中的PowerShell变量或表达式(比如$(Get-Date...))。要实现动态解析这些路径,你需要显式执行字符串中的表达式逻辑,以下是具体解决方案:

修改后的脚本

$dateFormat = 'ddMMyyyy'
$1dayAgo = (Get-Date).AddDays(-1)
$FileList = '\\serverName\FileChecks\FileCheckList.txt'
$Checks = Get-content $FileList
$location = 'The following File has not been generated: '
$PSEmailServer = 'eu-smtp-outbound-1.mimecast.com'

foreach ($Check in $Checks) {
    # 解析路径中的PowerShell表达式
    try {
        $resolvedPath = Invoke-Expression -Command "`"$Check`""
    }
    catch {
        Write-Error "解析路径 '$Check' 失败: $_"
        continue
    }

    if (Test-Path -Path $resolvedPath -PathType Leaf) {
        Write-Output "文件存在: $resolvedPath"
    }
    else {
        $body = "$location$resolvedPath"
        Write-Output $body
        Send-MailMessage -From 'sending@emailaddress.com' `
                         -To 'recieving@emailaddress.com' `
                         -SmtpServer 'eu-smtp-outbound-1.mimecast.com' `
                         -Port 25 `
                         -Subject "File Missing" `
                         -Body $body
    }
}

关键修改说明

  1. 路径解析:通过Invoke-Expression将读取到的字符串作为PowerShell代码执行,解析其中的$(Get-Date...)表达式,生成真实的文件路径。注意:仅当你完全信任FileCheckList.txt的内容时使用此方法,避免执行恶意代码。
  2. 错误处理:添加try/catch块捕获路径解析失败的情况,防止脚本直接崩溃。
  3. 语法修正:修复Send-MailMessage中-Port参数的格式问题(参数名与值之间需加空格),补充$PSEmailServer的赋值确保邮件发送正常。
  4. 输出优化:调整输出信息,明确显示解析后的路径,便于排查问题。

更安全的替代方案

若担心Invoke-Expression的安全风险,可以在文本文件中使用自定义占位符,脚本中手动替换:

  • 文本文件示例:\\Serverlocation\foldername\Filename{yyyyMMdd}.csv、\\linapp04\Applications\Data\LP_Holdings\LP_Holdings_{1dayAgo-ddMMyyyy}.csv
  • 脚本替换逻辑:
$resolvedPath = $Check -replace '{yyyyMMdd}', (Get-Date -Format 'yyyyMMdd')
$resolvedPath = $resolvedPath -replace '{1dayAgo-ddMMyyyy}', (Get-Date -Date $1dayAgo -Format $dateFormat)

这种方式更可控,避免执行未知代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 05:44:59