Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

sharepoint - Explain Powershell [void] behavior

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?

question from:https://stackoverflow.com/questions/65906608/explain-powershell-void-behavior

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • 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()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...