1

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.

2 Answers 2

1

$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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I've tried that before and am getting an error: "Access to the path 'C:\abc.xml' is denied." so it seems like it needs the full path to save in the correct directory. abc.xml is the file in C: , not sure why it is being picked up
The second solution worked, I just needed to add "\". $xml.save($FilePath + "\" + $file.Name) . Thanks a lot!
Just to chime in on this: Remember that $file is an object with attributes, one of which is "name". Set a breakpoint inside the loop and look at $file | get-member
1

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.