I have a script that creates new users that can be used for different operations.
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$GivenName, #=givenName
[Parameter(Mandatory=$True,Position=2)]
[string]$Name, # =sn
[Parameter(Mandatory=$True,Position=9)]
[string]$ADuser,
[Parameter(Mandatory=$True,Position=4)]
[string]$Description, #=title
[Parameter(Mandatory=$True,Position=4)]
[string]$AdministrationUser,
[Parameter(Mandatory=$True,Position=4)]
[string]$SamAccManager
)
after these parameters I have a new-user -name and so on, But I want to user the last Parameter SamAccManager to be added to the adminDisplayName, so I can search who is in charge of that AD user as there will be users that have no logon rights, will be used only for test purposes.
new-aduser -name $DisplayName -DisplayName $DisplayName -Description $Description -GivenName $GivenName -Surname $Name -SamAccountName $usr -UserPrincipalName $UserPrincipalName -Path $OU_AD
How Can I integrate to add that info into that specific adminDisplayName field? for example, I want to add in the last section code -admindisplayname $samaccmanager , but I can not do that as it is an invalid parameter. Any ideas?
First thing I noticed is that you add duplicate values for Position to the parameters. Also, there is a parameter you do not seem to use: $AdministrationUser and personally, I would change the param names for some of them so it becomes much clearer what they stand for.
The code below uses Splatting to feed the parameters to the New-ADUser cmdlet. This is a nice readable and maintainable way of calling on cmdlets with lots of properties.
Param(
[Parameter(Mandatory=$True,Position=0)]
[string]$GivenName, # =givenName
[Parameter(Mandatory=$True,Position=1)]
[string]$SurName, # =SurName
[Parameter(Mandatory=$True,Position=2)]
[string]$AccountName, # =SamAccountName
[Parameter(Mandatory=$True,Position=3)]
[string]$Description, # =title
[Parameter(Mandatory=$True,Position=4)]
[string]$OU, #= distinguishedName of the OU
[Parameter(Mandatory=$True,Position=5)]
[string]$SamAccManager #= AdminDisplayName
)
# create a hashtable for the New-ADUser parameters
$userParams = #{
Name = "$GivenName $SurName"
DisplayName = "$GivenName $SurName"
Description = $Description
GivenName = $GivenName
Surname = $SurName
SamAccountName = $AccountName
UserPrincipalName = "$AccountName#yourdomain.com"
Path = $OU
# add the AdminDisplayName attribute as hashtable
OtherAttributes = #{AdminDisplayName = $SamAccManager}
}
# create the user by splatting the parameters
New-ADUser #userParams
Of course, you can also set the AdminDisplayName property after creating the user by using
Set-ADuser -Identity $AccountName -Add #{AdminDisplayName = $SamAccManager}
Related
I'm working on a script to implement MFA deployment through Powershell. I'm connecting to an office365 and running the Get-MsolUser command to grab a list of users from AD (I believe). I'm putting it into an array which I'm then running through a ForEach loop. I'm not sure if this is even functional yet, but I'm trying to figure out how to exclude certain users from this loop as I don't want to activate MFA for domain admins.
Connect-MsolService
$array = #(Get-MsolUser | Select UserPrincipalName)
ForEach ($users in $array)
{
$st = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
$st.RelyingParty = "*"
$st.State = "Enabled"
$sta = #($st)
Set-MsolUser -UserPrincipalName $users -StrongAuthenticationRequirements $sta
}
So I guess the 3 questions I have are:
How can I exclude users with names matching a certain string such as "Admin, Administrator" in the Array?
Is there anyway to take user input and apply it to the username/password fields for Connect-MsolService?
3)Is this code even functional as it stands or am I totally off the mark?
As commented, there are some enhancements to be made in your code.
Try:
Starting with your question 2)
Connect-MsolService has a -Credential parameter and the easiest way to obtain that is by using the Get-Credential cmdlet:
# ask for credentials to make the connection
$cred = Get-Credential -Message 'Please enter your credentials to connect to Azure Active Directory'
Connect-MsolService -Credential $cred
Next, you want to define a list of users to exclude from being affected.
$excludeTheseUsers = 'admin', 'user1', 'user2' # etc.
# for using the regex `-notmatch` operator later, you need to combine the entries with the regex OR sign ('|'),
# but you need to make sure to escape special characters some names may contain
$excludes = ($excludeTheseUsers | ForEach-Object { [regex]::Escape($_) }) -join '|'
# create the StrongAuthenticationRequirement object just once, to use on all users
$st = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
$st.RelyingParty = "*"
$st.State = "Enabled"
$sta = #($st)
# get an array of UserPrincipalNames
$array = (Get-MsolUser | Where-Object { $_.DisplayName -notmatch $excludes }).UserPrincipalName
foreach ($user in $array) {
Set-MsolUser -UserPrincipalName $user -StrongAuthenticationRequirements $sta
}
I am working on a script creating a new user via PowerShell with user (creator) input. The input I am looking for is for the first name and last name along with some attributes. I would like the samaccountname and the UPN to be auto created from the input. Not sure if this can be done completely but would like to get some input on my current script. I highlighted firstinital as a placeholder to show what I am trying to accomplish.
new-aduser -givenname($givenname = read-host "Input Firstname") -surname($surname = read-host "Input Lastname") -samAccountName ("***firstinitial***"+"$._surname") -userprincipalname "$._surname+"#domain.com" -path "OUName" -whatif
Alrighty thanks for the help below. I was able to do a few more searches and can up with the following. All looks to work except the distingushed name comes up as a single name instead of a space between the first and last name.
#User info entered
$first = Read-Host "First name"
$last = Read-Host "Last name"
$title = Read-Host "Title"
$location = Read-Host "Location"
$department = Read-Host "Business Practice"
$password = read-host -assecurestring "Password"
#Create new user
$Attributes = #{
Enabled = $true
ChangePasswordAtLogon = $false
UserPrincipalName = $first.split(" ")[0]+$last+"#domain.com"
Name = $first+$last
GivenName = $first
Surname = $last
DisplayName = "$first "+" $last"
Office = $location
Department = $department
Title = $title
samAccountName = $first.split(" ")[0] + $last
AccountPassword = $password
}
New-ADUser #Attributes -whatif
You can add this to get the $_.givenName as the first initial:
$gn = (read-host "Input Firstname")
$sn = (read-host "Input Lastname")
new-aduser -givenname $gn -surname $sn -samAccountName $gn.split(" ")[0]+$sn -userprincipalname $sn+"#kfriese.com" -path "OUName" -whatif
Here is a more advanced and robust way to do it: a custom function, that makes use of PowerShell integrated functionality.
It uses attributes that make the parameters mandatory, so user input will automatically be inquired when the function is called. Also a validation attribute to make sure the input is not empty and has no invalid characters (you might want to adjust the regex according to your needs).
The arguments for New-ADUser are passed using splatting. The rest is pretty straight-forward...
function makeuser {
param(
[Parameter(Mandatory, Position = 0)]
[ValidatePattern("[a-z]+")]
[string]$GivenName,
[Parameter(Mandatory, Position = 1)]
[ValidatePattern("[a-z]+")]
[string]$Surname
)
$params = #{
GivenName = $GivenName
Surname = $Surname
SamAccountName = $GivenName[0] + $Surname
UserPrincipalName = $Surname + "#kfriese.com"
Path = "OUName"
}
New-AdUser #params
}
To call the function, just type (parameter values will be inquired automatically)
makeuser
Or specify the values explicitly:
makeuser -GivenName Foo -Surname Bar
# or
makeuser foo bar
I'm pulling some user info from a .csv to create new users,
I've splatted the New User Params at the suggestion of someone here
but I'm getting this error
New-ADUser : Cannot convert 'System.String' to the type 'System.Management.Automation.SwitchParameter' required by parameter
'Confirm'.
At C:\Users\Administrator\Documents\GitHub\cyclone-internal-user-sync-1\Bamboo Attributes form a csv.ps1:68 char:28
+ New-ADUser #NewUserParms
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.NewADUser
I have no idea what this is haha, I've tried adding an erroraction stop to the new-aduser but that didn't have any effect
I have added trims and a section to remove spaces from usernames. to deal with multipart names such as Van der.... etc
#Bamboo Attributes from a .csv
#Enter a path to your import CSV file
$ADUsers = Import-csv 'path'
#Bamboo Attributes from a .csv
#Enter a path to your import CSV file
$ADUsers = Import-csv 'C:\Users\Administrator\Documents\GitHub\cyclone-internal-user-sync-1\documentation\SampleUserAttributes.csv'
#$apiRequest = Get-Content -Raw -Path C:\Users\alexh\Documents\GitHub\cyclone-internal-user-sync-1\cyclone-internal-user-sync-1\fake-api-query.json | ConvertFrom-Json
foreach ($User in $ADUsers) {
$firstName = $user.FirstName.Trim()
$surname = $user.Surname.Trim()
$vaildUsernameFormat = "[^a-zA-Z_.]" # identifies anything that's _not_ a-z or underscore or .
$username = "($firstName'.'$surname)" -replace $vaildUsernameFormat, '' #removes anything that isn't a-z
$DefaultPassword = 'Pa$$w0rd'
$NewUserParms = #{
'samAccountName' = $username;
'Name' = "$firstname $surname";
'DisplayName' = "$firstname $surname";
'UserPrincipalName' = "$username#domain.com";
'GivenName' = $firstname;
'Surname' = $surname;
'EmailAddress' = $User.Email;
'AccountPassword' = (ConvertTo-SecureString $DefaultPassword -AsPlainText -Force);
'Enabled' = $true;
'Path' = "OU=Users,DC=domain,DC=com";
'co' = $User.Country;
'company' = $User.CompanyName;
'countryCode' = $user.countryCode;
'department' = $user.OrgDepartmentName;
'Employeeid' = $user.EmployeeId;
'exstentionAttribute1' = $user.ExstentionNumber;
'ipPhone' = $user.ExstentionNumber;
'L' = $user.location;
'mail' = $user.Email;
'mobile' = $user.Mobile;
'Manager' = $user.Manager;
'physicalDeliveryOffice' = $user.Branch;
'postalCode' = $user.PostalCode;
'postOfficeBox' = $user.PostOfficeBox;
'proxyAddresses' = $user.ProxyEmail;
'scriptPath' = $user.scriptPath;
'st' = $user.StreetName;
'Title' = $user.Title
}
write-host "$username this is username value"
#Check if the user account already exists in AD
if (Get-ADUser -F {
sAMAccountName -eq $username
}) {
#If user does exist, output a warning message
Write-Warning "A user account $username has already exist in Active Directory."
}
else {
#If a user does not exist then create a new user account
New-ADUser #NewUserParms
}
}
I've removed some of the user attributes just to make this a bit smaller.
here is the.csv as well in case I've messed something up there
link to .csv file on git
A little known fact about PowerShell is that you don't need to use the whole parameter name. You can use the partial name and as long as it matches only one parameter name, that's what PowerShell assumes you mean.
The one it's choking on is this:
'co' = $User.Country;
If you look at the documentation for New-ADUser, it does not have a parameter called co. So PowerShell assumes it's a partial match to a known parameter, and the closest match is -Confirm. And the value in $User.Country doesn't make any sense for the -Confirm parameter, so it throws the error.
You will have to use the -OtherAttributes parameter to set all the other attributes that New-ADUser doesn't have a dedicated parameter for:
$NewUserParms = #{
...
'OtherAttributes = # {
'co' = $User.Country;
'exstentionAttribute1' = $user.ExstentionNumber;
...
}
...
}
As commented in this and previous questions, you are using New-ADUser $NewUserParms, where it should be New-ADUser #NewUserParms.
Also, to catch errors (you did add -ErrorAction Stop), you need to put that inside a try{..} catch{..} block.
I would also change the syntax you use for the -Filter parameter. Instead of using a scriptblock syntax {something -eq someotherthing}, you should create a string like "something -eq 'someotherthing'"
Try:
# define some 'constants'
$csvFile = 'X:\Folder\NewUsers.csv' # Enter a path to your import CSV file
$invalidCharacters = '[^a-z_.]' # identifies anything that's _not_ a-z or underscore or .
$DefaultPassword = 'Pa$$w0rd'
$securePassword = ConvertTo-SecureString -String $DefaultPassword -AsPlainText -Force
# read the input csv and loop through
Import-Csv -Path $csvFile | ForEach-Object {
$firstName = $_.FirstName.Trim()
$surname = $_.Surname.Trim()
$username = ('{0}.{1}' -f $firstName, $surname) -replace $invalidCharacters
# test if a user with that name already exists
$user = Get-ADUser -Filter "SamAccountName -eq '$username'" -ErrorAction SilentlyContinue
if ($user) {
Write-Warning "A user account $username already exist in Active Directory."
}
else {
Write-Host "Creating user $username"
$NewUserParms = #{
'SamAccountName' = $username
'Name' = "$firstname $surname"
'DisplayName' = "$firstname $surname"
'UserPrincipalName' = "$username#domain.com"
'GivenName' = $firstname
'Surname' = $surname
'EmailAddress' = $_.Email
'AccountPassword' = $securePassword
'Enabled' = $true
'Path' = "OU=Users,DC=domain,DC=com"
# add other properties to set from the CSV here.
# make sure you get the parameter data types correct and always check here:
# https://learn.microsoft.com/en-us/powershell/module/addsadministration/new-aduser?view=win10-ps#parameters
# switch parameters for the cmdlet can also be entered with a value $false or $true
}
try {
# '-ErrorAction Stop' ensures that also non-terminating errors get handled in the catch block
New-ADUser #NewUserParms -ErrorAction Stop
}
catch {
# something bad happened. Change 'Write-Warning' into 'throw' if you want your script to exit here
# inside a catch block, the '$_' automatic variable represents the actual exception object.
Write-Warning "Could not create account $username. $($_.Exception.Message)"
}
}
}
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
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
}
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
}
I am trying to add users in Active Directory. Those users need to have proxyAddresses. My problem is that those proxyAddresses are multiples and stored in an array.
I try :
$proxyAddresses = #("address1#test.com", "address2#test.com", "address3#test.com")
$userInstance = new-object Microsoft.ActiveDirectory.Management.ADUser
$userInstance.ProxyAddresses = $proxyAddresses
New-ADUser test -Instance $userInstance
And I get this error :
Invalid type 'System.Management.Automation.PSObject'. Parameter name: proxyAddresses
I would like to add this proxyAddresses array to the attribute proxyAddresses of my AD user but it don't seem to be possible.
Any idea how this could be done?
Anything wrong with using Set-ADUser?
$username = '...'
$proxyAddresses = 'address1#example.com', 'address2#example.com', 'address3#example.com'
New-ADUser -Name $username
Set-ADUser -Identity $username -Add #{
'proxyAddresses' = $proxyAddresses | % { "smtp:$_" }
}
I just had this same issue and I was pretty sure I was passing in a string array (that's how it was declared).
Problem was just before I sent my string array into AD I was passing it to "Sort-Object -Unique" - which unbeknownst to me was changing either the type or something that made the cmdlet unhappy.
Just FYI...Sort-Object can burn you in these circumstances.
So, in my testing of this. I made Get-ProxyAddresses at https://gist.github.com/PsychoData/dd475c27f7db5ce982cd6160c74ee1d0
function Get-ProxyAddresses
{
Param(
[Parameter(Mandatory=$true)]
[string[]]$username,
[string[]]$domains = 'domain.com'
)
#Strip off any leading # signs people may have provided. We'll add these later
$domains = $domains.Replace('#','')
$ProxyAddresses = New-Object System.Collections.ArrayList
foreach ($uname in $username) {
foreach ($domain in $domains ) {
if ($ProxyAddresses.Count -lt 1) {
$ProxyAddresses.Add( "SMTP:$uname#$domain" ) | Out-Null
} else {
$ProxyAddresses.Add( "smtp:$uname#$domain" ) | Out-Null
}
}
}
return $ProxyAddresses
}
It just returns as a collection. Pretty kludgy, but works for what I need. It also assumes the first username and first domain are the "primary"
I combined that with #ansgar's answer and tried just -OtherAttributes on New-Aduser
$proxyAddresses = Get-ProxyAddress -username 'john.smith', 'james.smith' -domains 'domain.com','domain.net'
New-ADUser -Name $username
-OtherAttributes #{
'proxyAddresses'= $proxyAddresses
}
Works perfectly and added the proxyAddresses for me right at creation, without having to have a separate set action afterwards.
If you are Going to do separate actions, I would recommend to use -Server, like below, so that you don't run into talking to two different DCs by accident (and you also know that the New-ADUser is finished and already there, you don't have to wait for replication)
#I like making it all in one command, above, but this should work fine too.
$ADServer = (Get-ADDomainController).name
New-ADUser -Server $ADServer -name $Username
Set-ADUSer -Server $ADServer -Identity $username -Add #{
'proxyAddresses' = $proxyAddresses | % { "smtp:$_" }
}