2

Here is my code, I am pulling user names, email addresses and a random password and would like to store these nicely in a CSV. How can I export to csv a custom property like my custom generated passwords while also exporting name and mail?

$pool = Get-ADUser -Filter * -SearchScope Subtree -SearchBase "OU=Test,OU=Users,OU=funny,DC=Corp,DC=funny,DC=com"
foreach ($user in $pool )
{ 

    #MY NAME AND MAIL FUNCTION
    $a = Get-ADUser $user -Properties name, mail

    #MY PASSWORD FUNCTION
    $password = {blah,blah,blah}
    $password
}

$pool | Select-Object name,mail,$password | Export-Csv -path test.csv

How do I print the random password in the CSV along with name and mail?

Notes: I am doing this on AD. I would like the CSV to be neat as i will be parsing through it again using powershell. I am using Powershell 3.

3

Add the password as a NoteProperty in your foreach loop, using Add-Member and then select on that.

So, something like this:

$pool = Get-ADUser -Filter * -SearchScope Subtree -SearchBase "OU=Test,OU=Users,OU=funny,DC=Corp,DC=funny,DC=com"
foreach ($user in $pool )
{ 

    #MY NAME AND MAIL FUNCTION
    $a = Get-ADUser $user -Properties name, mail

    #MY PASSWORD FUNCTION
    $password = {blah,blah,blah}
    $user | Add-Member -Force Password $password
    $password
}

$pool | Select-Object name,mail,Password | Export-Csv -path test.csv
| improve this answer | |
  • The example above will work as above with Powershell 3 or above (I believe) - earlier version of PowerShell will not support the abbreviated version of Add-Member. You'll have to do something like Add-Member -Type NoteProperty -Name Password -Value $password – Per von Zweigbergk Oct 2 '15 at 18:24
  • Thanks! That worked. But I had to add -Force to it because it gave me the following error. Add-Member : Cannot add a member with the name "Password" because a member with that name already exists. If you want to overwrite the member anyway, use the Force parameter to overwrite it. Might you know why this is? But i have solved it. – caesartcs Oct 2 '15 at 19:46
  • I added the -Force parameter to Add-Member in my answer, but that behaviour is interesting. I made a seperate question on Stack Overflow about that: stackoverflow.com/questions/32919541/… – Per von Zweigbergk Oct 3 '15 at 6:15
  • The question got an answer, the short answer is that the Active Directory objects are a bit "special", in that they do not behave like most other Powershell Objects. Hope that answers your query. :-) – Per von Zweigbergk Oct 3 '15 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.