String concatenate not working

Hi Guys,

I’m trying to create Samaccountname based on the firstname and lastname in csv file.

$adusers.lastname.substring(0,4) with this command, I was able to get the first 4 letters from lastname and similarly was able to pull the first two letters from firstname.

This is our organization naming convention.

samaccount will start with U or V and followed by First 4 letters from last name and First 2 letters from first name. The csv will have a column that states employee type. If it is full-time employee, the sam ID should start with U. If any other category it should start with U.

e.g-> Wayne Rooney

UROONWA - Full Time

VROONWA - Part time or consultancy …etc

I’m very new to PowerShell any help will be greatly appreciated.

I ran the below cmd without $(), I got some error message. I used subexpression $() and after that, I got the below message

[string]::join('',$($adusers.lastname.substring(0,4)),$($adusers.firstname.substring(0,2)))

 

PS C:\Windows\system32> $($adusers.lastname.substring(0,4))
thir
Rona
mess

PS C:\Windows\system32> [string]::Concat($adusers.lastname.substring(0,4),$adusers.firstname.substring(0,2))
System.Object[]System.Object[]

 

Commands which I was trying:

$adusers.firstname
$adusers.lastname

$ADUsers = Import-csv "E:\thiru\Automation\sampleinput.csv"


$adusers.lastname.substring(0,4)
$adusers.firstname.substring(0,2)

[string]::join('',$($adusers.lastname.substring(0,4)),$($adusers.firstname.substring(0,2)))

[string]::Concat($($adusers.lastname.substring(0,4)),$($adusers.firstname.substring(0,2)))

I tried both join and concatenate,

This is the message I get:

 

PS C:\Windows\system32> [string]::join('',$($adusers.lastname.substring(0,4)),$($adusers.firstname.substring(0,2)))
System.Object[]System.Object[]

PS C:\Windows\system32> [string]::Concat($($adusers.lastname.substring(0,4)),$($adusers.firstname.substring(0,2)))
System.Object[]System.Object[]

PS C:\Windows\system32>

Please help

 

 

Thiru,

When you crosspost the same question at the same time to different forums you should at least post links to the other forums along with your question to avoid people willing to you help making their work twice or more.

https://www.reddit.com/r/PowerShell/comments/ixo27c/samaccountname_genration_string_concatenation_not/

Thanks

No need to over complicate it, you can concatenate with + easily.

$adusers = @'
lastname,firstname,Type
Rooney,Wayne,U
'@ | ConvertFrom-Csv

$adusers | foreach {
    $_.type + $_.lastname.substring(0,4) + $_.firstname.substring(0,2)
}

Output

URoonWa

You can also use string interpolation

$adusers | foreach {
    "{0}{1}{2}" -f $_.type,$_.lastname.substring(0,4),$_.firstname.substring(0,2)
}

Sure, Doug. Noted

Another approach is just using a calculated expression:

$adusers = @'
lastname,firstname,Type
Rooney,Wayne,U
'@ | ConvertFrom-Csv | 
     Select *,
            @{Name='SamAccountName';Expression={'{0}{1}' -f $_.firstname.substring(0,1),$_.lastname}}

Calculating a samAccountName is more of a process than just joining parts of a name. Typically, you have to create a function to get the next available samAccountName against the destination, Active Directory in this case. I’ve posted this previously in an example here:

https://powershell.org/forums/topic/duplicate-names-in-csv/

# Generate samaccount based on employee type
Import-Csv "E:\thiru\Automation\sampleinput.csv" | ForEach-Object {
    $myobj = $_
    $emp = 
    switch ($myobj.Employee)
    {
        'F' {"U{0}{1}" -f $myobj.First.Substring(0,4),$myobj.Last.Substring(0,2)}
        Default {"V{0}{1}" -f $myobj.First.Substring(0,4),$myobj.Last.Substring(0,2)}
    }
    [PSCustomObject]@{
        FirstName = $myobj.First
        LastName = $myobj.Last
        Employee = $myobj.Employee
        SamAccount = $emp
    }
}

## Sample Results
FirstName LastName  Employee SamAccount
--------- --------  -------- ----------
Maria     Maria     F        UMariMa   
John      Smith     F        UJohnSm   
David     Jones     P        VDaviJo   
Michael   Johnson   P        VMichJo   
Chris     Lee       C        VChriLe  

Hi Rob,

Thanks for your reply.

I read the script from the URL. I could see you are using PSBoundParameters to generate strings based on the variable and progressing using Begin, Process & End scripts.

I don’t understand in detail of Begin, process, and end, however I tried to reuse the script with my little understanding. This is my first PowerShell script. I’m building it part by part and looking for a way to conjunct everything. Maybe this is a bad approach. But this is where I stand right now.

  • creating variable to inputfile
  • assinging variable to all my csv data
  • If AD account exisit, modify the account. (Actually this is not working,)
