EMP
EMP

Reputation: 61971

Check if an item exists without an error if it doesn't exist

I'd like to use PowerShell to check whether an IIS Web Application exists (or potentially some other kind of item). I can do this with Get-Item, but that reports an error if the item doesn't exist, which is misleading to the user running the script - it looks like something went wrong when actually everything is fine.

How do I do this without an error?

Upvotes: 37

Views: 42338

Answers (2)

Preet Sangha
Preet Sangha

Reputation: 65496

Use the command ... get-item blah -ErrorAction SilentlyContinue

alt text

Upvotes: 36

Roman Kuzmin
Roman Kuzmin

Reputation: 42033

The cmdlet Test-Path is specifically designed for this, it determines whether items of a path exist. It returns a Boolean value and does not generate an error.

The cmdlet Get-Item (and similar) can be used, too, but not directly. One way is already proposed: use -ErrorAction SilentlyContinue. It might be important to know that in fact it still generates an error; it just does not show it. Check the error collection $Error after the command, the error is there.


Just for information

There is a funny way to avoid this error (it also works with some other cmdlets like Get-Process that do not have a Test-Path alternative). Suppose we are about to check existence of an item "MyApp.exe" (or a process "MyProcess"). Then these commands return nothing on missing targets and at the same time they generate no errors:

Get-Item "[M]yApp.exe"
Get-Process "[M]yProcess"

These cmdlets do not generate errors for wildcard targets. And we use these funny wildcards that actually match single items.

Upvotes: 60

Related Questions