Closed Sekers closed 3 years ago
Indeed, this is a known issue with the original script. I typically run this during off-hours to avoid removing active user connections. Thanks for the suggestion for this change though. I will do some testing with it and see how it works. If there are no issues I'll update the script with your suggested changes. Thanks!
Thank you. In my copy, I made a slight change and also moved the initial write-verbose out of the loop so it only gets printed once.
# // Remove users with connections exceeding the value of MaxAge
Write-Verbose "Disconnecting VPN connections older than $MaxAge seconds..."
Foreach ($User in $Connections)
{
Write-Verbose ("" + $User.Username + " (" + $User.ClientIPAddress.IPAddressToString + ")")
Disconnect-VpnUser -HostIPAddress $User.ClientIPAddress.IPAddressToString
}
Sorry for the long delay! This slipped off my radar until recently when another customer asked me about this. I've implemented your changes, with the slight change to use ClientIPv4Address instead of ClientIPAddress to handle those scenarios when a client has both an IPv4 and IPv6 address. I'm making the assumption that the client will always have an IPv4 address, as IPv6-only networks are exceedingly rare. :) Thanks again for the assist on this!
Thank you for posting this script. We are running into the duplicate clients issue with device tunnel and thought this script would be cleaner than restarting the service regularly.
However, since the Disconnect-VpnUser command targets the username, it closes out all connections with that name, not just ones that we consider stale.
The solution I recommend is disconnecting by HostIpAddress instead of Username (see changes below). However, please correct me as I understand there may be something I am missing.
OLD $Connections = Get-RemoteAccessConnectionStatistics | Where-Object ConnectionDuration -ge $MaxAge | Select-Object -ExpandProperty UserName -Unique
NEW $Connections = Get-RemoteAccessConnectionStatistics | Where-Object ConnectionDuration -ge $MaxAge | Select-Object Username, ClientIPAddress | Sort-Object UserName
OLD Write-Verbose "Removing VPN connections older than $MaxAge seconds..." Disconnect-VpnUser -UserName $User
NEW Write-Verbose "Removing VPN connections older than $MaxAge seconds..." $User.Username Disconnect-VpnUser -HostIPAddress $User.ClientIPAddress.IPAddressToString