Powershell to update hosts file on PDQ from RAS VPN Clients
To start with I want to say I am not a powershell expert but I am hoping this might help some people
Second we manually update the Description of Computers in our AD with the name of the associated User
I prepped by copying the default hosts to a start_hosts file
$Server = "[YOUR VPN SERVER]" # Declare the host of the Microsoft VPN / RAS Server
$startfile = "C:\Windows\System32\drivers\etc\start_hosts"
$hostfile = "C:\Windows\System32\drivers\etc\hosts"
$Records = "" # Ensure this is empty
Copy-Item $startfile $hostfile # Replace old hosts with clean copy
$session = New-PSSession -ComputerName $Server # set session to pull Client Info
$Clients = Invoke-Command -Session $session -ScriptBlock {Get-RemoteAccessConnectionStatistics }
# Store Client Info in $Clients
Remove-PSSession $session # Cleanup
# Client Username is stored as DOMAIN\USER For each we will Split on the \ and use the 2nd entry
# $temp[0] stores the DOMAIN $temp[1] Stores the UserName
# In theory you should be able to pull everything from this but for some reason
#HostName and PSComputerName are null for my clients.
# UserName, ClientIPv4Address are present so I am using this to find the computer
Foreach ( $Client in $Clients) {
$temp = $Client.UserName
$temp = $temp.split("\")
$User = get-aduser $temp[1] # Load Domain Profile for the Connected Client
# Load the Computer whose description matches the Name of the client
# My Search Base is hardcoded I know bad practice it should be a variable at the top ...
$Computer = Get-ADComputer -searchbase "OU=Workstations,OU=Domain,DC=osprey,DC=com" -Filter {Description -eq $User.Name }
#Setup the record for the Host file
$Record = $Client.ClientIPv4Address+" "+$Computer.Name+" #"+$User.Name+"`n"
# Append the new record to the host file
[System.IO.File]::appendalltext($hostfile, $Record+"`r`n")
}
Profit !
Comments
Is there anyway to setup PDQ Inventory to run this script before a Scan cycle ?
There's no official way to do that, but I have a hacky idea.