powershell 脚本不工作,但未显示任何错误。查找目录中的所有 .xml 文件,对某些文本进行替换,移动到不同的目录

powershell script isn't working, but shows no errors. Find all .xml files in a directory, do a replace on some text, move to different directory

Powershell 脚本有几次 b/c 漏掉了逗号之类的错误。现在看起来 运行 没有错误,但什么也没发生 - 文件没有移动,文本没有被替换。

仅供参考,我让替换程序自行运行 - 它扫描了所有 .XML 文件并将那个小字符串替换为较大的字符串。替换确实包含 XML 中需要的新行和空格,但我在此示例中对其进行了简化,因此更易于阅读。

一如既往,非常感谢所有帮助。

编辑:添加了解决方案。谢谢你,TheMadTechnician

$CurrFilePath = "C:\Folder\Path1"
$TransIncludePattern = "*.xml"
$ProcessFilePath = "C:\Folder\Path2"

try #Get-ChildItem -Path $CurrFilePath\* -Include $TransIncludePattern | Select-Object -First 1 | ForEach-Object  
    { 
    $CurrFileName = Get-childitem -Path $CurrFilePath\* -Include $TransIncludePattern;
    $CurrFileName | 
        Select-Object -ExpandProperty FullName | 
        ForEach-Object {
            Write-Host "Changing file $_";
            $content = (Get-Content $_);
            $newContent = $content | ForEach-Object {
                    
                    ($_-replace '</InitgPty>', '<Id> <OrgId> <Id>DAMNID</Id> </OrgId> </Id></InitgPty>'); 
      
      }
            $newContent | Set-Content $_; #or [IO.File]::WriteAllLines($_, $newContent) :)

            Write-Host "File Changed: $_";
        }
        
        Write-Host "Has DamnID";
        
        Move-Item -CurrFileName $file -Destination $ProcessFilePath;
        
        exit 0;
}
catch {
    Write-Error $_;
}
        

工作脚本:

$CurrFilePath = "C:\Folder\Path1"
$TransIncludePattern = "*.xml"
$ProcessFilePath = "C:\Folder\Path2"

try #Get-ChildItem -Path $CurrFilePath\* -Include $TransIncludePattern | Select-Object -First 1 | ForEach-Object  
    { 
    $CurrFileName = Get-childitem -Path $CurrFilePath\* -Include $TransIncludePattern;
    $CurrFileName | 
        Select-Object -ExpandProperty FullName | 
        ForEach-Object {
            
            $content = (Get-Content $_);
            $newContent = $content | ForEach-Object {
                    
                    ($_-replace '</InitgPty>', '<Id> <OrgId> <Id>DAMNID</Id> </OrgId> </Id></InitgPty>'); 
      
      }
            $NewContent = Set-Content -Path $_ -Value $newContent;

          
        }
        
        
        Move-Item -Path .\*.xml -Destination $ProcessFilePath;
        
        exit 0;
}
catch {
    Write-Error $_;
}
        





当您转到 Set-Content 时,您失去了 $_ 的上下文。 $newContent = Set-Content $_ 我假设 $_ 应该引用文件名,但此时它包含文件的修改内容。在该行上尝试 Set-Content -Path $_ -Value $newContent

然后当您移动文件时,参数 -CurrFileName 不是有效参数。而是使用 Move-Item -Path $_ -Destination $ProcessFilePath