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

如何用PowerShell验证文件存在并按指定格式显示最后修改时间

PowerShell脚本优化:按指定格式关联文件名与修改时间

需要验证路径C:\Windows\System32\drivers\CrowdStrike\下以C-00000291开头的文件是否存在,并让每个文件名紧邻其最后修改时间显示(格式为文件名 Date: 修改时间)。现有脚本输出格式混乱,需调整。

现有脚本

if (Test-Path  "C:\Windows\System32\drivers\CrowdStrike\C-00000291*" -PathType Leaf) {
    $lastModifiedDate = (Get-Item "C:\Windows\System32\drivers\CrowdStrike\C-00000291*").LastWriteTime
    $Name = (Get-Item "C:\Windows\System32\drivers\CrowdStrike\C-00000291*").Name
    Write-Output "File exists. $Name Date: $lastModifiedDate" 
} else {
    Write-Output "File does not exist."
}

当前输出

File exists. Date: C-00000291-00000000-00000036.sys C-00000291-00000000-00000066.sys 07/19/2024 11:46:10 07/19/2024 11:46:22

期望输出

File exists. C-00000291-00000000-00000036.sys Date: 07/19/2024 11:46:10 C-00000291-00000000-00000066.sys Date: 07/19/2024 11:46:22

修正后的脚本

$targetFiles = Get-Item "C:\Windows\System32\drivers\CrowdStrike\C-00000291*" -ErrorAction SilentlyContinue

if ($targetFiles) {
    $outputParts = @("File exists.")
    foreach ($file in $targetFiles) {
        $outputParts += "$($file.Name) Date: $($file.LastWriteTime)"
    }
    Write-Output ($outputParts -join " ")
} else {
    Write-Output "File does not exist."
}

修正说明

  1. 仅执行一次Get-Item获取目标文件集合,避免重复查询文件系统,提升运行效率。
  2. 循环遍历每个文件,将文件名与对应修改时间按要求格式拼接为独立字符串片段。
  3. 用数组收集所有输出片段,最后通过-join " "合并为符合要求的完整输出行,确保每个文件的名称与修改时间成对关联显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 21:32:24