The goal of this program is to: 1) Rename the file to include the PONum from inside the file 2) Pretty-Print (format) the XML inside the file 3) Preserve (keep) the original date/time of the file
cls

function Format-XMLDoc ([xml] $xml, $indent=3) 
{ 
    $StringWriter = New-Object System.IO.StringWriter 
    $XmlWriter = New-Object System.XMl.XmlTextWriter $StringWriter 
    $xmlWriter.Formatting = “indented” 
    $xmlWriter.Indentation = $Indent 
    $xml.WriteContentTo($XmlWriter) 
    $XmlWriter.Flush() 
    $StringWriter.Flush() 
    Write-Output $StringWriter.ToString() 
}


function Format-XML ($xmlString, $indent=3) 
{ 
    [xml]$xml.LoadXml($xmlString) 
    $StringWriter = New-Object System.IO.StringWriter 
    $XmlWriter = New-Object System.XMl.XmlTextWriter $StringWriter 
    $xmlWriter.Formatting = “indented” 
    $xmlWriter.Indentation = $Indent 
    $xml.WriteContentTo($XmlWriter) 
    $XmlWriter.Flush() 
    $StringWriter.Flush() 
    Write-Output $StringWriter.ToString() 
}

$folderName = "c:\BizTalk\Messaging\Archive\SentToDropShipOrchBackup"
$files = Get-ChildItem $folderName -Filter "Test*.xml" -File  | Sort-Object LastWriteTime -Descending

$maxFiles = 1   #used to test with a small number of files first 
$fileCount = 0 


foreach ($file in $files) 
{
     $fileCount = $fileCount + 1 
     if ($fileCount -gt $maxFiles) 
        {
          exit 
        }
     Write-Host $fileCount $file.Name 
     Write-Host "Creation    Time: $($file.CreationTime)"
     Write-Host "Last Write  Time: $($file.LastWriteTime)"
     Write-Host "Last Access Time: $($file.LastAccessTime)"

     $origCreationTime  =  $file.CreationTime
     $origLastWriteTime =  $file.LastWriteTime

     $fileContents = [IO.File]::ReadAllText($file.FullName)
     [xml]$xml.LoadXml($fileContents)  #load into XmlDoc 


     $fileContentsFormatted = Format-XMLDoc $fileContents -indent 4
     Write-Host $fileContentsFormatted
     [IO.File]::WriteAllText($file.FullName, $fileContentsFormatted)

     $PONum = $xml.ShipDocDetails.ShipDocDetails_Child1.rcPONumber_d
     $PONum=$PONum.Replace('"','');
     Write "PONum=$PONum" 

     $newGuid = [guid]::NewGuid()
     $newFileName = "ShipDoc_PONum_${PONum}_$newGuid.xml"
     Write-Host "NewName=$newFileName"

     Rename-Item $file.FullName $newFileName 
     (Get-ChildItem "${folderName}\${newFileName}").CreationTime = $origCreationTime
     (Get-ChildItem "${folderName}\${newFileName}").LastWriteTime = $origLastWriteTime

}

Goal was to …

Filed under: PowershellUncategorized