I was wondering how to edit a specific attribute in an XML file.
the attribute that I would like to edit looks like this:
<Data key="serial">912487015087068085841514</Data>
I would like the file to set the value to a random 24 digit number.
I was wondering how to edit a specific attribute in an XML file.
the attribute that I would like to edit looks like this:
<Data key="serial">912487015087068085841514</Data>
I would like the file to set the value to a random 24 digit number.
PowerShell is pretty good at handling XML data. I'm posting this to avert suggestions to use sed, jrepl.bat, or other text-manipulation tools. XML should be handled as a hierarchical object.
<# : batch portion
@echo off & setlocal
set "xmlfile=test.xml"
powershell -noprofile "iex (${%~f0} | out-string)"
goto :EOF
: end batch / begin PowerShell hybrid code #>
function rnd([int]$digits) {
$x = foreach ($i in 1..$digits) { get-random -min 0 -max 9 }
$x -join ''
}
[xml]$xml = gc $env:xmlfile
$xml.SelectSingleNode('//Data[@key="serial"]/text()').data = rnd 24
$xml.Save($env:xmlfile)
If you'd like, you can change the rnd()
function to generate 24 hexadecimal characters (0-9 and a-f) for even more randomness.
function rnd([int]$digits) {
$x = foreach ($i in 1..$digits) { (get-random -min 0 -max 16).toString('x') }
$x -join ''
}
... Or you can generate from every alphanumeric character for even more.
function rnd([int]$digits) {
$x = foreach ($i in 1..$digits) { [char](48..57 + 65..90 + 97..122 | get-random) }
$x -join ''
}
But the rnd()
function is somewhat re-inventing the wheel. You can generate plenty of randomness by using .NET's GUID
class.
$xml.SelectSingleNode('//Data[@key="serial"]/text()').data = [guid]::NewGuid()