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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)