0

您好我创建了以下脚本来审核远程主机上的本地管理员组。它工作正常,但由于它只在通过所有主机后输出数据,我担心数组在它有机会导出到 csv 之前会用完缓冲区空间,所以我一直在尝试让它创建并在每个主机通过列表时附加输出,除非我无法让标题显示在第一行并在其下方附加附加行。下面是我尝试追加时得到的输出。斜体字应该是标题,其他信息应该列在下一行。我究竟做错了什么?

@{服务器=pc1; 成员=管理员;DistinguishedName =DC=域,DC=com

这就是它应该的样子。如果我不附加,它看起来是这样的,我让它在完成主机列表后创建 csv

Server           Members            DistinguishedName
host1   Administrator;Admin2    DC=DOMAIN,DC=COM





$servers= get-content "C:\Scripts\AD Audits\Local Admin\workstations.txt"
$output = "c:\temp\local admin audit $CurrentDate.csv" 
$results = @()
$disconnected = "Did not respond"
foreach($server in $servers)
{
 $connected = Test-Connection $server -count 1 -quiet
    if ($connected) {
        "$server responded" | Out-File -append "c:\temp\LocalAdmin goodhosts $CurrentDate.txt"}

    else { 
        "$server did not respond" | Out-File -append "c:\temp\LocalAdmin badhosts $CurrentDate.txt"}

$group =[ADSI]"WinNT://$server/Administrators" 
 $members = $group.Members() | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) } 
 $results += New-Object PsObject -Property @{
  DistinguishedName = (get-adcomputer ($server) -properties * | select distinguishedname).distinguishedname
  Server = $server
  Members = $members -join ";"

    }

$results | Export-Csv $Output -NoTypeInformation

}`

if($connected -eq $True) { New-Object PSObject -Property @{ DistinguishedName = (Get-ADComputer $_).DistinguishedName Server = $_ Members = $members -join ";" }} else {write-host ""}

4

1 回答 1

0

我的建议是使用管道而不是 foreach 语句,因此每个对象在处理后立即写入文件。

$servers | ForEach-Object{

    $connected = Test-Connection $_ -Count 1 -Quiet -ErrorAction SilentlyContinue
    $state = if($connected) {"$_ responded"} else {"$_ did not respond"}
    $state | Out-File -Append "c:\temp\LocalAdmin goodhosts $CurrentDate.txt"

    $group =[ADSI]"WinNT://$_/Administrators,group" 
    $members = $group.Members() | ForEach-Object {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) } 

    if($connected)
    {
       New-Object PSObject -Property @{
           DistinguishedName = (Get-ADComputer $_).DistinguishedName
           Server = $_
           Members = $members -join ";"
       }
    }

} | Export-Csv $Output -NoTypeInformation
于 2013-06-20T20:04:21.063 回答