Kerbol
Kerbol

Reputation: 716

Appending to a File with StreamWriter In PowerShell

I have created a PowerShell script that writes the results of the permissions of folders in windows to a CSV file using StreamWriter. Currently, the script creates a new file for each folder. My questions is, can StreamWriter append to a file instead of creating or overwriting each time. Thanks,

$file_stream_output = New-Object IO.StreamWriter "$path_to_file\results.csv"

$file_stream_output.WriteLine('FolderName,AD Group or User,Permission')

foreach ($directory in $directories_to_search_depth_2[$k]) 
{
$acl = Get-Acl -Path $directory.FullName
    foreach ($access_right in $acl.Access) 
    {
         if ( ($access_right.FileSystemRights -notmatch $exclude_filesystem_rightss_regex) ) 
         {
             $file_stream_output.WriteLine(('{0}, {1}, {2}' -f $directory.FullName, $access_right.IdentityReference, $access_right.FileSystemRights))
         }
    }
}
$file_stream_output.Close() 

My goal is have results appended to the file.

Upvotes: 2

Views: 6604

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174990

As Jeff Zeitlin alludes to, the StreamWriter class has a constructor overload that takes an append value as its second parameter - set it to $true:

$file_stream_output = [System.IO.StreamWriter]::new("$path_to_file\results.csv", $true)

Upvotes: 7

Related Questions