0

I have a powershell-script that I want to execute through the cammand-line. For this I need to input paths to xml files. Its better to show the problem. Error: File not Found

I have all my files in the same directory C:\Users\fynne\test (reason for that are the users I'm writing this script for) but somehow the test directory is skipped while loading the xml (C:\Users\fynne\01-38-029.xml not found). I have no idea why this happens.
This is how I load the xml.

$PatientA = $args[0]
$PatientB = $args[1]
$XmlA = New-Object System.XML.XMLDocument
$XmlA.Load($PatientA)
$XmlB = New-Object System.XML.XMLDocument
$XmlB.Load($PatientB)

Does somebody knows why and has a fix for it? I know that I can fix it by using some string manipulation and $pwd however I rather prefer not to.

Thx

Sinth
  • 3
  • 1
  • 2
    `$XmlA.Load((Resolve-Path $PatientA))` – Mathias R. Jessen Nov 19 '21 at 14:59
  • 1
    @MathiasR.Jessen IMO `Convert-Path` is the better choice as it also converts PSPath to native provider path. Compare `Resolve-Path ((Get-Item .).PSPath)` vs. `Convert-Path ((Get-Item .).PSPath)`, the former outputs a path that's invalid input for .NET API. Also we should pass `-LiteralPath` or otherwise be prepared to possibly get an array of paths. – zett42 Nov 19 '21 at 15:09
  • @zett42 Good point, included `Convert-Path` in my answer below – Mathias R. Jessen Nov 19 '21 at 15:16
  • 1
    Does this answer your question? [How to access a PSDrive from System.IO.File calls?](https://stackoverflow.com/questions/58721850/how-to-access-a-psdrive-from-system-io-file-calls) -- The question is somewhat different, but the answer also applies to the current question. – zett42 Nov 19 '21 at 15:20
  • Ah now I understand it. Thanks yall for your help :) – Sinth Nov 24 '21 at 11:19

1 Answers1

0

PowerShell will attempt to resolve non-absolute paths relative to the current provider location - but .NET methods (like XmlDocument.Load()) will resolve them relative to the working directory of the current process instead.

You can manually convert a relative path to an absolute one with Convert-Path:

$PatientA,$PatientB = $args[0..1] |Convert-Path

$XmlA = New-Object System.XML.XMLDocument
$XmlA.Load($PatientA)
$XmlB = New-Object System.XML.XMLDocument
$XmlB.Load($PatientB)

If you want to attempt further validation of the path, you can also use Resolve-Path which includes provider metadata:

$PatientA = $args[0] |Resolve-Path
if($PatientA.Provider.Name -ne 'FileSystem'){
  throw 'First path was not a file system path...'
  return
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206