Trinition
Trinition

Reputation: 1173

PowerShell load XML from remote server PathInfo; Can't save

I had a small script to manipulate some XML. The idea was simple:

  1. Load the XML via Get-Content and [xml]
  2. Manipulate the in-memory XmlDocument
  3. Save the XML

The script started out something like this:

$fileName = Resolve-Path (Join-Path $targetDir $xmlFile.FileName)
[xml]$xdoc = Get-Content $fileName
...
$xdoc.Save($fileName);

However, Save(...) was failing with "The given path's format is not supported". Some diagnostics I added revealed the path looked like this:

Microsoft.PowerShell.Core\FileSystem::\\remoteserver\sharedfolder\test.xml

As I understand it, that is the PowerShell variant of a path... actually a PathInfo (or the .ToString() output of a PathInfo).

When I was using a local path, Save(...) worked fine. It only breaks for a remote path.

It's not a problem for loading the XML, because we're using a native PowerShell cmdlet, Get-Context, that understands PowerShell paths. But when Save(...) is called, we're really invoking the .NET method on the XmlDocument class, and it doesn't understand PowerShell paths and throws an exception.

Is there no succinct, symmetrical, PowerShell means to write an XML file?

Upvotes: 0

Views: 753

Answers (1)

Frode F.
Frode F.

Reputation: 54971

Resolve-Path returns a PathInfo-object, but the Save() method expects a string-type. When you're using the PathInfo-object as an input for Save(), it converts the object to a string. As you've already figured out, the toString() of a PathInfo returns the full "PowerShell-path" including PSProvider details, which is not compatible for "normal" .Net methods.

You could use the ProviderPath-property that PathInfo provides to get a "normal" path.

As an alternative, you could rewrite your code to use Get-Item to get the more commonly used FileInfo-object which has FullName-property.

Sample using Resolve-Path:

$fileName = Resolve-Path (Join-Path $targetDir $xmlFile.FileName)
[xml]$xdoc = Get-Content $fileName
...
$xdoc.Save($fileName.ProviderPath);

Sample using Get-Item:

$file = Get-Item (Join-Path $targetDir $xmlFile.FileName)
[xml]$xdoc = Get-Content $file
...
$xdoc.Save($file.FullName);

Upvotes: 2

Related Questions