I am building a PowerShell script that might run or called in variety of different setup.
I need to define a function (say f
) if it is not defined anywhere else.
How to check then define a function if is not defined in other part of the code or other dot-sourced scripts?
CodePudding user response:
Get-Command -Name f -ErrorAction Stop
will throw an ObjectNotFound
exception if there is no cmdlet, function, or “operable program” (executable file) f
. You can use this in a try {...} catch {...}
construct to decide whether you need to define it - but be careful about scope rules.
Per the discussion in the comments, a System.Management.Automation.CommandNotFoundException
is not normally a terminating error, so you need the -ErrorAction Stop
to force it to become a terminating error that can be handled in the try {...} catch {...}
.