Important Notice: On February 29th, this community was put into read-only mode. All existing posts will remain but customers are unable to add new posts or comment on existing. Please feel to join our Community Discord for any questions and discussions.

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 !

1

Comments

2 comments
Date Votes
  • Is there anyway to setup PDQ Inventory to run this script before a Scan cycle ?

    0
  • There's no official way to do that, but I have a hacky idea.

    1. Create a static Collection that only contains your PDQ Inventory host
    2. Create a PowerShell Scanner in a new Scan Profile with your script
    3. Go to the Collections tab of this Scan Profile and Link it to the Collection
    4. Set the Trigger for this Collection to happen before your other Scan Profile
    0