I'm pretty new to PowerShell but loving it for automating loads of tasks on our Windows machines. I love that you can call functions from other scripts, however the scripts I have written all use parameters the user can provide (so it's easier for colleagues to use them).
There is one parameter in particular that is usually mandatory in my scripts. The problem I'm facing is calling functions from scripts with mandatory parameters.
Here's a simple example:
Param(
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$VirtualMachine=$(throw "Machine name missing!"),
[int]$Attempts = 150
)
Function DoSomething($VirtualMachine, $Attempts){
write("$VirtualMachine and $Attempts")
}
Running this as a script you would provide -VirtualMachine "VMnameHere" -Attempts 123. Running this would produce VMnameHere and 123. Perfect! However.. If I try to call this as a function from another script..
Example here:
. ".\Manage-Machine.ps1"
DoSomething -VirtualMachine "nwb-thisisamachine" -Attempts 500
This produced an error:
Machine name missing!
At C:\Users\something\Desktop\Dump\play\Manage-Machine.ps1:33 char:28
+ [string]$VirtualMachine=$(throw "Machine name missing!"),
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Machine name missing!:String) [], RuntimeException
+ FullyQualifiedErrorId : Machine name missing!
Which is clearly because the field is mandatory. Am I doing something wrong in how I'm calling the function in this case? Is there an alternative way to calling the function if the script it belongs to has mandatory parameters, because if I remove the validation for the parameter, it all works.
Would love some input,
Thank you!
[parameter(Mandatory = $true)]and remove=$(throw "Machine name missing!")Throwcan make for better messages though-NonInteractiveflag and any missing mandatory parameters will cause an error and a non-zero exit code will be returned.