PowerShellPracticeAndStyle icon indicating copy to clipboard operation
PowerShellPracticeAndStyle copied to clipboard

Dealing with Paths

Open Jaykul opened this issue 9 years ago • 1 comments
trafficstars

Given you're accepting a $Path parameter in your function...

I think there are 4 scenarios, which are the flip sides of two conditions:

Condition One: Does it need to already exist?
Condition Two: Do you care about the provider?
  1. You need the $path to exist, you don't care about the provider
  2. You don't care if the $path exists, you don't care about the provider
  3. You need the $path to exist, you need it to be a specific provider
  4. You don't care if it exists, you need it to be a specific provider

Have I missed any scenarios?

By far the hardest of these to deal with (I think) is when the path may not exist yet, and it has to be a specific provider. For instance, if you want to take a relative or absolute path to a file and pass it to $xml.Save($path)

If the path is relative, you must convert it to a full path, because [Environment]::CurrentDirectory might as well be randomized. Otherwise, you could probably leave it alone. But assuming it might be relative, and assuming your script might be called while $pwd is in a non-filesystem folder ... what do you do?

Does this work? Is there something simpler?

$PsCmdlet.SessionState.Path.PushCurrentLocation("fallback"); 
$PsCmdlet.SessionState.Path.SetLocation( $PsCmdlet.SessionState.Path.CurrentFileSystemLocation ); 
$Path = $PsCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path); 
$PsCmdlet.SessionState.Path.PopLocation("fallback");

Jaykul avatar Jul 19 '16 21:07 Jaykul

RE simpler - GetUnresolvedProviderPathFromPSPath() exists directly off of $PSCmdlet IIRC.

Also, don't forget about wildcard handling, which might necessitate a LiteralPath parameter. And how to make these parameters pipeline bound (via the alias PSPath). This should also cover recommend error handling practices for when path doesn't exist (and must) or the path is not a valid path, etc.

rkeithhill avatar Jul 19 '16 21:07 rkeithhill