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?
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.
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.
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.
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.
Use the command ... get-item blah -ErrorAction SilentlyContinue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With