2

I have a small PowerShell script that creates a user on various Windows platforms (2016,2012 and possibly 2008). The script mentioned below works fine on windows 2016 but it seems that it's not working on 2012 and I am guessing it won't work on 2008 as well. It's probably related to the PowerShell version but I am not sure if there is way to fix that properly. The script is the one below:

$username = "user"
$password = "pass1234"

Clear-Host
$ErrorActionPreference = 'Stop'
$VerbosePreference = 'Continue'

#User to search for
$USERNAME = "user"

#Declare LocalUser Object
$ObjLocalUser = $null

Try {
    Write-Verbose "Searching for $($USERNAME) in LocalUser DataBase"
    $ObjLocalUser = Get-LocalUser $USERNAME
    Write-Verbose "User $($USERNAME) was found"
}

Catch [Microsoft.PowerShell.Commands.UserNotFoundException] {
    "User $($USERNAME) was not found" | Write-Warning
}

Catch {
    "An unspecifed error occured" | Write-Error
    Exit # Stop Powershell! 
}

#Create the user if it was not found (Example)
If (!$ObjLocalUser) {
    New-LocalUser $username -Password $password -Description "test"
    Write-Verbose "$username account created"
    Add-LocalGroupMember -Group "Administrators" -Member $username
    Write-Verbose "$username added to the local administrator group"
}
else {
    Write-Host "User already created"
}

The error suggests that it's a problem with [Microsoft.PowerShell.Commands.UserNotFoundException] and it requires to load up some assemblies:

Unable to find type [Microsoft.PowerShell.Commands.UserNotFoundException].

Make sure that the assembly that contains this type is loaded.

Did anyone worked with assemblies before and have an idea on how to load up these assemblies? Any help would be appreciated.

1 Answer 1

2

Seems it's related to the WMF version. Windows 2012 comes with 4.0 and Windows 2016 comes with 5.1 by default. Updating WMF on windows 2012 to 5.1 solves the problem. This can be closed.

Sign up to request clarification or add additional context in comments.

2 Comments

You are right this is because of 2012 r2 i tested the script
You may accept your own answer to make it more obvious that this problem has been solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.