ADK
ADK

Reputation: 5

Exporting Objects in PowerShell

I have a script that imports a CSV, compares the list to AD and creates usernames and passwords. The scripts starts out like this:

$CSV = Import-CSV C:\Scripts\Add_AD_Users.csv

$CSV | ForEach-Object{
    if(user does exist){
        # skip it
    }   
    elseif(user doesn't exist){
        # create user and export password, email, and username to csv.
    }

In the elseif statement I would like to get the current ForEach-object "object" and export that to a CSV. Is that possible? The CSV contains 3 headers that I want to take $_.SamAccountName $_.EmailAddress $_.Password.

Is there a way to do this, so that I only have the newly created users? This can't be done with a -PassThru on Get-Aduser.

Upvotes: 0

Views: 2134

Answers (2)

Matt
Matt

Reputation: 46730

It's not super pretty but I would put this into a where clause and then, using Select-Object, output to CSV.

$CSV | 
    Where-Object{$result=try{Get-ADUser $_.samaccountname}catch{$false};!$result} |
    Select-Object SamAccountName, EmailAddress, Password | 
    Export-Csv -NoTypeInformation $path

Since you are not processing users that exist lets test using Where-Object so they do not continue down the pipe. Unfortunately you cannot use -ErorrAction which would have been nicer so we test the result from a try catch block instead.

From the looks of it your CSV file already has the columns SamAccountName, EmailAddress and Password so we just send those through the pipeline.

Upvotes: 1

Chris Kuperstein
Chris Kuperstein

Reputation: 678

The quickest way is to use a hashtable combined with a PSCustomObject creation accelerator.

$userToExport = [PSCustomObject]@{
    'sAMAccountName'=$_.SamAccountName
    'Email Address'=$_.EmailAddress
    'Password'=$_.Password
     # Each element in '' will be the column header, in order declared.
}

$userToExport | Export-CSV .\absolutefilepath.csv -Append -NoTypeInformation

-NoTypeInformation strips the object type away from the object so it doesn't print it out in your CSV. -Append will format the CSV if empty, and add the current added user to the csv, even if it was created before.

Upvotes: 0

Related Questions