pmac5
pmac5

Reputation: 65

Removing String from Powershell variable

I am trying to return simply the active username to use later in a script, however I am currently hung up on having my variable populate only the username, excluding the domain.

Function Get-Username() {
$username = Get-WMIObject -class Win32_ComputerSystem | select username

return $username
}


Function Delimit-Username() {
$newUserName = $username -replace 'DOMAIN\',''

Write-Host $newUserName
}

Get-Username
Delimit-Username

Upvotes: 2

Views: 1527

Answers (2)

lit
lit

Reputation: 16246

The USERNAME is also in the environment.

$Env:USERNAME

Upvotes: 0

vrdse
vrdse

Reputation: 3154

The domain is delimited from the user by a \, hence you can use the -split operator and access the second element to get the username without the domain.

('DOMAIN\User' -split '\\')[1]

You can also access the environment variable username ($env:username)

Upvotes: 1

Related Questions