Change Terminal Services Profile Path PowerShell

/ October 28th, 2014/ Posted in Random / No Comments »

Problem: I needed to change all domain users to the new terminal services profile server

Solution
I was able to create a powershell script that loops through the domain and finds instances of where the terminal services profile path is set to the old server. It then replaces the old server with the new server name and logs the output to console.

You can modify the below to limit the scope of the items found (findall() only does 1000 objects by default) by changing adding in an OU filter or creating a function that adds in the user. In any case my problem was solved with the below script.

$root = "LDAP://DC=GALAXY,DC=local"
$searcher = ([ADSISearcher]"(&(samAccountType=805306368)(!userAccountControl:1.2.840.113556.1.4.803:=2))") #user account type will be person and the account not disabled.
$searcher.SearchRoot=$root
$users = $searcher.findall()
 foreach ($user in $users) {
    try {
    $userSearch = ""
    $tsprofilepath = ""
    $username = ""
    $userSearch = [adsi]"$($user.path)"
    $tsprofilepath = $userSearch.psbase.InvokeGet("TerminalServicesProfilePath")
    
    $username = $userSearch.psbase.InvokeGet("sAMAccountName")
                
       if ($tsprofilepath) { #check for not null
            if ($tsprofilepath.contains("OLDSERVERNAME")) { #check for containing string
                $newtsprofilepath = $tsprofilepath.Replace("OLDSERVERNAME", "NEWSERVERNAME") ##set ts profile path location
                Write-Output "$username has profile path of $tsprofilepath"#log existing
                $userSearch.psbase.Invokeset(‚Äúterminalservicesprofilepath‚ÄĚ, $newtsprofilepath) #set new path
                $userSearch.setinfo() #save user info
                Write-Output "$username changed profile path to $newtsprofilepath" #log new path
                }
            else {
                Write-Output "$username has a profile path of $tsprofilepath" #log already has new path
                }
            }
            else {
                Write-Output "$username has a no profile path set" #log already has no path
            }
            #start-sleep 1 #loop sleep Timer
        }
        catch { 
        #error handle
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName
        Write-Output "$username had an error of: $ErrorMessage"
        Write-Output "$FailedItem"
    }
}

Tags:

Leave a Reply

Name required

Please Submit Answer * Time limit is exhausted. Please reload CAPTCHA.