Delete a file if it exists
If
remove-item
is used to delete a file that does not exist,
PowerShell answers with a
Cannot find path … because it does not exist error message.
In order to suppress this error message,
test-path
can be used to determine if a file exists. Combined with an
if
statement, this results in something like:
if (test-path foo.txt) {
remove-item foo.txt
}
Of course, even easier is to ignore the potential error message with the -errorAction
option:
remove-item foo.txt -errorAction ignore
Delete directories and subdirectories
In order to delete a directory with its subdirectories, both, the -recurse
and the -force
option need to be specified:
remove-item subDir -force -recurse
Without -force
, the cmdLet write the error message Directory … cannot be removed because it is not empty.
Deleting multiple items / A positional parameter cannot be found that accepts argument …
When multiple items need to be deleted, their names need to separated by a comma.
This idiosyncrasy might take some getting used to for someone used to the
cmd.exe
del
or Unix
rm
command.
The reason for this speciality it that
remove-item
expects an
array for the
path
parameter.
The following command deletes the files foo.txt
, bar.txt
and baz.txt
:
PS C:\users\rene\> remove-item foo.txt, bar.txt, baz.txt