Powershell – How to set a default domain controller for all PowerShell AD cmdlets

active-directorydomain-controllerpowershell

All the PowerShell cmdlets in the ActiveDirectory module support being run against a specific domain controller using the -server parameter; but is there any way to set a default DC to use for all AD-related operations, or do I need to specify it on every single command if I actually care about which DC I'm using (as is frequent when replication latency is involved)?

Best Answer

If you are on PowerShell version 3, then you can use the new automatic variable $PSDefaultParameterValues to set a default for the Server parameter on the AD Module cmdlets. You can run

Get-Help about_Parameters_Default_Values

for more details on this variable.

In your specific case, you could set the variable like so:

$PSDefaultParameterValues = @{"*-AD*:Server"='YOUR-CHOSEN-DC'}

Another option which would work with version 2 or 3, is to use the AD Module's provider to create a new PSDrive.

By default when you import the AD Module, it creates an "AD:" PSDrive which connects to the local domain. You can create new PSDrives using this same provider, specifying the specific domain controller you want to connect to. Then, when you run AD cmdlets from within the context of that PSDrive, they will use that connection. You can create a new PSDrive like so:

New-PSDrive -Name <name of the drive> -PSProvider ActiveDirectory -Root "<DN of the partition/NC>" –Server <server or domain name (NetBIOS/FQDN)[:port number]> -Credential <domain name>\<username>

Then just cd <name of drive>: and when you run your cmdlets, they will use the domain controller you specified in the New-PSDrive cmdlet.