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

PowerShell脚本排除指定文件名失效求助:目标文件仍输出

问题解决:PowerShell排除指定前缀文件失败

你的脚本存在两个关键问题:

  1. 运算符逻辑搞反:-contains/-notcontains要求左侧是集合,右侧是待检查的元素,你写的$sname -notcontains $E_list完全颠倒了逻辑,导致条件永远为真,所有文件都会被输出。
  2. 字符串格式错误:$E_list里的UUID被**包裹,实际执行时这些星号会被当作字符串的一部分,无法匹配文件名里的纯UUID前缀。

修正后的脚本

# 移除UUID字符串中的**标记,确保匹配纯UUID前缀
$E_list= @("a8e4022a-41c4-4480-b627-02fd6ca03413","042d7f01-46da-4f64-b0a8-1fa90e2386d8")

foreach($file in Get-ChildItem $path) {
    # 截取文件名前36位(UUID标准长度)
    $sname = $file.Name.Substring(0,36) 
    # 两种正确的条件写法二选一:
    # 写法1:用-notcontains,集合在前,元素在后
    if ($E_list -notcontains $sname) {
        Write-Output $file.Name
    }
    # 写法2:用-inin(PowerShell 3.0+支持,逻辑更直观)
    # if ($sname -notin $E_list) {
    #     Write-Output $file.Name
    # }
}

额外提示

  • 若你的PowerShell版本低于3.0,只能使用-notcontains的写法;3.0及以上版本推荐用-notin,可读性更强。
  • 如果文件夹里存在文件名长度不足36位的文件,Substring(0,36)会报错,可提前增加长度判断:
    if ($file.Name.Length -ge 36) {
        $sname = $file.Name.Substring(0,36)
        if ($sname -notin $E_list) {
            Write-Output $file.Name
        }
    } else {
        # 根据需求处理短文件名,比如直接输出或跳过
        Write-Output $file.Name
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:54:22