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

PowerShell字符串拆分异常求助:计数正确但无法显示元素

问题分析与解决

你的代码存在两个关键问题:

1. foreach循环变量引用错误

你在foreach循环里使用了$_,但这个是PowerShell的管道自动变量,在foreach ($string in $substrings)这种遍历逻辑下,必须用你定义的循环变量$string才能输出每个排除项。

2. -split的正则分隔符未正确处理

|是正则表达式里的交替运算符,直接用-split "|"会让PowerShell按正则规则解析,虽然这次碰巧得到了正确的元素数量,但逻辑上不可靠。正确的做法是按字面量分割|,有三种实现方式:

  • 用[regex]::Escape()转义分隔符:$substrings = $exclusions -split [regex]::Escape("|")
  • 直接转义|字符:$substrings = $exclusions -split "\|"
  • 添加SimpleMatch参数强制字面分割:$substrings = $exclusions -split "|", 0, "SimpleMatch"

关于反斜杠的疑问:原字符串中的反斜杠是用来转义正则里的.,它属于每个排除项的内容,不会干扰-split调用,无需担心。

修正后的完整代码

# Regular expression of files/folders to exclude from the search
$exclusions =  "\.bak| - Copy|\.db|\.ini|\.log|\.temp|template|test|\.tmp|New-Folder|prototype|_vti"
$substrings = $exclusions -split [regex]::Escape("|")
$substrings
$count      = $substrings.count
Write-Host "Number of exclusions: $count"
foreach ($string in $substrings) {
      Write-Host "► $string"
}

运行修正后的代码,就能正确显示每个排除项了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 03:27:48