You need to enable JavaScript to run this app. PowerShell中使用Select-Object如何逐行提取字符串指定片段
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中使用Select-Object如何逐行提取字符串指定片段

PowerShell脚本修改方案

问题原因

你之前使用Split()出现异常的核心原因是:PowerShell中Split()方法传入字符串参数时,默认会把字符串的每个字符都当作独立的分隔符,而不是匹配整个字符串作为分隔符,所以会出现额外删除字符的问题。

实现方案(按你要求的索引截取方式)

直接通过定位两个标记的索引位置截取子串即可,修改后的完整代码如下:

Write-Host "Hello, World!"

# 路径配置
$path = 'C:\Users\Documents\4_Testing\fe\*.ts'
# 匹配规则
$pattern = "dummy,"

Get-ChildItem -Recurse -Path $path | Select-String -Pattern $pattern |
Select-Object FileName,Path,LineNumber,Line,
@{name='Function';expression={
    # 定位dummy,的结束位置
    $startTag = "dummy,"
    $startIndex = $_.Line.IndexOf($startTag) + $startTag.Length
    # 定位startIndex之后第一个?的位置
    $endIndex = $_.Line.IndexOf("?", $startIndex)
    # 截取中间内容并去除前后空格
    $_.Line.Substring($startIndex, $endIndex - $startIndex).Trim()
}} |
Export-Csv 'C:\Users\User\Documents\4_Testing\Output1.csv' -NoTypeInformation

Write-Host "Complete"

补充简化方案(正则匹配)

如果不需要强制用索引截取,用正则提取的写法更简洁容错性更高,对应计算属性的表达式块可以替换为:

expression={
    if($_.Line -match 'dummy,(.*?)\?'){
        $matches[1].Trim()
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 02:54:03