简体   繁体   中英

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. 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.

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

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

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 in your snippet is actually null, hence the error you're having.

Also, Substring is a String method and SID and objectSid are instances of SecurityIdentifier . This class does not have a Substring method. You would need to refer to the .Value property :

$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:

$sid = $user.SID
$last4DigitsOfObjectSid = $sid -replace '.+(?=.{4}$)'

Or using -split which would also work for SIDs having less than 4 digits:

$last4DigitsOfObjectSid = ($sid -split '-')[-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM