New-Adgroup from CSV - Help an powershell n00b

Welcome Forums General PowerShell Q&A New-Adgroup from CSV - Help an powershell n00b

Viewing 2 reply threads
  • Author
    Posts
    • #194882
      Participant
      Topics: 1
      Replies: 0
      Points: -28
      Rank: Member

      Hej Gents.

      I recently acquired The Learn windows Powershell in a month of lunches.
      I need a new approach to mastering powershell, im getting better, but I am still at the first few chapters.

      Im in the need to create a 1000 AD security groups.
      But hours in, im still fighting to get the variables into the script.

      I have tried multiple approaches, but im failing for some reason.

      Formatted the csv file in multiple ways, currently trying.
      CSV:
      GroupName,GroupCategory,GroupScope,OU
      Groupamexxx,Security,Global,"OU=Groups,OU=Accounts,OU=xxx,DC=live,DC=zxy,DC=local"
      Im running this from Powershell ISE as administrator, but my $item.name is not working..

      $csv = Import-Csv -Path 'C:\Temp\Create_AD_groups\List3.csv'
      forEach ($item in $csv)
      
      {
      $Create_group = New-ADGroup -Name '$item.Groupname' -GroupCategory '$item.Groupcategory' -GroupScope '$Item.Groupscope' -Path '$Item.OU' -PassThru –Verbose
      }
      
      

      ERROR

      New-ADGroup : Cannot bind parameter 'GroupCategory'. Cannot convert value "$item.Groupcategory" to type "Microsoft.ActiveDirectory.Management.ADGroupCategory". Error: "Unable to match the identifier name $item.Groupcategory
      to a valid enumerator name. Specify one of the following enumerator names and try again:
      Distribution, Security"
      At line:5 char:68
      
    • #194903
      Participant
      Topics: 2
      Replies: 1687
      Points: 3,340
      Helping Hand
      Rank: Community Hero

      Please remove your quotes around your variables. That "converts" them to strings. 😉

      ... and what for do you assign a variable $Create_group when you never use it?

      You might coninue reading your book before proceeding. 😉

    • #194915
      Participant
      Topics: 10
      Replies: 1375
      Points: 1,481
      Helping Hand
      Rank: Community Hero

      Assign the variable to the loop rather than inside the loop. When commands get to be lengthy, also check out splatting:

      $csv = Import-Csv -Path 'C:\Temp\Create_AD_groups\List3.csv'
      
      #Anything outputted in the loop gets populated into $result variable
      $results = forEach ($item in $csv) {
          
          #Splatting
          $params = @{
              Name = $item.Groupname
              GroupCategory = $item.Groupcategory
              GroupScope = $Item.Groupscope
              Path = $Item.OU
              PassThru = $true
              Verbose = $true
          }
      
          New-ADGroup @params
      }
      
      $results
      
Viewing 2 reply threads
  • You must be logged in to reply to this topic.