Getting complex – More line breaks in Powershell
This is a follow up to Jacob Moran’s article Keeping it simple - Line breaks in PowerShell.
I am strongly in the pro backtick camp, but I won’t get into that debate here. Instead, I’ll cover more of the common ground between the two camps.
In addition to after a pipe, there are many, many more places where you can put in a line break without a backtick and without breaking your code.
As a rule of thumb, any spot where the syntax unambiguously must be followed by something more, you can break the line.
As an extreme example, this:
$A
=
1
,
1
1
,
3
$B
= @( “a”
,
“b”
,
“c” ) If ( $A
[
2
]
. ToString() -eq
$B
[
2
]
. Length -or ( Get-Date ) . Date . DayOfWeek -eq
‘Tuesday’ ) { [pscustomobject] @{ Name
“x” } }
Can be written like this:
$A
=
1
,
1
1
,
3
$B
= @(
“a”
“b”
“c”
)
If (
$A
[
2
]
.
ToString( ) -eq
$B
[
2
]
.
Length -or
(
Get-Date
) .
Date .
DayOfWeek -eq
‘Tuesday’
) {
[ pscustomobject] @{ Name
“x”
} }
That example is, of course, silly.
But combine judicious use of the line break with appropriate horizontal whitespace, and you can turn this:
If ( $SourceFile1
. Length /
1Gb
-gt
$MaxSizeGB
-and ( $SourceFile1
. FullName -like
“*\Accounting*”
-or
$SourceFile1
. FullName -like
“*\Finance*” ) ) {
$Destination
=
$SourceFile1
. FullName . Replace( $SourceShare
,
$DestinationShare ) . Replace( ‘\Accounting'
,
‘\ACC' ) . Replace( ‘\Accounting'
,
‘\FIN' ) }
Into this:
If ( $SourceFile1
. Length /
1Gb
-gt
$MaxSizeGB
-and
(
$SourceFile1
. FullName -like
“*\Accounting*”
-or
$SourceFile1
. FullName -like
“*\Finance*” ) )
{
$Destination
=
$SourceFile1
. FullName .
Replace(
$SourceShare
,
$DestinationShare ) .
Replace(
‘\Accounting'
,
‘\ACC' ) .
Replace(
‘\Accounting'
,
‘\FIN' )
}
Related Articles
So you want to start a User Group
But where do you begin? I’ve blogged about this from the reversed perspective on my own blog about finding user groups with a …
Read moreICYMI: PowerShell Week of 02-April-2021
Topics include help sections, Approved Verbs, Identity Management and more…
Read moreMedia Sync: Organize Your Photos and Videos with PowerShell
Do you have photos and videos that you have taken over the years that are scattered all over the place? Do you want to have …
Read more