I'm creating a PowerShell script to create a unique ID based off of some AD info. Here is what I have so far.
Import-Module -Name ActiveDirectory
$username = Read-Host -Prompt ("Please Enter the Username")
$startdate = Read-Host -Prompt ("Please Enter the user's Start Date (Format: Feb 2022 = 022022)")
Basically I want to create another variable called $UserID that will concatenate the first letter of the given name for the Active Directory user first letter of the surname for the Active Directory user but lowercase $startdate. So for example, if I input jdoe for username for John Doe in AD and the startdate is 022022, UserID should be Jd022022.
Is there a way to concatenate this in PowerShell?
CodePudding user response:
You can use .tolower()
and .Substring()
methods to do this.
Import-Module -Name ActiveDirectory
$username = Read-Host -Prompt ('Please Enter the Username')
$startdate = Read-Host -Prompt ("Please Enter the user's Start Date (Format: Feb 2022 = 022022)")
$user = Get-ADUser -Identity $username
$finalvariable = $user.GivenName.Substring(0,1) $user.Surname.Substring(0,1).tolower() $startdate
$finalvariable
You could use this as a reusuable function with arguments like below.
Nicknamer
function Generate-NewID {
<#
.SYNOPSIS
Nicknamer
.DESCRIPTION
Provides nickname given username and date.
.PARAMETER user
The samAccountName of the User.
The specified date.
.PARAMETER date
The specified date.
.EXAMPLE
Generate-NewID -user mjones -date 010122
> Mj010122
.NOTES
Place additional notes here.
.OUTPUTS
Nickname in the correct format.
#>
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
HelpMessage = 'Please Enter the Username')]
[Object]$user,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
HelpMessage = "Please Enter the user's Start Date (Format: Feb 2022 = 022022)")]
[Object]$date
)
Import-Module -Name ActiveDirectory
try {
## test if AD user exists
$null = Get-ADUser -Identity $user
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
##can't find that user
Write-Warning -Message 'There was an error finding that user.'
}
catch {
## a different issue
## if you are seeing this you need to remove the
## "$null =" in the above try{} block
Write-Warning -Message 'Other issues...'
}
finally {
$inputuser = Get-ADUser -Identity $user
$startdate = $date
$output = $inputuser.GivenName.Substring(0, 1) $inputuser.Surname.Substring(0, 1).tolower() $startdate
$inputuser = $null
$user = $null
}
$output
}