9

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?

2 Answers 2

15

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's the simplest solution and does exactly what's needed!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.