I am trying to create function that will receive an argument as log file path.
I want this parameter to be able to receive string path or used as a [switch], without any arguments.
The reason I want to do it is because I have three scenarios I need to cover and I wanted to do it with only one parameter:
1. The parameter is not passed
2. The parameter is passed with empty argument
3. The parameter is passed with argument
Here is a script that demonstrate what I want:
function myFunc(){
param(
$LogFile = $null
)
# 1. PS > myFunc
if($LogFile -eq $null){
}
# 2. PS > myFunc -LogFile
if($LogFile -eq ""){
}
# 3. PS > myFunc -LogFile "C:\tmp\log.txt"
else{
}
}
Is it possible to create such input parameter that can receive empty and non-empty values ?
When I run myFunc -LogFile I receive an error:
myFunc : Missing an argument for parameter 'LogFile'. Specify a parameter of type 'System.Object' and try again.
At line:1 char:8
+ myFunc -LogFile
+ ~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [myFunc], ParameterBindingException
+ FullyQualifiedErrorId : MissingArgument,myFunc
This is because it is not set to [switch] and if I add the [switch] than I can't run myFunc -LogFile c:\tmp\file.txt:
myFunc : A positional parameter cannot be found that accepts argument 'C:\tmp\file.txt'.
At line:1 char:1
+ myFunc -LogFile C:\tmp\file.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [myFunc], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,myFunc
I also tried to use [AllowNull()] and [AllowEmptyString()] but they still require to some char.
More information about the parameters can find here.