0

I am try to pull just the display name (first and last name) from cmd or powershell. (AzureAD - not on-prem AD) I have gotten a couple of different commands but all of them keep the name together. Examples:

$env:UserName = jatonjustice

[System.Security.Principal.WindowsIdentity]::GetCurrent().Name = azureAD\jatonjustice

I am trying to find a way where the result has the first and last name separated or maybe just the first and just the last name as an alternate idea.(Like: `Jaton Justice') I can't parse it myself as I don't know what the display name will be upfront. (AzureAD - not on-prem AD)

Any ideas for this? research: How do I get the current username in Windows PowerShell? How to get an Azure Active Directory username in Windows Powershell?

Thanks

  • Basically you're asking for a script that will predict what the first and last name of a user will be and how do you code the logic for that? Unless you can query the `$env:UserName` against AD or some identity service there is no way for what you're asking. – Santiago Squarzon Apr 17 '21 at 04:14
  • Your question and your follow-on comments show you are new to Powershell and looking for code to copy/paste and run without really thinking about what it is, how it works and why. If you are just doing get-* commands, OK, but, if you are doing destructive code, i.e., stuff that adds/changes things, then you should really get some training first before you cause real damage to your host or your environment. There are tons of resources/videos, all for free to learn PowerShell. There are even tools that can write baseline PowerShell code for you, that you can tweak. Your ask is very basic stuff. – postanote Apr 19 '21 at 00:46
  • Rules to protect yourself and your environment: 1. Never ever run anyone's code if you do not understand what it is doing, or be willing to fully accept the outcomes. No matter where or whom you get it from. especially if you have access to the source code) unless you are will to accept all consequences of running it. 2. Never ever run destructive code (add/create/update, move/remove/modify, etc.), without fully checking results before you do. Master the use of WhatIf/Confirm/Trace-Command/Invoke-ScriptAnalyzer. 3. All input is evil, no matter where it comes from until you validate it first. – postanote Apr 19 '21 at 00:48
  • To help you in your learning journey. https://www.tutorialspoint.com/powershell/index.htm and https://www.altaro.com/msp-dojo/teach-powershell-pskoans/ – postanote Apr 19 '21 at 00:50

3 Answers3

0

$env:UserName should return SamAccountName, rather than user's name. 'Get-ADUser -Property *' should show you all info about the user you are querying, you should be able to find a property called GivenName and Surname.

Digger
  • 55
  • 6
0
$search = [adsisearcher]"(SamAccountName=$env:USERNAME)"
$search.PropertiesToLoad.AddRange(@('givenname','sn'))
$adAccount = $search.FindOne()

$firstName = $adAccount.Properties.givenname
$lastName = $adAccount.Properties.sn

$fullname = "$firstName $lastName"
Daniel
  • 4,792
  • 2
  • 7
  • 20
0

All you are after is explained and detailed by examples in the PowerShell help files. More on that later.

As for ...

'but all of them keep the name together. Examples:'

...and they are supposed to, by design.

Using those, you are asking for the local logged-on username (SamAccountName, which is a short name defined in the user profile on the localhost and in ADDS/AAD - for the UPN, SamAccountName@DomainName.com) with those, not ADDS/AAD name specifics.

If you want First and last from the locally logged-on user, then you have to have that populated in the account, or you have to ask for it from ADDS/AAD. What is your use case?

If you are on PSv5x and higher there is this module:

# Results
<#
Get-Module -Name '*local*'

ModuleType Version    Name                                ExportedCommands                                                                                                   
---------- -------    ----                                ----------------                                                                                                   
Binary     1.0.0.0    Microsoft.PowerShell.LocalAccounts  {Add-LocalGroupMember, Disable-LocalUser, Enable-LocalUser, Get-LocalGroup...} 
#>

You get local user details this way.

Get-LocalUser | Select-Object -Property '*' -First 1

# Results
<#
AccountExpires         : 
Description            : Built-in account for administering the computer/domain
Enabled                : False
FullName               : 
PasswordChangeableDate : 
PasswordExpires        : 
UserMayChangePassword  : True
PasswordRequired       : True
PasswordLastSet        : 
LastLogon              : 
Name                   : Administrator
SID                    : S-1-5-21-2047949552-857980807-821054962-500
PrincipalSource        : Local
ObjectClass            : User
#>

Note that on his local account, Fullname is not populated. So, obviously, you can't use that, nor can you extrapolate from the name/SamAccoutnName property.

So, you can ask for the locally logged on username in a number of ways,...

# Get loggedon users
$env:UserName

[System.Environment]::UserName

[System.Security.Principal.WindowsIdentity]::GetCurrent().Name

(Invoke-CimMethod -InputObject $(
    Get-CimInstance Win32_Process -Filter "name = 'explorer.exe'"
) -MethodName GetOwner).User

Get-WmiObject Win32_Process -Filter "name='explorer.exe'" | 
Select Name, @{
    Name       = 'UserName'
    Expression = {"$($PSItem.GetOwner().Domain)\$($PSItem.GetOwner().User)"}
} | 
Sort-Object UserName, Name

(Get-Process -Name 'explorer' -IncludeUserName).UserName

(
    Get-WMIObject -ClassName Win32_ComputerSystem | 
    Select-Object -Property Username
).username

[adsisearcher]"(SamAccountName=$env:USERNAME)"

whoami

... then use that Name/SamAccountName to ask ADDS/AAD what the user FullName or whatever you wish is.

If you are on an earlier version, you need to install one of these modules from Microsofts' powershelgallery.com...

Find-Module -Name '*local*'
# Results
<#
Version    Name                                Repository           Description
-------    ----                                ----------           -----------
...                                    
1.6        localaccount                        PSGallery            A Simple module to allow the management of local users and groups on a computer
1.0.0.0    Microsoft.PowerShell.LocalAccounts  PSGallery            Provides cmdlets to work with local users and local groups
3.0        LocalUserManagement                 PSGallery            a module that performs various local user management functions
...                               
0.1.1      LocalAccountManagement              PSGallery            Manage local and remote user accounts and profiles
... 
#>

... and do the same thing or use WMI, ADSI, etc.

[adsisearcher]"(SamAccountName=$env:USERNAME)"
# Results
<#
CacheResults             : True
ClientTimeout            : -00:00:01
PropertyNamesOnly        : False
Filter                   : (SamAccountName=TestUser)
PageSize                 : 0
PropertiesToLoad         : {}
ReferralChasing          : External
SearchScope              : Subtree
ServerPageTimeLimit      : -00:00:01
ServerTimeLimit          : -00:00:01
SizeLimit                : 0
SearchRoot               : 
Sort                     : System.DirectoryServices.SortOption
Asynchronous             : False
Tombstone                : False
AttributeScopeQuery      : 
DerefAlias               : Never
SecurityMasks            : None
ExtendedDN               : None
DirectorySynchronization : 
VirtualListView          : 
Site                     : 
Container                : 
#>

Now, back to my 'read the help file comment.'

Get-ADUser | MS DOcs

https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-aduser?view=windowsserver2019-ps

# Example 3: Get all of the properties for a specified user
Get-ADUser -Identity $env:USERNAME -Properties '*'
# Results
<#
Surname           : David
Name              : Chew David
UserPrincipalName : 
GivenName         : David
Enabled           : False
SamAccountName    : ChewDavid
ObjectClass       : user
SID               : S-1-5-21-2889043008-4136710315-2444824263-3544
ObjectGUID        : e1418d64-096c-4cb0-b903-ebb66562d99d
DistinguishedName : CN=Chew David,OU=NorthAmerica,OU=Sales,OU=UserAccounts,DC=FABRIKAM,DC=COM
#>
postanote
  • 15,138
  • 2
  • 14
  • 25