1

In Java I'm used to working with paths as semantic, platform-agnostic Path objects. If I have a directory dir and I want to find the filename bar.txt inside that directory, I'd use something like dir.resolve("bar.txt"), which would resolve foo.bar to the parent directory dir. I would not use dir.toString() + "\bar.txt"; this would be considered back practice, as it is error-prone and assumes a path separator \ (which might be / on Linux for example).

In my PowerShell script the user passes an $archive variable containing some foo.zip archive. I expand it to foo.zip.tmp like this:

$dir = $archive + '.tmp'
Expand-Archive -Path $archive -DestinationPath $dir

At this point I want to work with a file bar.txt inside that new directory—that is, $dir + '\bar.txt'. But what is the best-practices approach for resolving a known filename to some directory variable in PowerShell? I hope this is not the best we can do, for the reasons explained above:

$barFile = $dir + '\bar.txt'
Garret Wilson
  • 18,219
  • 30
  • 144
  • 272
  • 3
    `Join-Path $dir 'bar.txt'` – zett42 Dec 24 '22 at 16:34
  • Using [`Join-Path`](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/join-path) is good practice, but you can also take advantage of the fact that PowerShell accepts ``\`` and `/` _interchangeably_, on all supported platforms, so - when passing paths to _PowerShell_ commands - both `$dir + '/bar.txt'` and `$dir + '\bar.txt'` should work fine. – mklement0 Dec 24 '22 at 22:14
  • It would seem `Join-Path` works for simple filenames relative to a directory, so that answers this highly specific question. But is there no general `Resolve-Path` method (such as I get with Java `Path`) that would work correctly if the second argument were absolute? See my more general question https://stackoverflow.com/q/74908519 . – Garret Wilson Dec 26 '22 at 18:32

1 Answers1

0

I'm not too familiar with PowerShell, but a quick look at documentation, this might be a better practice to get rid of /:

Join-Path -Path "path" -ChildPath "childpath"

Outputs: path\childpath

Source: learn microsoft powershell

ukw
  • 166
  • 2
  • 14
  • 2
    That's great, thanks. It's verbose, but seems to do what I want. Turns out I can even use it with the wildcard character, for example to recompress files back into an archive: `Compress-Archive -Path (Join-Path $dir '*') $outputArchive`. – Garret Wilson Dec 24 '22 at 17:28