2017-05-10 58 views
0

我有以下PowerShell腳本,我不確定如何讓它將所有結果導出到文件。需要有$計算機,$ Group.Name,$名稱最好在CSV格式需要將Powershell結果導出到文件

這裏是我的查詢

$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)" 
    } 

} 

回答

1

這仍將會給你控制檯輸出,但它會建立與發現的每個成員PSObject在該組中,然後將這些對象添加到$results陣列中。完成後,您可以選擇在GridView彈出窗口中顯示結果數組和/或在桌面上將它們導出爲CSV。註釋掉任一行不採取該行動:

**更新:每條評論,我參數化腳本,允許調用進程提供一個計算機名稱(或單個)的數組。調用批處理文件這個腳本會像這樣工作:

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 
} 
+0

的組名和成員名稱,我得到 「System.DirectoryServices.PropertyValueCollection」, 「System.DirectoryServices.DirectoryEntry」在出口 –

+0

更新我的答案來解決! 'GroupName'和'MemberName'具有現在稱爲ToString()'的方法來將對象轉換爲字符串。我還更新了'[ADSI]'這一行,以便在添加到對象時保留計算機名稱,因爲我注意到這也是borking。讓我知道這是如何工作的! –

+0

這很好,我現在怎麼把它放在ps1文件中?我想從命令行使用批處理文件調用 –

相關問題