# String concatenate not working

**URL:** <https://forums.powershell.org/t/string-concatenate-not-working/14979>\
**Category:** PowerShell Help\
**Created:** [September 21, 2020, 1:46pm UTC](https://forums.powershell.org/t/string-concatenate-not-working/14979 "2020-09-21T13:46:28Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![thirudk](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/thirudk/32/54_2.png) [@thirudk](https://forums.powershell.org/u/thirudk)\
**Post date:** [September 21, 2020, 1:46pm UTC](https://forums.powershell.org/t/string-concatenate-not-working/14979/1 "2020-09-21T13:46:28Z")

</div>

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)))
```

&nbsp;

```
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[]
```

&nbsp;

**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:**

&nbsp;

```
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

&nbsp;

&nbsp;

---

<div class="post-metadata">

**Author:** ![krzydoug](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/krzydoug/32/1008_2.png) [@krzydoug](https://forums.powershell.org/u/krzydoug)\
**Post date:** [September 22, 2020, 5:56am UTC](https://forums.powershell.org/t/string-concatenate-not-working/14979/2 "2020-09-22T05:56:16Z")

</div>

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/](https://www.reddit.com/r/PowerShell/comments/ixo27c/samaccountname_genration_string_concatenation_not/)

Thanks

---

<div class="post-metadata">

**Author:** ![krzydoug](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/krzydoug/32/1008_2.png) [@krzydoug](https://forums.powershell.org/u/krzydoug)\
**Post date:** [September 22, 2020, 6:00am UTC](https://forums.powershell.org/t/string-concatenate-not-working/14979/3 "2020-09-22T06:00:25Z")

</div>

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)
}
```

---

<div class="post-metadata">

**Author:** ![thirudk](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/thirudk/32/54_2.png) [@thirudk](https://forums.powershell.org/u/thirudk)\
**Post date:** [September 22, 2020, 6:42am UTC](https://forums.powershell.org/t/string-concatenate-not-working/14979/4 "2020-09-22T06:42:17Z")

</div>

Sure, Doug. Noted

---

<div class="post-metadata">

**Author:** ![rob-simmers](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/rob-simmers/32/1010_2.png) [@rob-simmers](https://forums.powershell.org/u/rob-simmers)\
**Post date:** [September 22, 2020, 8:11am UTC](https://forums.powershell.org/t/string-concatenate-not-working/14979/5 "2020-09-22T08:11:32Z")

</div>

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/](https://powershell.org/forums/topic/duplicate-names-in-csv/)

---

<div class="post-metadata">

**Author:** ![random-commandline](https://avatars.discourse-cdn.com/v4/letter/r/e56c9b/32.png) [@random-commandline](https://forums.powershell.org/u/random-commandline)\
**Post date:** [September 22, 2020, 10:10am UTC](https://forums.powershell.org/t/string-concatenate-not-working/14979/6 "2020-09-22T10:10:24Z")

</div>

```
# 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
```

---

<div class="post-metadata">

**Author:** ![thirudk](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/thirudk/32/54_2.png) [@thirudk](https://forums.powershell.org/u/thirudk)\
**Post date:** [September 24, 2020, 8:50am UTC](https://forums.powershell.org/t/string-concatenate-not-working/14979/7 "2020-09-24T08:50:36Z")

</div>

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” …
- 

```auto
 + CategoryInfo : InvalidArgument: (VRONACR:ADUser) [Set-ADUser], ArgumentException
 + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.SetADUser</pre>

```

&nbsp;

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

&nbsp;
```
#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  
}  
}
```
&nbsp;

---

<div class="post-metadata">

**Author:** ![david-schmidtberger](https://avatars.discourse-cdn.com/v4/letter/d/ba9def/32.png) [@david-schmidtberger](https://forums.powershell.org/u/david-schmidtberger)\
**Post date:** [September 25, 2020, 3:43am UTC](https://forums.powershell.org/t/string-concatenate-not-working/14979/8 "2020-09-25T03:43:07Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:28pm UTC](https://forums.powershell.org/t/string-concatenate-not-working/14979/9 "2024-05-16T20:28:49Z")

</div>


