Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Here's something that bedeviled me for the longest time: if I have a [switch] type parameter at the script level, how do I pass it to the core function it calls?
# script Test-It.ps1 will call Test-It function
param (
[String[]]$ComputerName = @(),
[switch]$Full
);
function Test-It {
param (
[String[]]$ComputerName = $script:ComputerName
[switch]$Full
);
$ComputerName | % {
if ($Full) {
$_;
} else {
$_ -replace "\..*";
}
}
}
Test-It -ComputerName $ComputerName # how to handle $Full?
I could branch based on $Full to two different calls to Test-It.
if ($Full) {
Test-It -ComputerName $ComputerName -Full;
} else {
Test-It -ComputerName $ComputerName;
}
That works, but what if I have three [switch] parameters, such as from the Get-ConsoleBuffer function a few days back? I'd have to have a binary tree of if () ... else () three deep with eight separate versions of calls to Test-It.
Actually, Get-ConsoleBuffer uses my solution:
# script Test-It.ps1 will call Test-It function
param (
[String[]]$ComputerName = @(),
[switch]$Full
);
function Test-It {
param (
[String[]]$ComputerName = $script:ComputerName
[switch]$Full,
[bool]$__boolFull );
if (!$Full) { $Full = $__boolFull; }
$ComputerName | % {
if ($Full) {
$_;
} else {
$_ -replace "\..*";
}
}
}
Test-It -ComputerName $ComputerName -__boolFull $Full;
I use an [bool] parameter, _boolFull, to accept the value of $Full specified in the outer script. It has an 'ugly' name to remind me that it's the [bool] equivalent of the the user-friendly [switch] parameter. As a matter of personal style I use variable names starting with double-underscore as 'system' variables, i.e.: variables that aren't intended for end-user use.
(For those into computer culture/trivia, this is a variation of Hungarian Notation.)
This means that, for any number of [switch] parameters, I only need to make one version of the call to the nested function.
a
Comments
- Anonymous
October 08, 2013
The comment has been removed