簡體   English   中英

Null PowerShell 創建新用戶的AD腳本問題

[英]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 方法, SIDobjectSidSecurityIdentifier的實例。 這個 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM