China Syndrome
China Syndrome

Reputation: 993

need to export Powershell results to file

I have the following powershell script, I am unsure how to get it to export all the results to a file. Needs to have $Computer,$Group.Name, $Name preferably in CSV format

here is my query

$Computer = "ChynaSyndrome"

$Computer = [ADSI]"WinNT://$Computer"
$Groups = $Computer.psbase.Children | Where {$_.psbase.schemaClassName -eq "group"}

ForEach ($Group In $Groups)
{
    "Group: " + $Group.Name
    $Members = @($Group.psbase.Invoke("Members"))
    ForEach ($Member In $Members)
    {
        $Class = $Member.GetType().InvokeMember("Class", 'GetProperty', $Null, $Member, $Null)
        $Name = $Member.GetType().InvokeMember("Name", 'GetProperty', $Null, $Member, $Null)
        "-- Member: $Name ($Class)"
    }

}

Upvotes: 0

Views: 447

Answers (1)

scrthq
scrthq

Reputation: 1076

This will still give you console output, but it will build a PSObject with each member found in the group, then add those objects to the $results array. Once done, you have the option to show the resulting array in a GridView popup window and/or exporting them to CSV on your Desktop. Comment out either line to not take that action:

** Update: Per comments, I parameterized the script, allowing the calling process to provide an array of computer names (or a single one). Calling this script from a batch file would work like this:

powershell.exe -File "C:\script.ps1" -ComputerName "ChynaSyndrome","ChynaSyndrome2","ChynaSyndrome3"

Script.ps1:

Param
(
  [parameter(Mandatory=$true,Position=0)]
  [String[]]
  $ComputerName
)
Begin {
    $results = @()
}
Process {
    foreach ($Computer in $ComputerName) {
        $ComputerADSI = [ADSI]"WinNT://$Computer"
        $Groups = $ComputerADSI.psbase.Children | Where-Object {$_.psbase.schemaClassName -eq "group"}

        ForEach ($Group In $Groups) {
            "Group: " + $Group.Name
            $Members = @($Group.psbase.Invoke("Members"))
            ForEach ($Member In $Members) {
                $Class = $Member.GetType().InvokeMember("Class", 'GetProperty', $Null, $Member, $Null)
                $Name = $Member.GetType().InvokeMember("Name", 'GetProperty', $Null, $Member, $Null)
                "-- Member: $Name ($Class)"
                $object = New-Object PSObject -Property @{
                    Computer = $Computer
                    GroupName = $Group.Name.ToString()
                    MemberName = $Name.ToString()
                    MemberClass = $Class
                }
                $results += $object
            }
        }
    }
}
End {
    # Export results to CSV on your Desktop
    $results | Export-Csv -NoTypeInformation "$env:USERPROFILE\Desktop\GroupResults.csv" -Force
}

Upvotes: 1

Related Questions