Recently my powershell scripts require to explicitly say which domain I want to connect to. Is it necessary to write this for each command? Or can I set it somehow once in the beginning of the script.
Instead of Get-ADUser -Server server otherparameters
could I write in the beginning something like Set-default server to connect to ?
Is it necessary to write this for each command?
You can specify a default parameter value for a parameter belonging to one or more cmdlets by assigning it to the $PSDefaultParameterValues
automatic variable:
$PSDefaultParameterValues['*-AD*:Server'] = 'mydc.mydomain.tld'
Any cmdlet you subsequently invoke that matches the *-AD*
pattern by name and has a -Server
parameter will now implicitly have 'mydc.mydomain.tld'
bound to the -Server
parameter unless an argument is explicitly passed.
In other words: next time you invoke Get-ADUser rsterba
, PowerShell now calls Get-ADUser rsterba -Server 'mydc.mydomain.tld'
instead.
For more information about $PSDefaultParameterValues
and how it works, see the about_Parameters_Default_Values
help topic
If you want to pass the same argument but selectively, use partial splatting to avoid re-typing -Server ...
:
# define target DC in a hashtable
$srv = @{ Server = 'mydc.mydomain.tld'}
# ... it doesn't have to be a hardcoded value
$srv = @{ Server = (Get-ADDomainController -Discover -Service PrimaryDC).HostName}
# `@srv` will expand to `-Server <DC hostname>`
Get-ADUser <# other parameters #> @srv
# ... but it no longer applies by default, so omitting it restore the original behavior
Get-ADUser <# other parameters #>