Kerbol
Kerbol

Reputation: 696

Export to CSV using PowerShell 2.0?

I have the following code that prints the file system rights of each account enabled on the folder with path "C:\Temp\CSM\*" & "C:\Temp\CSM\*\*" . How do I write the output in a comma-separated CSV? As this is for PowerShell 2.0 Export-Csv -Append parameter cannot be used.

$FolderPath = dir -Directory -Path "C:\Temp\CSM\*", "C:\Temp\CSM\*\*" -Force

foreach ($Folder in $FolderPath) {
    $Acl = Get-Acl -Path $Folder.FullName
    foreach ($Access in $acl.Access) {
        Write-Host $Folder.FullName "," $Access.IdentityReference "," $Access.FileSystemRights
    }
}

Upvotes: 1

Views: 588

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

Prior to PowerShell v3 if you wanted to append to an existing CSV you need something like this:

... | ConvertTo-Csv -NoType | Select-Object -Skip 1 | Add-Content

However, in your scenario that probably isn't necessary. If you replace your foreach loops with a pipeline you can write the CSV in one go without having to append to it in a loop (which isn't recommended anyway).

$folders = "C:\Temp\CSM\*", "C:\Temp\CSM\*\*"

Get-ChildItem -Path $folders -Directory -Force | ForEach-Object {
    $path = $_.FullName
    Get-Acl -Path $path |
        Select-Object -Expand Access |
        Select-Object @{n='Path';e={$path}}, IdentityReference, FileSystemRights
} | Export-Csv 'C:\output.csv' -NoType

Upvotes: 1

Related Questions