如何在 Powershell 中按第三列对对象进行排序?

如何在 Powershell 中按第三列对对象进行排序?

我有一个这样的文本文件:

4108689096 2531 ./ssss/132432.odt
481446057 2293 ./abc/a.txt
3157353085 1096 ./dsjvbjf/c.docx
653380669 1824 ./bcd/x.avi

我想在 Powershell 中按第三列对列表进行排序,但无论我做什么Sort-Object,似乎都按文件名(按每/行最后一个字符之后的第一个字符)对该列表进行排序。

我想实现这样的目标:

481446057 2293 ./abc/a.txt
653380669 1824 ./bcd/x.avi
3157353085 1096 ./dsjvbjf/c.docx
4108689096 2531 ./ssss/132432.odt

所以我想按第三列作为包含.,/字符的字符串进行排序。


编辑#1:一些相关代码

# Gets a relative path based on a base and a full path (to file)
# 
# Usage: RelativePath <path to file> <base path>
# 
# Note: Specifying arguments is mandatory.
function global:RelativePath
{
    param
    (
        [string]$path = $(throw "Missing: path"),
        [string]$basepath = $(throw "Missing: base path")
    )

    return [system.io.path]::GetFullPath($path).SubString([system.io.path]::GetFullPath($basepath).Length + 1)
}

# Calculates CRC checksums for all files in the specified directory and writes
# the checksums to a file
# 
# Usage: CRCSumAll <path to folder to check> <file conatining checksums>
# 
# Note: Specifying arguments is mandatory.
function global:CRCSumAll
{
    param($inputpath,$outputfile)

    $allfiles=get-childitem $inputpath -rec | Where-Object {!($_.psiscontainer)} | Sort-Object Name

    new-item -force -type file $outputfile

    cd $inputpath
    foreach ($file in $allfiles)
    {
        $relfile=RelativePath $file.fullname $inputpath
        $relfile=$relfile -replace("\\","/")
        $relfile="./$relfile"
        cksum.exe $relfile | Out-File -Encoding OEM -Append $outputfile
    }
}

编辑#2:解决方案

我意识到问题出在哪里了。我在排序后添加了相对路径。所以正确的代码是:

function global:CRCSumAll
{
    param($inputpath,$outputfile)

    $allfiles=get-childitem $inputpath -rec | Where-Object {!($_.psiscontainer)} #| Sort-Object Name

    new-item -force -type file $outputfile

    cd $inputpath
    foreach ($file in $allfiles)
    {
        $relfile=RelativePath $file.fullname $inputpath
        $relfile=$relfile -replace("\\","/")
        $relfile="./$relfile"
        $relfile | Out-File -Encoding OEM -Append $outputfile
    }

    $sorted=Get-Content $outputfile | Sort-Object
    new-item -force -type file $outputfile
    $sorted | Out-File -Encoding OEM -Append $outputfile

    $forcksum=Get-Content $outputfile
    new-item -force -type file $outputfile
    $forcksum | Foreach-Object { cksum.exe $_ | Out-File -Encoding OEM -Append $outputfile}
}

现在我只需要稍微清理一下代码,因为三次写入文件确实很难看。:)

答案1

尝试这样的操作:

Import-CSV C:\Path\To\File.txt -Header ('foo', 'bar', 'wombat') -delimiter ' ' | Sort-Object wombat

我将保留我原来的答案,因为只要输入具有明确定义的列,它就符合标准。根据评论,解决方案是在创建时对数组进行排序:

$allfiles=get-childitem $inputpath -rec | Where-Object {!($_.psiscontainer)} | Sort-Object Name
cd $inputpath
foreach ($file in $allfiles) {cksum.exe $file | Out-File -Append $pathtooutputfile}

相关内容