Getting a substring from a Select-Object / Get-Aduser command

In the code below, the userprinciplename will output strings like “LLL_John.Smith@email.com” and XXXX_Jane.Doe@email.com" but i am hoping to extract a substring from that, that being the codes before the “_” character, so LLL and XXXX.

There may be some which do not have an underscore character however and so these would need to be ignored / have the original string it would have returned.

##Check bottom of script for setting specific OU
Function Get-LastLogon {
  param(
    [string]$OUName
  )

  # Get all matching OUs on any level
  $OUs = Get-ADOrganizationalUnit -Filter "Name -like '$OUName'"
  $DCs = Get-ADDomainController -Filter *

  # Get all users from each OU from each DC
  $ADUsers = Foreach ($OU in $OUs) {
    Foreach ($DC in $DCs.HostName) {
      Get-ADUser -SearchBase $OU.DistinguishedName -Filter * -Properties LastLogon -server $dc | 
        Select-Object Name,userPrincipalName, @{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}
    }
  }

  # return most recent LastLogon date for each user
  $ADUsers | 
    Group Name,userPrincipalName | 
    Select Name,userprinciplename, @{n='LastLogon';e={$_.Group.LastLogon | sort -desc | select -First 1}}
}  ## End function

$OUcustom = Read-Host -prompt 'Enter OU here or "Clients" for all'
##Enter the OU here
Get-LastLogon -OUName $OUcustom |
##export csv
Export-Csv -path "C:\temp\UserExport_$((Get-Date).ToString("ddMM_HHmm")).csv" -NoTypeInformation
".csv extracted to C:\temp"
pause

Hi, welcome to the forum :wave:

You can just use -split for this. If it doesn’t split, you’ll get the original string.

PS E:\Temp> ('LLL_John.Smith@email.com' -split '_')[0]
LLL
PS E:\Temp> ('LLLJohn.Smith@email.com' -split '_')[0]
LLLJohn.Smith@email.com
1 Like

This script is going to return hundreds of different variations of email, this would mean i’d need to incorporate every single one into the script no? - Apologies if i am misunderstanding.
The email examples were just that, i need a way of basically doing the below, but in a way that works:

Select-Object userPrincipalName.Substring(0,'_')

It outputs all of this to a CSV and whilst i could truncate everything in the userPrincipalName column before the underscore in excel for the result i want, it’d be nice for this to be done in the PS script without any input needed from the person running the script.

I understand that, it was just an example to show the output.

You can either assign userPrinicalName to a variable and split the variable, or do it as a calculated property in your Select-Object command.

That’s great, just got it working, thanks!

1 Like