I have a little script to set displayname in bulk for some user. But some of my users do not have a value like 'Firstname' and 'Lastname' in there objects. I have tried to look for it, but cannot find to skip this users from my script.
$UPNs = Import-Csv -Path "C:\temp\users.csv" -Delimiter “;”
#.UserPrincipalName, means the value of the first row in CSV file
$Users = ForEach($UPN in $UPNs){Get-MsolUser -UserPrincipalName $UPN.UserPrincipalName | Select-Object Userprincipalname,displayname,firstname,lastname}
$Users | ForEach-Object {
$DisplayName = $_.firstname " " $_.lastname " " "(Admin Account)"
set-msoluser -UserPrincipalName $_.userprincipalname -DisplayName $DisplayName
}
How can I made this script to say, "no 'firstname' or 'lastname' -> do not change object"
Many thanks,
Ricardo
CodePudding user response:
# Filter out users unless both FirstName and LastName has values
$Users |Where-Object {$_.FirstName -and $_.LastName} | ForEach-Object {
$DisplayName = $_.firstname " " $_.lastname " " "(Admin Account)"
set-msoluser -UserPrincipalName $_.userprincipalname -DisplayName $DisplayName
}
Here, we use the -and
boolean logic operator to ensure that both $_.FirstName
and $_.LastName
has a value that is truthy - $null
and empty strings will evaluate to $false
in a boolean context, strings with any other value will evaluate to $true
.
If you also want to skip when either consists of just whitespace, use the static [string]::IsNullOrWhiteSpace()
method
# Filter out users unless both FirstName and LastName has non-whitespace-only values
$Users |Where-Object {-not([string]::IsNullOrWhiteSpace($_.FirstName)) -and -not([string]::IsNullOrWhiteSpace($_.LastName))} | ForEach-Object {
$DisplayName = $_.firstname " " $_.lastname " " "(Admin Account)"
set-msoluser -UserPrincipalName $_.userprincipalname -DisplayName $DisplayName
}