powershell - Set-ADUser : Object reference not set to an instance of an object. What does this mean? - Stack Overflow

admin2025-04-27  3

I am trying to run a script to change the account settings of all users.

$users = (Get-ADUser -Filter * | Select sAMAccountNAme)

for ($users) {Set-ADUser -Identity $users -CannotChangePassword $false}

I get "Set-ADUser : Object reference not set to an instance of an object". What does this mean?

I am trying to run a script to change the account settings of all users.

$users = (Get-ADUser -Filter * | Select sAMAccountNAme)

for ($users) {Set-ADUser -Identity $users -CannotChangePassword $false}

I get "Set-ADUser : Object reference not set to an instance of an object". What does this mean?

Share Improve this question asked Jan 11 at 15:12 Jingle BellsJingle Bells 1 2
  • Check out foreach and ForEach-Object – Daniel Commented Jan 11 at 15:33
  • 2 Isn't that an infinite loop? For works like this: for ($i = 1; $i -le 10; $i++ ){ $i } – js2010 Commented Jan 11 at 17:49
Add a comment  | 

1 Answer 1

Reset to default 0

... |Select sAMAccountName is gonna create 1 or more custom objects with a single sAMAccountName property, and Set-ADUser doesn't know what to do with an array of such objects.

Either skip Select-Object completely:

$users = Get-ADUser -Filter *

..., or rename the sAMAccountName property so PowerShell will know to bind it to Set-ADUser -Identity:

$users = Get-ADUser -Filter * |Select-Object @{Name='Identity';Expression='sAMAccountName'}

... and then finally pipe the input objects to Set-ADUser:

$users |Set-ADUser -CannotChangePassword:$false

If you skipped the |Select-Object step, PowerShell will recognize that the input objects match the type of Set-ADUser's -Instance parameter, whereas if you renamed the property to Identity, PowerShell will instead bind the account name to -Identity by name.

转载请注明原文地址:http://anycun.com/QandA/1745706697a91096.html