My script exports some information from Sharepoint sites to a .CSV file.
# Enter Web Application URL
$WebAppURL="http://server"
# Enter Path to CSV-file
$CSVFilePath="Path"
$SiteCollections = Get-SPWebApplication $WebAppURL | Get-SPSite -Limit All
$Tree = foreach ($Site in $SiteCollections) {
foreach ($Web in $Site.AllWebs) {
$Groups = New-Object System.Collections.ArrayList
foreach ($Group in $web.Groups) {
[void]$Groups.Add($Group.Name)
}
$Groups = $Groups -join ','
[PSCustomObject]@{
Url = $web.URL
Title = $web.Title
CountOfLists= $web.Lists.Count
PermissionsInherited = $web.Permissions.Inherited
Groups = $Groups
}
}
}
$Tree | Export-CSV $CSVFilePath -NoTypeInformation -Encoding UTF8
If I use [void] before $Groups.Add($Group.Name) it works correctly, but without [void], the script returns an empty .CSV file.
Why does this happen?
PowerShell implicitly outputs values that are neither captured in a variable, suppressed (as with [void] (...), $null = ..., or Out-Null), redirected (with > / >>), nor sent through the pipeline (|) to another command.
$Groups.Add($Group.Name) outputs an [int] (System.Int32) value (the index of the newly appended element), so without the [void] cast this integer becomes part of first the inner and then the outer foreach loop's output[1], and thereby effectively the very first output object captured in $Tree.
When piping objects to Export-Csv, it is the first object alone that determines what columns to export, based on that object's (public) properties.
An [int] instance is just a value itself, it doesn't have any properties, so the resulting CSV file is effectively empty.
[1] The generic equivalent of System.Collections.ArrayList is System.Collections.Generic.List`1, whose .Add() method does not return a value, which is why its use is preferable in PowerShell (and generally). The equivalent construct call would be:
$Groups = New-Object System.Collections.Generic.List[object] or, in PSv5+,
$Groups = [System.Collections.Generic.List[object]]::new()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With