Quick Learn – Using Out-Variable to Reduce Line Count

I’ve written about Out-Variable before, but I used it today in a way I hadn’t previously, and so I thought I’d take a moment before bed to share it.

I’m in the process of writing some small, reusable code and I want to keep the number of lines to an absolute minimum. In the first section of this reusable code, I want to determine the name of the module that contains the currently running function. Not all functions have a value for the module name, so it’s possible this value might be empty.

The below example is how I might’ve written the command had I not been concerned with keeping the line count low. I first attempt to set the $Module variable to the ModuleName property of the currently running function. Then, I evaluate whether or not the $Module variable contains any value. If it does, and therefore evaluates to true, I set the variable $ModuleNameCode to the value of $Module and a trailing backslash. Pretty straightforward.

$Module = (Get-Command -Name $MyInvocation.MyCommand.Name).ModuleName
If ($Module) {
    $ModuleNameCode = "$Module\"
}

In the second example — which boasts one less line, and is the reason why I’m writing this evening — I evaluate the command as part of the If statement’s conditional section. That’s common enough. What isn’t, is the use of the -OutVariable parameter. This allows me to create my $Module variable on the fly, and then use it as a part of the statement portion in the If statement (the part in curly brackets: { }).

If ((Get-Command -Name $MyInvocation.MyCommand.Name -OutVariable Module).ModuleName) {
    $ModuleNameCode = "$Module\"
}

Well, there it is. It’s a simple, yet possibly unconsidered option for using Out-Variable. It also saved me a line. That’s not a normal concern, but it was, and so this usage paid off. Until next time.

Oh, I should mention that in my little chunk of reusable code, I actually made this If statement only consume a single line, such as I’ve done below. That’s it for real, this time.

If ((Get-Command -Name $MyInvocation.MyCommand.Name -OutVariable Module).ModuleName) {$ModuleNameCode = "$Module\"}

Leave a Reply

Your email address will not be published.