Reputation: 65
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.
Upvotes: 2
Views: 494
Reputation: 65
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.
Upvotes: 2