Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a PowerShell script, is it possible to tell whether a default parameter value is being used?

Tags:

powershell

Lets say I have a simple script with one parameter, which has a default value:

param(
    [string] $logOutput = "C:\SomeFolder\File.txt"
)
# Script...

And lets say a user runs the script like so:

PS C:\> .\MyScript.ps1 -logOutput "C:\SomeFolder\File.txt"

Is there any way the script is able to know that the user explicitly entered a value (which happens to be the same as the default), rather than let the default be decided automatically?

In this example, the script is going to print some output to the given file. If the file was not specified by the user (i.e. the default got used automatically), then the script will not produce an error in the event it is unable to write to that location, and will just carry on silently. However, if the user did specify the location, and the script is unable to write to that location, then it should produce an error and stop, warning the user. How could I implement this kind of logic?

like image 809
Scott Avatar asked Jan 29 '14 15:01

Scott


2 Answers

The simplest way to tell if a parameter was specified or not when you have a default is to look at $PSBoundParameters. For example:

if ($PSBoundParameters.ContainsKey('LogPath')) {
    # User specified -LogPath 
} else {
    # User did not specify -LogPath
}
like image 117
Jason Shirk Avatar answered Sep 23 '22 18:09

Jason Shirk


Would this work for you?

function Test-Param
        {
            [CmdletBinding()]
            param(
              [ValidateScript({Try {$null | Set-Content $_ -ErrorAction Stop
                                    Remove-Item $_
                                    $True}
                                Catch {$False}
                                })]
              [string] $logOutput = 'C:\SomeFolder\File.txt'


            )
        }

The validate script will only run and throw an error if it is unable to write to the file location passed in using the -logOutput parameter. If the parameter is not specified, the test will not be run, and $logOutput will get set to the default value.

like image 29
mjolinor Avatar answered Sep 25 '22 18:09

mjolinor