Alon Segal
Alon Segal

Reputation: 59

Splitting CSV cell (but leave the original as is) using Powershell

I'm trying to add some pdf's files from a directory into csv file.

I'm using the below PowerShell script to add the PDFs but the issue is that I need to split (but leave the original PDF path on each file as is) the path numbers into calls.

Is there any way to accomplish this one?

Get-ChildItem -Recurse "C:\Users\alon\Desktop\MYpdf\" |
    ForEach-Object {
        $_ | Add-Member -Name "Owner" -MemberType NoteProperty -Value (Get-Acl $_.FullName).Owner -PassThru
    } |
    Sort-Object FullName |
    Select FullName, CreationTime, LastWriteTime, Length, Owner | 
    Export-Csv -Force -NoTypeInformation "C:\Users\alon\Desktop\MYpdf\directory.csv"

The output should be like this:

enter image description here

Upvotes: 1

Views: 47

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200493

You mean you want to add the numbers from the filename as additional fields in your output? I would split each file's basename and construct custom objects from that information and the file metadata:

Get-ChildItem ... |
    ForEach-Object {
        $numbers = $_.BaseName -split '_'

        [PSCustomObject]@{
          FullName      = $_.FullName
          Company       = [int]$numbers[0]
          Invoice       = [int]$numbers[1]
          Deal          = [int]$numbers[2]
          Customer      = [int]$numbers[3]
          Autonumber    = [int]$numbers[4]
          CreationTime  = $_.CreationTime
          LastWriteTime = $_.LastWriteTime
          Length        = $_.Length
          Owner         = (Get-Acl $_.FullName).Owner
    } |
    Sort-Object FullName |
    Export-Csv ...

Using calculated properties would also work, but in this case constructing new objects is arguably the simpler approach.

Note that the [PSCustomObject] type accelerator requires PowerShell v3 or newer. On older versions you can create the objects via New-Object and then use Select-Object to get the properties in a defined order.

Upvotes: 1

Related Questions