Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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?

like image 589
EMP Avatar asked Dec 06 '10 00:12

EMP


People also ask

How do I check if an item exists in Sitecore?

Navigate to the item in the Media Library or Extras folder. Click View in the Sitecore ribbon and check the Hidden Items checkbox if not already checked.

What does Test-path do?

The Test-Path cmdlet determines whether all elements of the path exist. It returns $True if all elements exist and $False if any are missing. It can also tell whether the path syntax is valid and whether the path leads to a container or a terminal or leaf element.

How to validate path in PowerShell?

Validate the path exists We can do this relatively simply using Test-Path. You can also easily reverse this to validate that a file or folder does not exist. We can use the PathType parameter of the Test-Path cmdlet to verify the path is either a leaf (file) or container (folder) type.


2 Answers

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.

like image 71
Roman Kuzmin Avatar answered Oct 02 '22 14:10

Roman Kuzmin


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

alt text

like image 43
Preet Sangha Avatar answered Oct 02 '22 15:10

Preet Sangha