You want to use the closest Domain Controller (DC) in you powershell script, then you can simply use this one-liner:
Get-ADDomainController -Discover -NextClosestSite
The parameter -NextClosestSite does deliver you the closest Domain Controller, either in your Site, or in the best Site based on the Site link costs, based on the Microsoft Article about the cmdlet:

Source: Get-ADDomainController