VMware Cloud Community
jtfox76
Contributor
Contributor
Jump to solution

Invoke-VMscript to create local user on Windows 2012r2 Guuest

I am trying to use the invoke-vmscript to create a local user on a 2012r2 Guest. I have tried 2 different methods both unsuccessfully. Below are those methods. Any guidance would be greatly appreciated. I plan to switch to use a PSCredential instead of standard user and password inputs once I get this working. .

Script 1

This script calls a PS script saved on the local C drive of the guest. I receive an access denied error. If I run the script locally with an elevated PowerShell prompt it works. How can I run PowerShell through the invoke-vmscript elevated? The user account I use to access the guest is a local admin.

#variables

$user = "test"

$userpw = "Thisismypasswordin2017!"

$script = "C:\scripts\create_local_user.ps1 -username $user -password $userpw"

#Executing the Script
#Connect to vCenter
Connect-viserver $vcenter -User $vcenter_user -Password $vcenter_password

#Creating the local User account via the invoke command
Write-Host "Creating local user account"
Invoke-VMScript -VM $bserver -ScriptText $script -GuestUser $adminaccount -GuestPassword $adminpw

create_local_user.ps1

param (
[Parameter(Position=0,Mandatory=$True,HelpMessage="the desired username you want to create")]
[ValidateNotNullOrEmpty()]
[string]$username,

[Parameter(Position=1,Mandatory=$True,HelpMessage="the account's desired password")]
[ValidateNotNullOrEmpty()]
[string]$password

)

$prov = [adsi]"WinNT://localhost,computer"
$user = $prov.Create("User", $username)
#obvious
$user.SetPassword($password)
# set to not expire and not allow changing of password
$user.userflags = 65536 -bor 64
#commit the change
$user.SetInfo()

#add them to the users group
$group = $prov.Children.Find("Users", 'group')
#cant't use the same syntax as you see up above
$group.Add(("WinNT://$env:COMPUTERNAME/$username"))

Error Output

ExitCode     : 0
ScriptOutput : Exception calling "SetInfo" with "0" argument(s): "Access is denied.
               "
               At C:\scripts\create_local_user.ps1:21 char:1
               + $user.SetInfo()
               + ~~~~~~~~~~~~~~~
                   + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
                   + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI

               Exception calling "Add" with "1" argument(s): "A member could not be added to
               or removed from the local group because the member does not exist.
               "
               At C:\scripts\create_local_user.ps1:26 char:1
               + $group.Add(("WinNT://$env:COMPUTERNAME/$username"))
               + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                   + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
                   + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI

Script2

This attempt I installed WRM 5.1 on the 2012r2 guest so I could get the Microsoft.PowerShell.LocalAccounts Module. Whether I run the command through the invoke-vmscript or locally in the guest I get the same error. The only difference between script 1 and script 2 is the variable $script.

$script = "Microsoft.PowerShell.LocalAccounts\New-LocalUser -Name $user -Password $userpw -PasswordNeverExpires -UserMayNotChangePassword"

Error Output

ExitCode     : 0

ScriptOutput : New-LocalUser : Cannot bind parameter 'Password'. Cannot convert the

               "Thisismypasswordin2017!" value of type "System.String" to type

               "System.Security.SecureString".

               At line:1 char:74

               + ... s\New-LocalUser -Name test -Password Thisismypasswordin2017!  -Passwo ...

               +                                          ~~~~~~~~~~~~~~~~~~~~~~~~

                   + CategoryInfo          : InvalidArgument: (:) [New-LocalUser], ParameterB

                  indingException

                   + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerSh

                  ell.Commands.NewLocalUserCommand

Reply
0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

I went back to the beginning of this thread, and noticed your attempt to use the new PS v5.1 local user cmdlets.

The reason that failed is due to the Password parameter type you passed.

Try like this

$vmName = 'MyServer'

$newUser = 'NewUser'

$pswd = 'Password1!'

$getUsers = @"

Get-LocalUser | Select Name |

ConvertTo-Csv -UseCulture -NoTypeInformation

"@

