[英]Null troubles with PowerShell AD script for creating new users
為我的域創建用戶一帆風順,現在我正在嘗試根據生成的 objectSid 的最后 4 位數字設置 uidNumber。 可能是一個簡單的解決方案,但希望得到一些幫助。
代碼的 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}
錯誤
您不能對空值表達式調用方法。 在 C:\Users\Administrator\Desktop\newtry.ps1:31 char:1
- $last4DigitsOfObjectSid = $objectSid.Substring($objectSid.Length - 4)
CategoryInfo: InvalidOperation: (:) [], RuntimeException FullyQualifiedErrorId: InvokeMethodOnNull
objectSid
不是Get-ADUser
默認返回的屬性,您要查找的屬性只是SID
。 $objectSid
在你的片段中實際上是 null,因此你有錯誤。
此外, Substring
是一個 String 方法, SID
和objectSid
是SecurityIdentifier
的實例。 這個 class 沒有Substring
方法。 您需要參考.Value
屬性:
$sid = $user.SID
$last4DigitsOfObjectSid = $sid.Value.Substring($sid.Value.Length - 4)
獲取最后 4 位數字的更簡單方法是使用-replace
,它會在替換之前將SecurityIdentifier
強制轉換為字符串:
$sid = $user.SID
$last4DigitsOfObjectSid = $sid -replace '.+(?=.{4}$)'
或者使用-split
也適用於少於 4 位數字的 SID:
$last4DigitsOfObjectSid = ($sid -split '-')[-1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.