Shepherdess
Shepherdess

Reputation: 651

Powershell - path's format is not supported when variables in the file name

I'm trying to add an XML declaration to multiple files in a directory. The code works for a single file with hard-coded name but when I want to run it for multiple files, I'm getting the following error:

"Exception calling "Save" with "1" argument(s): "The given path's format is not supported."

I'm using:

$FilePath = C:\test
$files = Get-ChildItem $FilePath\*.xml
foreach ($file in $files)
{
$xml = [xml](get-content $file)
$decl = $xml.CreateXmlDeclaration("1.0", "ucs-2", "yes")
$xml.InsertBefore($decl, $xml.DocumentElement)
$xml.save($FilePath$file)
}

I've been changing the last line to

$xml.save($FilePath+"\"+$file)
$xml.save("$FilePath\$file")

and other formats but still getting the same error.

Upvotes: 1

Views: 3287

Answers (2)

Chops
Chops

Reputation: 11

I have a similar issue and I was able to get what I needed by joining strings using the -join command to create a new var. In this case we'll call it $XMLCompatibleFileNames.

$FilePath = C:\test
$files = Get-ChildItem $FilePath\*.xml
foreach ($file in $files)
{
$xml = [xml](get-content $file)
$decl = $xml.CreateXmlDeclaration("1.0", "ucs-2", "yes")
$xml.InsertBefore($decl, $xml.DocumentElement)
# Join your vars as strings and add the wack (\) if not included in the directory var
# Test it with write-host $XMLCompatibleFileName
$XMLCompatibleFileName = -join ("$($FilePath)\","$($File)")
$xml.save($XMLCompatibleFileName)
}

Upvotes: 1

Bob007
Bob007

Reputation: 109

$xml.save("$file") ?

$FilePath = "C:\test"
$files = Get-ChildItem $FilePath\*.xml
foreach ($file in $files)
{
$xml = [xml](get-content $file)
$decl = $xml.CreateXmlDeclaration("1.0", "ucs-2", "yes")
$xml.InsertBefore($decl, $xml.DocumentElement)
$xml.save($file)
}

or

$FilePath = "C:\Scripts"
$files = Get-ChildItem $FilePath\*.xml
foreach ($file in $files)
{
$xml = [xml](get-content $file)
$decl = $xml.CreateXmlDeclaration("1.0", "ucs-2", "yes")
$xml.InsertBefore($decl, $xml.DocumentElement)
$xml.save($FilePath + $file.Name)
}

As $file is full:\path\of\file\plus\filename.xml you are trying to add full:\path to it.

$file or $Filepath + $File.Name will work.

Upvotes: 1

Related Questions