The code below exports all the permissions set on the directories of a file server. As there are more than 1,000 permission on the file server my code is searching, I am using StreamWriter to speed up the export/writing of these permissions to a CSV. The code below runs accordingly and gets all permission however, the problem is that the results are not being written to a CSV as intended using StreamWriter. Any idea why this is?
$current_date = Get-Date -UFormat "%Y%m%d"
$directory_to_search = dir -Path "C:\Temp\test_folder\*\*\*" -Force |
where {$_.Attributes -match'Directory'}
$file_to_stream_results = New-Object System.IO.StreamWriter "C:\Temp\test_folder\server_permissions_$current_date.csv"
$count_of_directories = $directory_to_search.length.ToString()
$Report = @()
for ($i=0; $i -lt $directory_to_search.Length; $i++) {
$acl = Get-Acl -Path $directory_to_search[$i].FullName
for ($j=0; $j -lt $acl.Access.Count; $j++) {
if (!($acl.Access[$j].IdentityReference -eq "BUILTIN\Administrators") -and !($acl.Access[$j].IdentityReference -eq "NT AUTHORITY\SYSTEM")) {
$Report += New-Object PsObject -Property @{
'FolderName' = $directory_to_search[$i].FullName
'AD Group or User' = $acl.Access[$j].IdentityReference
'Permissions' = $acl.Access[$j].FileSystemRights
}
}
}
}
$Report | Export-Csv -Path $file_to_stream_results -Encoding "utf8" -NoTypeInformation
$file_to_stream_results.Close();
It's worth adding that I have worked the below functioning example for Stream Writer into my code above. I have tried to use $file.Writeline("$i" + ",") but it didn't work in my code.
$directory = "C:\Temp\test_folder"
$file = New-Object System.IO.StreamWriter "$directory\1000_values_to_file.csv"
Write-Output $file
$file_length = 1000
for ($i=0; $i -lt $file_length; $i++) {
Write-Output $i
$file.Writeline("$i" + "," )
}
$file.Close();