Reputation: 21
I'm very new to PowerShell and was hoping someone could help me understand where I'm going wrong with a script I am wanting to create.
The script's purpose is to take a First and Last name as mandatory values and store then in $FirstNames and $LastNames. It is then to add them together and create $Samaccountname. This is then fed to a ForEach-Object loop to create a user account per object provided to $Samaccountname with an array providing extra attributes to -otherattributes.
Please see below my code:
Param
(
[Parameter(Mandatory=$True)]
[string[]]$FirstNames
,
[Parameter(Mandatory=$True)]
[string[]]$LastNames
)
#This will create new users with pre-set attributes based on an array.
Import-Module ActiveDirectory
$Samaccountnames = $FirstNames+$LastNames
$OtherAttributes = @{
City="Sunderland"
Department="IT"
Title='1st Line Analyst'
#This is the 'Office' attribute
office='Sunderland IT Building'
Path='OU=Sunderland,OU=North East,OU=Lab Users,DC=*******,DC=***'
}
foreach($Samaccountname in $Samaccountnames)
{
New-ADUser -name $Samaccountname @OtherAttributes
}
This created users with Samaccount names coming from $firstnames. It also did not apply a surname attribute.
Many thanks
Upvotes: 2
Views: 477
Reputation: 114
Since both name and surname are mandatory - the quantity of them will be the same. I would recommend you to create a new samaccountname for each name in $FirstNames and add it to an array of samaccountnames.
Param
(
[Parameter(Mandatory=$True)]
[string[]]$FirstNames
,
[Parameter(Mandatory=$True)]
[string[]]$LastNames
)
#This will create new users with pre-set attributes based on an array.
Import-Module ActiveDirectory
$Samaccountnames = @() #define $samaccountnames as an array
#for each name in $firstnames we create new samaccountname and add it to samaccountnames array
foreach ($item in (0..$Firstnames.count)) #
{
$samaccountnames += $firstnames[$item]+$lastnames[$item]
}
$attributes = @{
'City' = 'Sunderland'
'Department' = 'IT'
'Title' = '1st Line Analyst'
'Office' = 'Sunderland IT Building'
'Path' = 'OU=Sunderland,OU=North East,OU=Lab Users,DC=*,DC=*'}
foreach($Samaccountname in $Samaccountnames)
{
New-ADUser -name $Samaccountname @OtherAttributes
}
Upvotes: 0
Reputation: 19694
The problem is you're taking two arrays and trying to add them to each other. It would make more sense to just take what you want: SamAccountName
.
param(
[Parameter(Position = 0, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string[]]
$SamAccountName
)
Import-Module -Name ActiveDirectory
$attributes = @{
'City' = 'Sunderland'
'Department' = 'IT'
'Title' = '1st Line Analyst'
'Office' = 'Sunderland IT Building'
'Path' = 'OU=Sunderland,OU=North East,OU=Lab Users,DC=*,DC=*'
}
foreach ($Name in $SamAccountName) {
New-ADUser -Name $Name @attributes
}
Upvotes: 0