p whelan
p whelan

Reputation: 29

Powershell to remove particular text from a file

Im not really sure how best to approach this. I want to replace text in xml.rels files.

They contain xml data but dont seem to like being opened with $xml=New-Object XML

I want to remove all path information in the Target tag.

A file example is ...

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath" Target="/Finance/Audit/Mgt%20Accts%202020/MGT%20ACCTS%20-%20Copy2/Mgt%20Accts%20MAR%2020.xlsx" TargetMode="External"/></Relationships>

So in thie case I wish the file to become...

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath" Target="Mgt%20Accts%20MAR%2020.xlsx" TargetMode="External"/></Relationships>

Now the Target could contain any path so I would need to find the last "/" in Target and just keep the text after that.

Thanks for any help at all. P

Upvotes: 0

Views: 64

Answers (1)

Theo
Theo

Reputation: 61148

You can do this by loading the XML file(s), loop through the elements and then change the Target attribute using the SetAttribute() method:

$sourceFolder = "Y:\Finance\Audit\Mgt Accts 2020\MGT ACCTS - Copy3\Mgt Accts APR 20 unzipped\xl\externalLinks_rels"

# PowerShell versions below 3.0 need to use:
# Get-ChildItem -Path $sourceFolder -Filter '*.xml' | Where-Object { !$_.PSIsContainer } | Foreach-Object {

Get-ChildItem -Path $sourceFolder -Filter '*.xml' -File | Foreach-Object {
    # load the xml file
    [xml]$xml = Get-Content $_.FullName -Raw

    # loop through the <RelationShip> elements and change the Target attribute
    foreach ($relationNode in $xml.Relationships.Relationship) {
        # or use $newTarget = Split-Path -Path $relationNode.Target -Leaf
        $newTarget = [System.IO.Path]::GetFileName($relationNode.Target)
        $relationNode.SetAttribute("Target", $newTarget)
    }
    $xml.Save($_.FullName)
}

Upvotes: 1

Related Questions