Search code examples
powershellfieldextract

How to extract field content in powershell


  • History: I'm making a Powershell script in order to create user from a defined table containing list of users and put them in a defined OrganizationalUnit.

  • Problem: At the end of the script, I'd like to have a report in order to list whether or not there is one or many user account disabled amoung newly created account

In my script, I have to input a password for each user, but I may enter a password that won't meet the password policy defined in Active Directory; in this case, the account will be created but disabled.

To proceed, I tried :

dsquery user "ou=sp,dc=mydomain,dc=local" -disabled

and it print me this :

"CN=user1,OU=SP,DC=mydomain,DC=local"
"CN=user2,OU=SP,DC=mydomain,DC=local"
"CN=user3,OU=SP,DC=mydomain,DC=local"
  • My goal : I'd like to extract in a variable the values in "CN" field in order to compare them to the inital user table in my script.

    dsquery user "dc=mydomain,dc=local" -disabled | where-object {$_.CN -ne $null}
    

or

dsquery user "dc=mydomain,dc=local" -disabled | where-object {$_.Common-Name -ne $null}

But it didn't help (doesn't work). How can I proceed please?


Solution

  • It's not tested - just "from my mind"

    $csvData = Import-Csv 'UserList.csv' -Delimiter ';' -Encoding UTF8
    $userList = dsquery user "ou=sp,dc=mydomain,dc=local" -disabled
    $listOfDisabledAccounts = @()
    foreach ($user in $userList)
    {
        if ($csvData.Name -contains (($user -split ',')[0] -replace 'CN=',''))
        {
            $listOfDisabledAccounts += $csvData.Name
        }
    }
    
    $listOfDisabledAccounts