You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell脚本中跳过firstname或lastname为空的用户不执行修改

修改后的完整脚本

$UPNs = Import-Csv -Path "C:\temp\users.csv" -Delimiter ";"

# 拉取用户属性
$Users = ForEach($UPN in $UPNs){
    Get-MsolUser -UserPrincipalName $UPN.UserPrincipalName | Select-Object Userprincipalname,displayname,firstname,lastname
}

$Users | ForEach-Object {
    # 仅当firstname和lastname都不为空/空白时才执行修改
    if (-not [string]::IsNullOrWhiteSpace($_.firstname) -and -not [string]::IsNullOrWhiteSpace($_.lastname)) {
        $DisplayName = $_.firstname + " " + $_.lastname + " " + "(Admin Account)"
        Set-MsolUser -UserPrincipalName $_.userprincipalname -DisplayName $DisplayName
    }
    # 可选:增加跳过日志输出
    <#
    else {
        Write-Host "已跳过用户:$($_.UserPrincipalName),原因:FirstName或LastName属性为空"
    }
    #>
}

核心修改说明

  • 新增属性非空判断逻辑:使用.NET方法[string]::IsNullOrWhiteSpace()同时校验firstname和lastname的有效值,该方法可以覆盖null、空字符串、全空格三种无效场景,判断逻辑更严谨
  • 只有两个属性同时存在有效值时才会执行DisplayName拼接和Set-MsolUser修改操作,不符合条件的用户会直接跳过
  • 额外修复了原脚本中Delimiter参数后的中文双引号问题,替换为英文双引号避免PowerShell解析报错

内容的提问来源于stack exchange,提问作者user16113972

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:45:03