首页 > 解决方案 > Powershell迭代文本行会引发异常

问题描述

我正在尝试将大量 .txt 文件解析为我需要的特定格式。

代码的目标是:

这是我的代码:

$targetDir = "E:\home\export\"
$indexDir = "E:\index\"

Get-ChildItem -Path "$indexDir\*" -Include *.txt -Recurse | % {
    $file = $_
    $name = $file | Select -exp BaseName

    get-content $file | select -Skip 39 | select -SkipLast 6 | ForEach-Object {
        $_ = $name + "\" + $_.Remove(53, $_.Length)
    }| set-content $file+"temp"
    move $file+"temp" $file -Force
}

Remove 函数抛出以下异常:

Exception calling "Remove" with "2" argument(s): "Index and count must refer to a location within the string. Parameter name: count"
At E:\create_index_stap2.ps1:9 char:9
+         $_ = $name + "\" + $_.Remove(53, $_.Length)
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentOutOfRangeException

文本文件如下所示:

**********************
Windows PowerShell transcript start
Start time: 20200324111411
Username: MYPC\xorinzor
RunAs User: MYPC\xorinzor
Configuration Name: 
Machine: MYPC (Microsoft Windows NT 10.0.17763.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe
Process ID: 18468
PSVersion: 5.1.17763.1007
PSEdition: Desktop
PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.17763.1007
BuildVersion: 10.0.17763.1007
CLRVersion: 4.0.30319.42000
WSManStackVersion: 3.0
PSRemotingProtocolVersion: 2.3
SerializationVersion: 1.1.0.1
**********************
Transcript started, output file is E:\index\filename.7z.txt

7-Zip 19.00 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2019-02-21

Scanning the drive for archives:
1 file, 29931544 bytes (29 MiB)

Listing archive: E:\home\export\filename.7z

--
Path = E:\home\export\filename.7z
Type = 7z
Physical Size = 29931544
Headers Size = 2281
Method = LZMA2:24
Solid = +
Blocks = 1

   Date      Time    Attr         Size   Compressed  Name
------------------- ----- ------------ ------------  ------------------------
2018-03-17 11:14:44 D....            0            0  Contacts
2018-03-17 13:38:06 D....            0            0  Desktop
2018-03-17 13:22:04 D....            0            0  Documents
2018-02-06 14:14:28 D....            0            0  Documents\Some directory
------------------- ----- ------------ ------------  ------------------------
2018-12-16 07:36:34           43367240     29929263  79 files, 37 folders
**********************
Windows PowerShell transcript end
End time: 20200324111411
**********************

基本上,如果这种情况下的文本文件名为“filename.7z.txt”,我希望得到以下文件内容:

filename.7z\Contacts
filename.7z\Desktop
filename.7z\Documents
filename.7z\Documents\Some directory

为什么我的代码会抛出异常?

标签: powershell

解决方案


这似乎做你想做的事。[咧嘴笑]

但是,由于这是来自脚本,因此重新运行代码以获取所需的用户文件夹看起来可能更容易......也许添加导出到 CSV 或 CliXml,以便您以后可以根据需要重新导入数据。

代码似乎得到了很好的 enuf 注释。如果您有任何问题,请询问... [微笑]

#region >>> fake reading in a text file as an array of lines
#    in real life, use Get-Content
$InStuff = @'
**********************
Windows PowerShell transcript start
Start time: 20200324111411
Username: MYPC\xorinzor
RunAs User: MYPC\xorinzor
Configuration Name: 
Machine: MYPC (Microsoft Windows NT 10.0.17763.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe
Process ID: 18468
PSVersion: 5.1.17763.1007
PSEdition: Desktop
PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.17763.1007
BuildVersion: 10.0.17763.1007
CLRVersion: 4.0.30319.42000
WSManStackVersion: 3.0
PSRemotingProtocolVersion: 2.3
SerializationVersion: 1.1.0.1
**********************
Transcript started, output file is E:\index\filename.7z.txt

7-Zip 19.00 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2019-02-21

Scanning the drive for archives:
1 file, 29931544 bytes (29 MiB)

Listing archive: E:\home\export\filename.7z

--
Path = E:\home\export\filename.7z
Type = 7z
Physical Size = 29931544
Headers Size = 2281
Method = LZMA2:24
Solid = +
Blocks = 1

   Date      Time    Attr         Size   Compressed  Name
------------------- ----- ------------ ------------  ------------------------
2018-03-17 11:14:44 D....            0            0  Contacts
2018-03-17 13:38:06 D....            0            0  Desktop
2018-03-17 13:22:04 D....            0            0  Documents
2018-02-06 14:14:28 D....            0            0  Documents\Some directory
------------------- ----- ------------ ------------  ------------------------
2018-12-16 07:36:34           43367240     29929263  79 files, 37 folders
**********************
Windows PowerShell transcript end
End time: 20200324111411
**********************
'@ -split [System.Environment]::NewLine
#endregion >>> fake reading in a text file as an array of lines

# set the file name prefix
$FileName = 'A_FileName.7z'

# grab the lines starting at the 39th item [array indexes start with zero]
#    & ending 6 lines before the end
$Results = $InStuff[38..($InStuff.GetUpperBound(0) - 6)].
    ForEach({
        # replace the 1st 53 chars with nothing
        $_ -replace '^.{53}', ''
        }).
    # trim away any leading/trailing spaces
    Trim().
    ForEach({
        # concatenate the file name with the remainder of each line
        "$FileName\$_"
        })

# display on screen
$Results

输出 ...

A_FileName.7z\Contacts
A_FileName.7z\Desktop
A_FileName.7z\Documents
A_FileName.7z\Documents\Some directory

推荐阅读