$createNewUser = @"

`$securePswd = ConvertTo-SecureString -AsPlainText -String $pswd -Force

New-LocalUser -Name $newUser -Password `$securePswd -Confirm:`$false

"@

$vm = Get-VM -Name $vmName

# Get local users

$users = Invoke-VMScript -VM $vm -ScriptText $getUsers -ScriptType Powershell |

    Select -ExpandProperty ScriptOutput |

    ConvertFrom-Csv | %{$_.Name}

if($users -notcontains $newUser){

# Create user

    Invoke-VMScript -VM $vm -ScriptText $createNewUser -ScriptType Powershell |

    Select -ExpandProperty ScriptOutput

}

else{

    Write-Output "User $($newUser) aleady exists on $($vm.Name)"

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

Reply
0 Kudos
8 Replies
LucD
Leadership
Leadership
Jump to solution

You might want to have a look at Re: Invoke-VMScript to run ps commands as an administrator

An alternative could be to use psexec from from the SysInternals Suite.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
jtfox76
Contributor
Contributor
Jump to solution

LucD

I have reviewed that thread before but did not see a clear answer. How would I use PSExec?

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Two options there:

  • run psexec from your station, but that requires ports 135 and 445 to be open on the target station
  • run psexec locally on the target station, via Invoke-VMScript, but that requires a copy of psexec on the target station

Which of these two is feasible in your environment?

We're using psexec to avoid all UAC issues.

Would you be able to adapt the UAC settings on the target station?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
jtfox76
Contributor
Contributor
Jump to solution

Yes, I could adapt to use PSExec on the target machine through the invoke-vmscript.

How would that look?

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

I went back to the beginning of this thread, and noticed your attempt to use the new PS v5.1 local user cmdlets.

The reason that failed is due to the Password parameter type you passed.

Try like this

$vmName = 'MyServer'

$newUser = 'NewUser'

$pswd = 'Password1!'

$getUsers = @"

Get-LocalUser | Select Name |

ConvertTo-Csv -UseCulture -NoTypeInformation

"@

$createNewUser = @"

`$securePswd = ConvertTo-SecureString -AsPlainText -String $pswd -Force

New-LocalUser -Name $newUser -Password `$securePswd -Confirm:`$false

"@

$vm = Get-VM -Name $vmName

# Get local users

$users = Invoke-VMScript -VM $vm -ScriptText $getUsers -ScriptType Powershell |

    Select -ExpandProperty ScriptOutput |

    ConvertFrom-Csv | %{$_.Name}

if($users -notcontains $newUser){

# Create user

    Invoke-VMScript -VM $vm -ScriptText $createNewUser -ScriptType Powershell |

    Select -ExpandProperty ScriptOutput

}

else{

    Write-Output "User $($newUser) aleady exists on $($vm.Name)"

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
jtfox76
Contributor
Contributor
Jump to solution

Previously I would get an error about converting to secure string. Using your approach I am getting access denied. I am using a local admin account but NOT the built-in administrator account. Do I still need to run PowerShell elevated? Or do I need to use the built-in admin account?

New-LocalUser : Access denied.

At line:2 char:1

+ New-LocalUser -Name 003JTFoxTestRemote -Password $securePswd -Confirm ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : PermissionDenied: (003JTFoxTestRemote:LocalUser)

    [New-LocalUser], AccessDeniedException

    + FullyQualifiedErrorId : AccessDenied,Microsoft.PowerShell.Commands.NewLo

   calUserCommand

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Not sure, haven't tested that.
I used a domain account that was in the local Administrators group.

Admittedly it was on a W2K16 box, don't have any W2K12R2 left in my lab.

Try the builtin admin.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
jtfox76
Contributor
Contributor
Jump to solution

Using the built-in administrator works.

To use a service account that is a member of the local admins group I had to disabled UAC

“EnableLUA” DWORD to 0 in HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\policies\system

I also added the following line to the $createnewuser script text. I discovered it creates the user but doesn't add the user to a group.

Add-LocalGroupMember -Group Users -Member $newUser -Confirm:`$false