forge

Changing an Attribute for an XML file with PowerShell

In my little FCI program I output an attribute called author from Word documents – and I wanted to import the FCI data into SharePoint but Author is the internal field name for the creator of a file. SharePoint expects this to be a login name – but out of Word I got a friendly name. So I needed to convert this property to a different name. The first step was getting some XSLT to do this so I came up with:

<?xml version=’1.0′ ?>
<xsl:stylesheet version=”1.0″ xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”>
<xsl:output method=”xml” version=”1.0″ encoding=”UTF-8″ indent=”yes”/>
<xsl:template match=”/” >
<xsl:apply-templates />
</xsl:template>
<xsl:template match=”/Files/File/Properties/Property/@Name[.=’Author’]” >
<xsl:attribute name=”Name”>DocumentAuthor</xsl:attribute>
</xsl:template>
<xsl:template match=”@*|node()”>
<xsl:copy>
<xsl:apply-templates select=”@*|node()”/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

Help Your SharePoint User

This worked pretty well but I wanted to run it from PowerShell so how could I do that? Well first I’m lazy so I wanted the Convert-Xml commandlet from the PowerShell Community Extensions. With that I wasn’t quite done. I still needed to process all of my metadata files – and I wanted to refer to my XSLT file relative to the script. So I came up with the following which processes all ~~metadata.xml files, creates ~~spmetadata.xml files, deletes the ~~metadata.xml and then renames all of the ~~spmetadata.xml to ~~metadata.xml.

Import-Module pscx
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
$scriptLocation = Get-ScriptDirectory
$xsltLocation = Join-Path $scriptLocation “authortransform.xsl”
$files = dir -Recurse -Include “~~metadata.xml”
foreach ($file in $files)
{
$outputPath = Join-Path $file.Directory.FullName “~~spmetadata.xml”
Convert-Xml -path $file.FullName -XsltPath $xsltLocation > $outputPath
}
dir -include “~~metadata.xml” -recurse | remove-item
dir -include “~~spmetadata.xml” -recurse | %{ $newName = join-path $_.Directory.FullName “~~metadata.xml”; move-item $_.FullName $newName }

It took me way to long to put these pieces together but once I did they seem to work pretty well.

1 reply
  1. Huongtan
    Huongtan says:

    Excellent. Thanks for the link I’ll check it out.Now that I’ve checked it out, I have a copule of comments. First, the article was posted more than four years ago. Even though the article is loosing its relevance, I agree with several points in his post. Personally, I don’t see hAtom as a way to replace RSS. I see it as an alternative. And, if it’s an alternative, it should have some distinguishing features. Featured content and visual metadata would be two that I think would fit well.

Comments are closed.