If I run the below command along with the top of the script. It is writing the employee ID, when I add multiple attributes seperated by ;, it giving me an error
{Set-ADUser -Identity $username -Replace @{'employeeID'="$employeeID";'status' = "$Status";}}}
Error:
PS C:\Windows\system32> E:\thiru\Automation\working.ps1
Set-ADUser : The specified directory service attribute or value does not exist
Parameter name: OfficePhone
At E:\thiru\Automation\working.ps1:36 char:2
+ {Set-ADUser -Identity $username -Replace @{'employeeID'="$employeeID" ...
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (testthiru1:ADUser) [Set-ADUser], ArgumentException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.SetADUser

Set-ADUser : The specified directory service attribute or value does not exist
Parameter name: OfficePhone
At E:\thiru\Automation\working.ps1:36 char:2

  • {Set-ADUser -Identity $username -Replace @{‘employeeID’="$employeeID" …
  •  + CategoryInfo          : InvalidArgument: (VRONACR:ADUser) [Set-ADUser], ArgumentException
     + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.SetADUser</pre>
    

 

cont-

  • else generate the SAMID
  • From here, I used your scripts, but i need help on joining those.
  • And have to find a way to parse the information to New-ADuser cmdlet (Right now i'm using IF, I think that is not right)
Can you tell me what logic I should use once I created the SAMID,
  • Checking it with AD
  • IF exisit, increment with number
  • And to create the AD account
 
#Input file
$ADUsers = Import-csv "E:\thiru\Automation\sampleinput.csv"
$currentlyInAD = get-aduser -Filter * -Properties samaccountname | select samaccountname

foreach ($user in $ADUsers)
{
$Username = $User.u42
$Firstname = $User.firstname
$Lastname = $User.lastname
$employeeID = $User.number
$commonname = $user.‘Common Name’
$displayname = $user.‘Display Name’
#$Password = $User.password
$email = $User.‘business email’
#$telephone = $User.telephone
$jobtitle = $User.job
$department = $User.department
#$company = $User.company
$cWKType = $user.PayGroup
$status = $user.Status
$payClass = $user.payClass
$Officephone = $user.telephone

$location = $user.Location
$streetaddress = $User.streetaddress
$city = $User.city
$zipcode = $User.zipcode
$state = $User.state
$country = $User.country

if (Get-ADUser -F {SamAccountName -eq $Username})

{Set-ADUser -Identity $username -Replace @{‘employeeID’="$employeeID";‘status’ = “$Status”;‘payClass’ = “$PayClass”;‘EmailAddress’ = “$email” ;‘Department’ = “$department”;‘description’ = “$description”;‘givenname’ = “$firstname”;‘Surname’ = “$lastname”;‘streetAddress’ = “$streetaddress”;‘st’ = “$state”;‘c’ = “$Countrycode”;‘co’ = “$country”;‘City’ = “$city”;‘cWKType’ = “$paygroup”;‘OfficePhone’ = “$telephone”;}}}

ForEach ($Line in $ADUsers) {
If ($Line.“Pay Class” -eq “FT”) {
$Prefix = “U”
} Else {
$Prefix = “V”
}
$FirstName = $Line.FirstName.substring(0,2).ToUpper()
$LastName = $Line.LastName.substring(0,4).ToUpper()
$FullSAM = “$Prefix$LastName$FirstName”
$FullSAM
}

#Create a search filter for Get-ADUser with a * wildcard
$searchFilter = “{0}*” -f $FullSAM

if ($currentlyInAD) {
Write-Verbose (“Found {0} matches in AD, comparing with possible names list for available SamAccountName” -f @($currentlyInAD).Count)
#Compare the list possibilities with the returned AD accounts for the SamAccountName format
$availableSAM = Compare-Object -ReferenceObject $currentlyInAD -DifferenceObject $possibleNames -Property SamAccountName -PassThru | Where{$_.SideIndicator -eq “=&gt;”} | Select -ExpandProperty SamAccountName -First 1
}
else {
$availableSAM = $possibleNames | Select -ExpandProperty SamAccountName -First 1
Write-Verbose ("{1}: No matches found in AD, returning first possible SamAccountName: {0}" -f $availableSAM, $MyInvocation.MyCommand)

if ($FullSAM -notcontains $currentlyInAD) {
New-ADUser -SamAccountName $u42
-UserPrincipalName “$Username@contosp.com-Name "$Firstname $Lastname"
-GivenName $Firstname -Surname $Lastname
-Enabled $True -DisplayName "$Lastname, $Firstname"
-Path $OU -City $city
-Company $company -State $state
-StreetAddress $streetaddress -OfficePhone $telephone
-EmailAddress $email -Title $jobtitle
-Department $department `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
}
}

 

PowerShell
{Set-ADUser -Identity $username -employeeID $employeeId}}}

i’m not exactly sure what you are doing with Status, as thats not a valid ad attribute.
Look through get-help on set-aduser. For any of the valid parameters listed, just use -parametername value approach in a single set-aduser.
make sure any value you are trying to set is an actual valid value in your domain.