Search code examples
powershellenvironmentrdpwmic

Assign logon script in Environment Tab for terminal server client using Powershell


Hi I am looking to set the logon script parameter for a user profile, using Powershell. I was planning to use WMIC USERACCOUNT to do this but found that it is not possible. As shown below the method does not exist in the method:

    class Win32_UserAccount : Win32_Account
{
  uint32   AccountType;
  string   Caption;
  string   Description;
  boolean  Disabled;
  string   Domain;
  string   FullName;
  datetime InstallDate;
  boolean  LocalAccount;
  boolean  Lockout;
  string   Name;
  boolean  PasswordChangeable;
  boolean  PasswordExpires;
  boolean  PasswordRequired;
  string   SID;
  uint8    SIDType;
  string   Status;
};

I would prefer to do this as a statement in powershell but if that is not possible it could be done as a script I am looking to set the parameter shown in picture, for a Win Server 2008 R2 this parameter


Solution

  • It took a long time but finally got the answer the trick was to use IADsTSUserEx. I also tried to use ADSI but could only get it to set a logon script for logging on localy. See other post. Here is the code plus for Elijiah how to set environment varibles of local users through the registry

    # adds user
    $objComputer = [ADSI]"WinNT://127.0.0.1"
    $objUser = $objComputer.Create('user', $username)
    $objUser.SetPassword($password)
    $objUser.PSBase.InvokeSet('Description', "user " + $userName)
    $objUser.PSBase.InvokeSet('userflags', 512)
    $objUser.SetInfo();
    # set password not to expire
    wmic USERACCOUNT WHERE "Name = '$username'" SET Passwordexpires=FALSE
    #set logoff script
    $ou = [adsi]"WinNT://127.0.0.1"
    $user = $ou.psbase.get_children().find("test")
    $user.PSBase.InvokeSet("TerminalServicesInitialProgram", "C:\logoff.bat")
    $user.setinfo()
    #add to group
    net localgroup $groupname $username /add
    net localgroup "Remote Desktop Users" $username /add
    #remote login
    cmdkey /generic:TERMSRV/127.0.0.1 /user: $username /pass: $password
    #add logoff script
    #launch remote desktop
    mstsc /v:127.0.0.1 | Out-Null
    cmdkey /delete:TERMSRV/127.0.0.1
    #load hive
    reg load HKU\%username% "C:\Users\$username\NTUSER.dat"
    #set environment valiables
    Set-ItemProperty -Path HKU:\$username\Environment -Name SERVERTYPE -Type STRING -Value DIR
    #Unload hive
    reg unload HKU\$username