[英]Null troubles with PowerShell AD script for creating new users
Been smooth sailing with creating users for my domain, now I'm trying to set the uidNumber based on what the last 4 digits of the generated objectSid.为我的域创建用户一帆风顺,现在我正在尝试根据生成的 objectSid 的最后 4 位数字设置 uidNumber。 Might be a simple solution but hoping for some help.可能是一个简单的解决方案,但希望得到一些帮助。
The rest of the code runs fine until we get to the '$last4' variable so I snipped to make it shorter, but if putting the whole script helps, happy to do so.代码的 rest 运行良好,直到我们到达“$last4”变量,所以我剪短了它以使其更短,但如果放置整个脚本有帮助,我很乐意这样做。
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}
Error错误
You cannot call a method on a null-valued expression.您不能对空值表达式调用方法。 At C:\Users\Administrator\Desktop\newtry.ps1:31 char:1在 C:\Users\Administrator\Desktop\newtry.ps1:31 char:1
- $last4DigitsOfObjectSid = $objectSid.Substring($objectSid.Length - 4) $last4DigitsOfObjectSid = $objectSid.Substring($objectSid.Length - 4)
CategoryInfo: InvalidOperation: (:) [], RuntimeException FullyQualifiedErrorId: InvokeMethodOnNull CategoryInfo: InvalidOperation: (:) [], RuntimeException FullyQualifiedErrorId: InvokeMethodOnNull
objectSid
is not an attribute that Get-ADUser
returns by default, the attribute you're looking for is just SID
. objectSid
不是Get-ADUser
默认返回的属性,您要查找的属性只是SID
。 $objectSid
in your snippet is actually null, hence the error you're having. $objectSid
在你的片段中实际上是 null,因此你有错误。
Also, Substring
is a String method and SID
and objectSid
are instances of SecurityIdentifier
.此外, Substring
是一个 String 方法, SID
和objectSid
是SecurityIdentifier
的实例。 This class does not have a Substring
method.这个 class 没有Substring
方法。 You would need to refer to the .Value
property :您需要参考.Value
属性:
$sid = $user.SID
$last4DigitsOfObjectSid = $sid.Value.Substring($sid.Value.Length - 4)
A much easier way of getting the last 4 digits would be with -replace
which will coerce the SecurityIdentifier
to a string before replacing:获取最后 4 位数字的更简单方法是使用-replace
,它会在替换之前将SecurityIdentifier
强制转换为字符串:
$sid = $user.SID
$last4DigitsOfObjectSid = $sid -replace '.+(?=.{4}$)'
Or using -split
which would also work for SIDs having less than 4 digits:或者使用-split
也适用于少于 4 位数字的 SID:
$last4DigitsOfObjectSid = ($sid -split '-')[-1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.