David
David

Reputation: 81

Outputting Objects to excel with powershell

Working on a simple script to output administrator accounts on all computers on our domain. Script works well in Powershell but when attempting to export to an excel all I get is the last object in the excel file. This would be the last object from the last computer (in this case 3 objects)

function get-localadministrators {
    param ([string]$computername=$env:computername)

    $computername = $computername.toupper()
    $ADMINS = get-wmiobject -computername $computername -query "select * from win32_groupuser where GroupComponent=""Win32_Group.Domain='$computername',Name='Administrators'""" | % {$_.partcomponent}

    foreach ($ADMIN in $ADMINS) {
                $admin = $admin.replace("\\$computername\root\cimv2:Win32_UserAccount.Domain=","") # trims the results for a user
                $admin = $admin.replace("\\$computername\root\cimv2:Win32_Group.Domain=","") # trims the results for a group
                $admin = $admin.replace('",Name="',"\")
                $admin = $admin.REPLACE("""","")#strips the last "

                $objOutput = New-Object PSObject -Property @{
                    Machinename = $computername
                    Fullname = ($admin)
                    DomainName  =$admin.split("\")[0]
                    UserName = $admin.split("\")[1]
                }#end object

    $objreport+=@($objoutput)
    }#end for
    $objreport | export-csv ("C:\Accounts.csv") -notypeinformation
    return $objreport
}#end function
Get-content ("C:\100w.csv") | % {get-localadministrators -computername $_}

Upvotes: 0

Views: 823

Answers (1)

Jawad
Jawad

Reputation: 11364

You need to use -Append at the end of export-csv command to not overwrite the file each time. If the file does not exist, Export-csv will create the file and then each time append to it.

$objreport | export-csv ("C:\Accounts.csv") -notypeinformation -Append

See example 6 in ms documentation

Upvotes: 1

Related Questions