【问题标题】:Parse Text with Powershell Using IndexOf使用 IndexOf 使用 Powershell 解析文本
【发布时间】:2021-09-11 20:00:56
【问题描述】:

我已阅读此处引用的所有文章,但我的代码中遗漏了一些明显的内容。我有以下文本文件:

d:/mev/doc1.xls
d:/mev/doc2.xls
d:/mev/doc3.xls
d:/mev/doc4.doc
d:/mev/doc5.doc

我正在尝试解析所有以 .xls 作为扩展名的文件。解析代码似乎正在工作,但它没有循环遍历整个文件。这是我的代码:

$array = Get-Content "Q:\mev\pattern.txt" -raw
foreach($item in $array)
{     
    $firstref = $array.IndexOf("/mev/")
    $lastref = $array.IndexOf("xls")
    $array.Substring($firstindex+7,$lastref+2)
} 

这是输出:

PS Q:\mev> .\read3.ps1
doc1.xls
d:/m

我到底错过了什么?

提前感谢您的帮助!

【问题讨论】:

  • 我们还没有收到您的来信.. 我的回答解决了您的问题吗?如果是这样,请通过单击左侧的 图标来考虑accepting。这将帮助其他有类似问题的人更轻松地找到它,并有助于激励其他人回答您将来可能遇到的任何问题。

标签: powershell parsing indexof


【解决方案1】:

您需要删除-Raw 开关,因为您想遍历文件中的每一行。使用-Raw,文件将被读取为单个多行字符串而不是数组。

还有,为什么这么难?如果我理解正确,这将返回您所寻求的:

Get-Content "Q:\mev\pattern.txt" |
Where-Object { $_ -like '*.xls' }

如果您只需要没有路径的文件名,请追加 | ForEach-Object { [System.IO.Path]::GetFileName($_)} 到那个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 2020-12-30
    相关资源
    最近更新 更多