I’m trying to write a custom powershell script that will create a local user if no user exists with the specified name.
I have this script :
function Ensure-LocalUser
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string] $userName,
[Parameter(Mandatory=$true)]
[string] $passWord
)
process{
$objOu = [ADSI]"WinNT://${env:Computername}"
$localUsers = $objOu.Children | where {$_.SchemaClassName -eq 'user'} | Select {$_.name[0].ToString()}
if($localUsers -NotContains $userName)
{
$objUser = $objOU.Create("User", $userName)
$objUser.setpassword($password)
$objUser.SetInfo()
$objUser.description = "CMM Test user"
$objUser.SetInfo()
return $true
}
else
{
return $false
}
}
}
The part related to the creation of the user works, but my -NotContains verification always return false. This leads to a failing attempt to create a user because the user already exists. Using a debugger, I can see that $localusers actually contains the username I’m looking for.
How can I correct my script to reach my goal ?
Change this line
with