【问题标题】:Powershell - path's format is not supported when variables in the file namePowershell - 文件名中的变量时不支持路径格式
【发布时间】:2015-08-06 14:58:45
【问题描述】:

我正在尝试将 XML 声明添加到目录中的多个文件。该代码适用于具有硬编码名称的单个文件,但是当我想为多个文件运行它时,我收到以下错误:

“使用“1”参数调用“保存”的异常:“给定路径的 不支持格式。”

我正在使用:

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

我一直把最后一行改成

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

和其他格式,但仍然出现相同的错误。

【问题讨论】:

    标签: xml powershell


    【解决方案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)
    }
    

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

    由于 $file 已满:\path\of\file\plus\filename.xml 您正在尝试将 full:\path 添加到它。

    $file 或 $Filepath + $File.Name 将起作用。

    【讨论】:

    • 谢谢。我之前尝试过,但出现错误:“拒绝访问路径 'C:\abc.xml'。”所以看起来它需要完整路径才能保存在正确的目录中。 abc.xml 是 C: 中的文件,不知道为什么要提取它
    • 第二种解决方案有效,我只需要添加“\”。 $xml.save($FilePath + "\" + $file.Name) 。非常感谢!
    • 只是插话:记住 $file 是一个具有属性的对象,其中之一是“名称”。在循环内设置断点并查看 $file |获取成员
    【解决方案2】:

    我有一个类似的问题,我能够通过使用 -join 命令连接字符串来创建新的 var 来获得所需的内容。在这种情况下,我们将其称为 $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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 2011-11-13
      • 2012-04-21
      • 1970-01-01
      相关资源
      最近更新 更多