如何为该脚本格式化csv?

时间:2018-11-15 12:05:35

标签: powershell csv active-directory

我有一个脚本,该脚本扫描AD中的所有服务器并返回本地组成员。您能帮我更新脚本,以便将输出格式按服务器的标题(服务器名称,本地组名称,成员,类型)分组吗?

# Define local groups to audit
$groups = "Administrators", "Remote Desktop Users";

# Add Active Directory powershell plug-in
import-module activedirectory;

# Get all servers from AD and ignore predefined list 
$adservers = get-adcomputer -filter {operatingsystem -like "*server*"} | where {$_.enabled -eq $true} | sort name;

# Loop through each server found in AD
foreach ($adserver in $adservers) {


# Set server name from AD object
$servername = $adserver.name;

# Check if server is pingable
if((test-connection -computername $servername -count 1 -quiet)) {

    # Loop through each group to audit
    foreach ($group in $groups) {

        # Define the localgroup in the correct format
        $localgroup = [ADSI]"WinNT://$servername/$group";

        # Get members of the local group
        $members = @($localgroup.Invoke("Members"));

        # Loop through each member found
        foreach ($member in $members) {

            # Define name and type of the member
            $memberName = $member.GetType().Invokemember("Name","GetProperty",$null,$member,$null);
            $memberType = $member.GetType().Invokemember("Class","GetProperty",$null,$member,$null);

            # Build CSV string
            $outstring = $servername + "," + $group + "," +$membername + "," +$membertype;
            # Output string to screen
            write-host $outstring;

            # Append CSV string to file
            $outstring >> c:\temp\localgroupaudit.csv;
        }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

内容:

        # Build CSV string
        $outstring = $servername + "," + $group + "," +$membername + "," +$membertype;
        # Output string to screen
        write-host $outstring;

除非您要在屏幕上书写,否则请更改为:

[Array]$results = $results + [PSCustomObject]@{Servername=$servername; LocalGroupName=$group,Members=$membername,Type=$membertype}

在所有循环结束之后:

$results | Export-CSV C:\path\youwanto\exportfileto\filenamehere.csv -notypeinformation