Home > database >  Powershell split file name and export to csv
Powershell split file name and export to csv

Time:12-07

I have lot of files in the folder in this nameing format "yyyy-mm-dd_Discription_$Amount.pdf" , how do I make powershell script that creates csv file with three columns (Date , Description and Amount)?

I am able to extract the full file name in the below, but I need help to split and make columns.

$Directory = "C:\path to directory"
Get-ChildItem -Path $Directory -Recurse -Force | ForEach {

    [PSCustomObject]@{                 
        Name = $_.BaseName          
    }
    
} | Export-Csv -Path "./temp.csv" -NoTypeInformation


I have tried this below

$Directory = "C:\path to directory"
Get-ChildItem -Path $Directory -Recurse -Force | ForEach {

    [PSCustomObject]@{                 
        Name = $_.BaseName          
    }
    
} | Export-Csv -Path "./temp.csv" -NoTypeInformation


CodePudding user response:

This will work

$Directory = '.'

(Get-ChildItem -Path $Directory -File).BaseName | Select `
    @{l='Date'; e={$_.Split('_')[0]}},
    @{l='Description'; e={$_.Split('_')[1]}},
    @{l='Amount'; e={$_.Split('_')[2]}} |
        ConvertTo-Csv -NoTypeInformation
  • Related