Explain Powershell [void] behavior
Asked Answered
B

1

3

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?

Blakeslee answered 26/1, 2021 at 17:53 Comment(0)
A
6
  • 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.

    • See the bottom section of this answer for the design rationale behind this behavior.
  • $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()

Allmon answered 26/1, 2021 at 18:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.