Allan Xu
Allan Xu

Reputation: 9358

How to check then define a function if is not defined in other part of the code or other dot-sourced scripts

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?

Upvotes: 2

Views: 107

Answers (1)

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10799

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.

A System.Management.Automation.CommandNotFoundException (which is the ‘parent’ type of an ObjectNotFound) 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 {...}.

Upvotes: 3

Related Questions