Knewmania
Knewmania

Reputation: 13

Powershell, Importing Registry Values from XML

This is my first post and I am somewhat new to PowerShell, so apologies for any posting issues.

I'm having some issues trying to import registry values from a formatted XML file. I can read in the content of the XML, and use foreach to loop through the XML code but I am stuck trying to build the New-ItemProperty commands. Here is the XML example:

<?xml version="1.0" encoding="utf-8" ?>
<REGUPDATES>
<SASR>
    <Reg>
        <Key>HKLM:\Some\Key\Path\000\111\22222</Key>
        <Name>Something.exe</Name>
        <Type>DWORD</Type>
        <Value>00000001</Value>
    </Reg>
    <Reg>
        <Key>HKLM:\Some\Key\Path\333\444\55555</Key>
        <Name>Something.exe</Name>
        <Type>DWORD</Type>
        <Value>00000002</Value>
    </Reg>
</SASR>
</REGUPDATES>

And here is the PowerShell code example:

[xml]$RegUpdates = Get-Content C:\Temp\RegUpdates.xml 
$SASRReg = $RegUpdates.REGUPDATES.SASR.Reg
$SASRKey = $RegUpdates.Regupdates.SASR.Reg.Key
$SASRName = $RegUpdates.Regupdates.SASR.Reg.Name 
$SASRType = $RegUpdates.Regupdates.SASR.Reg.Type 
$SASRValue = $RegUpdates.Regupdates.SASR.Reg.Value 
foreach ($IAVA in ($SASRReg))
{
New-ItemProperty -Path ([string]$SASRKey) -Name ([string]$SASRName) -     
PropertyType ([string]$SASRType) -Value ([string]$SASRValue)

What appears to happen is that the Registry key values (as well as the other variables) are being strung together. Here is the error that I see:

New-ItemProperty : Cannot find path 'HKLM:\Some\Key\Path\000\111\22222 
HKLM:\Some\Key\Path\333\444\55555' because it does not exist.

Thanks in advance for any assistance!

Upvotes: 1

Views: 1937

Answers (1)

Maximilian Burszley
Maximilian Burszley

Reputation: 19684

You're going to need a loop to handle the array:

$xml = [xml](Get-Content -Path myfile.xml)

foreach ($update in $xml.REGUPDATES.SASR.REG) {
    $propArgs = @{
        Path         = $update.Key
        Name         = $update.Name
        Value        = $update.Value
        PropertyType = $update.Type
        Force        = $true
    }
    New-ItemProperty @propArgs
}

All the xml elements are already seen as strings so you don't need to cast them.

Upvotes: 1

Related Questions