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

PowerShell AD用户创建脚本Null错误:objectSid取值异常求助

问题:提取ObjectSID后4位设置uidNumber时触发空值错误

此前域用户创建流程运行顺畅,现尝试基于生成的ObjectSID最后4位设置uidNumber,但执行到$last4DigitsOfObjectSid变量时出现错误,其余代码运行正常。

代码片段:

Import-Module ActiveDirectory

$firstname = Read-Host -Prompt "Please enter the first name"
$lastname = Read-Host -Prompt "Please enter the last name"

$location = Read-Host -Prompt "Please enter user location (LA/NY)"
$path = "OU=Users,OU=$location,OU=GS,DC=random,DC=com"

New-ADUser `
   -snip

Add-ADGroupMember `
    -Identity "$snip" -Members $username

$user = Get-ADUser -Identity $username

$objectSid = $user.objectSid

$last4DigitsOfObjectSid = $objectSid.Substring($objectSid.Length - 4)
$newUidNumber = "71$last4DigitsOfObjectSid"

Set-ADUser -Identity $username -Replace @{'uidNumber'=$newUidNumber}

错误信息:

You cannot call a method on a null-valued expression.
At C:\Users\Administrator\Desktop\newtry.ps1:31 char:1

  • $last4DigitsOfObjectSid = $objectSid.Substring($objectSid.Length - 4)

CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : InvokeMethodOnNull


原因分析

错误提示无法对空值表达式调用方法,本质是$objectSid并非可直接调用Substring的字符串类型:Get-ADUser返回的objectSid是SecurityIdentifier类型的对象,直接赋值给变量后无法直接使用字符串方法,导致调用Substring时触发空值错误。


解决方法

方法1:将SecurityIdentifier对象转为字符串后处理

修改相关代码段,先把SID对象转为字符串,再提取后4位:

$user = Get-ADUser -Identity $username -Properties objectSid
$objectSidStr = $user.objectSid.ToString()
$last4DigitsOfObjectSid = $objectSidStr.Substring($objectSidStr.Length - 4)
$newUidNumber = "71$last4DigitsOfObjectSid"
Set-ADUser -Identity $username -Replace @{'uidNumber'=$newUidNumber}
  • 显式添加-Properties objectSid确保属性被加载(默认可能包含,但显式指定更稳妥)
  • 用.ToString()将SID对象转换为可操作的字符串

方法2:直接提取SID的RID(相对标识符)

SID的结构为S-1-5-21-xxx-xxx-xxx-RID,其中RID是用户的唯一标识数字,也就是SID最后一段的数值,直接提取更可靠:

$user = Get-ADUser -Identity $username
$rid = $user.objectSid.Value.Split('-')[-1]
# 若RID不足4位,自动补前导零至4位
$last4DigitsOfObjectSid = $rid.PadLeft(4, '0')
$newUidNumber = "71$last4DigitsOfObjectSid"
Set-ADUser -Identity $username -Replace @{'uidNumber'=$newUidNumber}

此方法避免了字符串长度依赖,即使RID位数变化也能保证取到最后一段数值,适配性更强。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 02:06:03