Take a command like this for example:
Get-AdUser -Filter {Enabled -eq $true} -Credential (Get-Credentials) -Server some.server.domain.com | Where-Object {DisplayName -like '*Reemer, Bob*'}
Of course it is gross, long and goes off the screen... what is the preferred way to split this up over multiple lines (to improve readability)?
Please give example that works in ISE, plain powershell interpreter and scripts.
Of course it is gross and long...
It looks perfectly fine to me, but if you want shorter lines, I'd suggest splatting:
$ADUserParams = @{
Filter = {Enabled -eq $true}
Credential = (Get-Credential)
Server = 'some.server.domain.com'
}
Get-ADUser @ADUserParams | Where-Object {DisplayName -like '*Reemer, Bob*'}
You could also split the Where-Object filter scriptblock over multiple lines:
Get-ADUser -Filter {Enabled -eq $true} -Credential (Get-Credentials) -Server some.server.domain.com | Where-Object {
DisplayName -like '*Reemer, Bob*'
}
If you always reuse the same parameter value a lot, you can use $PSDefaultParameterValues as well:
$PSDefaultParameterValues['*-AD*:Server'] = 'some.server.domain.com'
Get-ADUser -Filter {Enabled -eq $true} -Credential (Get-Credentials) | Where-Object {DisplayName -like '*Reemer, Bob*'}
And of course you can combine all of them:
$PSDefaultParameterValues['*-AD*:Server'] = 'some.server.domain.com'
$ADUserParams = @{
Filter = {Enabled -eq $true}
Credential = (Get-Credential)
}
Get-ADUser @ADUserParams | Where-Object {
DisplayName -like '*Reemer, Bob*'
}
You can use the line continuation character, which is a backtick `, as in Bryce's answer.
But I don't like that at all. It's hard to see, makes editing a pain, and is overall ugly.
Instead, I recommend splatting.
This lets you define your parameters both dynamically, and with better formatting for the hashtable, making your function/cmdlet call nice and neat:
$myParams = @{
Filter = { Enabled -eq $true }
Credential = (Get-Credential)
Server = 'some.server.domain.com'
}
Get-ADUser @myParams
Note that you can modify the hashtable as many times as you want before calling, and you can combine splatting with individual parameters.
$myParams = @{
Filter = { Enabled -eq $true }
Credential = (Get-Credential)
}
$myParams.Server = Get-MyCustomServer
Get-ADUser @myParams -Verbose
For the pipe, just use a newline directly after the | character. That part I like a lot and I use it all the time.
You can also use newlines inside a scriptblock, so you have great separation options there as well.
Get-ADUser @myParams -Verbose |
Where-Object -FilterScript {
$_.SomeProperty -eq $SomeValue
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With