-relative
With the option -relative
specified, resolve-path
returns a list of relative paths (relative to the current directory, that is):
resolve-path ../../*.txt -relative
The returned data type is not a
PathInfo
object anymore, but a
string.
Combining -relative with get-childItem
The following simple
pipeline combines
get-childItem
and
resolve-path -relative
to return a list of all relative path names of
.sql
files beneath the current directory:
get-childItem -recurse -filter *.sql | select-object { resolve-path $_.fullName -relative }
Get relative path between an arbitrary directory and file/directory
Files must exist
resolve-path
requires real (existing) files to operate. It's not possible (as far as I can see) to use resolve-path -relative
to find a relative path to a hypothetical file that does not yet exist, for example, in order to create its directory:
PS C:\> resolve-path $home\foo\bar\baz.txt
resolve-path : Cannot find path 'C:\Users\Rene\foo\bar\baz.txt' because it does not exist.
The
DevHawk Blog alternatively suggests to set the
-errorAction
parameter to
silentlyContinue
and, in case the file does not exist, use an
error variable to get the path for the inexisting file:
function resolve-always($path) {
$resolved = resolve-path $path -errorAction silentlyContinue -errorVariable err
if (! $resolved) {
return $err[0].targetObject
}
return $resolved
}