New-aduser foreach

This topic contains 4 replies, has 3 voices, and was last updated by Profile photo of Graham Beer Graham Beer 1 year, 3 months ago.

  • Author
    Posts
  • #30904
    Profile photo of Graham Beer
    Graham Beer
    Participant

    This is confusing me, it works if the CSV file has one "name" and "Displayname" but any more at it doesn't work.

    Can anyone help ?

    Import-Module ActiveDirectory
    
    Import-Csv C:\UserAccounts.csv -Header Name, Displayname |
    New-ADUser -path 'OU=Service Account,OU=Viamonstra,DC=Viamonstra,DC=com' |
    ForEach-Object {
         $_ | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText 'P@$$w0rd' -Force)
         $_ | Enable-ADAccount 
         $_ | Set-ADAccountControl -PasswordNeverExpires $True -CannotChangePassword $True
        }      
    
  • #30906
    Profile photo of Bob McCoy
    Bob McCoy
    Participant

    That's because the foreach needs to follow the Import-CSV to iterate over all the entries.

  • #30916
    Profile photo of Graham Beer
    Graham Beer
    Participant

    Bob,

    Thanks.

    So it works now, but if it exists i want it to just say exist and not loads of "red" error writing. Again, the Try / Catch is not working as i would like :

     
    Import-Module ActiveDirectory
    
    Import-Csv C:\UserAccounts.csv -Header Name, Displayname |
    New-ADUser -path "OU=Service Account,OU=Viamonstra,DC=Viamonstra,DC=com" |
    ForEach-Object {
    try {
         $_ | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText 'P@$$w0rd' -Force)
         $_ | Enable-ADAccount 
         $_ | Set-ADAccountControl -PasswordNeverExpires $True -CannotChangePassword $True
        } 
     catch { 
           write-warning "Error occured: $_" }
        }  
    
  • #30919
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    For try{} catch{} to work, the cmdlet must throw a terminating error. Cmdlets will usually not do that so that one object erroring does not kill processing for the rest of the objects in the collection. You can force a terminating error by specifying the "ErrorAction" parameter.

    For example:

    $_ | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText 'P@$$w0rd' -Force) -ErrorAction Stop
    

    Since you have four different cmdlets being executed in your code. you would need to specify the ErrorAction up to 4 times, depending on which cmdlets you want to trap.

    You should check out "The Big Book of PowerShell Error Handling" free ebook under the "Resources" section in this site.

  • #30949
    Profile photo of Graham Beer
    Graham Beer
    Participant

    I've written the below script with seems to work quite nicely. Usage correct ?

    
    function Add-UsersToAD
    {
        [CmdletBinding()]
        Param
        (
            #description
            [Parameter(Mandatory=$false,
                       ValueFromPipelineByPropertyName=$true,
                       Position=0)]
            [system.string]
            $CSVInput = 'C:\UserAccounts.csv'  
        )
    
        Begin
        {
        #import ActiveDirectory Module
        Import-Module ActiveDirectory
        }
        Process
        {
      #Import CSV with Name and displayname
    Import-Csv $CSVInput -Header Name, Displayname |
    ForEach-Object {
    Try {
    #Create the AD account
    New-ADUser -Name $_.name -DisplayName $_.Displayname -path "OU=Service Account,OU=Viamonstra,DC=Viamonstra,DC=com" -PassThru |
        ForEach-Object {
    #Set attributes of accounts
         $_ | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText 'P@$$w0rd' -Force) -ErrorAction Stop
         $_ | Enable-ADAccount -ErrorAction Stop
         $_ | Set-ADAccountControl -PasswordNeverExpires $True -CannotChangePassword $True -ErrorAction Stop }
               }
    catch {
        Write-Warning $_.exception.message -WarningVariable +err 
          }
        }
      }
        End
        {
    #Completion message
        If ([int]$err.count -gt 1 ) 
        {
        #No input required
        }
        else 
        {
        Write-Host -ForegroundColor Cyan "Accounts created"
        }
      }
    }

You must be logged in to reply to this topic.