filename extract and formatting

I have a lot of files in a folder \Testing, I’m trying to take the file name and format it inside the text file to a certain way. Example would be 111005000_10312019.pdf inside folder “Testing”. I’m trying to take that and format the name to be exactly this below without formatting the files itself.

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

this will be all be in a txt file. I tried it but can’t manage to do it. Can someone assist?

My code is this…

    $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

Answer

Without knowing what your final aim is with the finished output file, here’s how to do what you want:

$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

Output

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

Attribution
Source : Link , Question Author : user1358005 , Answer Author : Theo

Leave a Comment