文件名提取和格式化

文件名提取和格式化

我在文件夹 \Testing 中有很多文件,我试图获取文件名并在文本文件中将其格式化为某种方式。例如,文件夹“Testing”中的 111005000_10312019.pdf。我试图获取该文件并将名称格式化为下面的格式,而无需格式化文件本身。

111005000|10/31/2019|111005000_10312019.PDF
123005000|10/31/2019|123005000_10312019.PDF

这些都将保存在一个 txt 文件中。我试过了,但没能做到。有人能帮忙吗?

我的代码是这样的...

    $dir = "C:\Users\aalsraimi\Desktop\Testing\"
$delim = "-"

Get-ChildItem $dir -Name | `
foreach { 
  $nameArray = $_.Split($delim)
  $newName = $nameArray[0]+"+"+$nameArray[1] 
  Write-Output $newName
}

$newName | export-csv -Path "C:\Users\aalsraimi\Desktop\Testing\output.txt" -NoTypeInformation

答案1

如果不知道完成的输出文件的最终目的是什么,可以按照以下方法操作:

$dir = 'C:\Users\aalsraimi\Desktop\Testing'

# first use a coarse Filter on the file names to collect
$names = Get-ChildItem -Path $dir -Filter '*_*.pdf' | 
    # use Where-Object to further specify the wanted format of the file's BaseName (name without extension)
    Where-Object { $_.BaseName -match '^\d{9}_\d{8}$' } | 
    ForEach-Object {
        $parts    = $_.BaseName -split '_'
        $parts[1] = $parts[1] -replace '(\d{2})(\d{2})(\d{4})', '$1/$2/$3'  # format the second part as date
        # next join all parts to format the string you want as output
        '{0}|{1}|{2}' -f $parts[0], $parts[1], $_.Name
    }
# next output the collected strings to file.
# switch '-PassThru' also display the list in the console
$names | Set-Content -Path 'C:\Users\aalsraimi\Desktop\Testing\output.txt' -PassThru

输出

111005000|10/31/2019|111005000_10312019.PDF
123005000|10/31/2019|123005000_10312019.PDF

相关内容