Cheeso
Cheeso

Reputation: 192627

Can I do this in powershell? Read the Registry, write out binary contents to file

This is the C# code. Can you help me translate this to powershell?

private static void Main(string[] args)
{
    byte[] buffer = (byte[]) Registry.LocalMachine.OpenSubKey(@"HARDWARE\ACPI\DSDT\HP____\8510x\00010000").GetValue("00000000");
    if (File.Exists("8510x.orig"))
    {
        Console.WriteLine("File 8510x.orig already exists.");
    }
    else
    {
        using (FileStream stream = new FileStream("8510x.orig", FileMode.CreateNew))
        {
            stream.Write(buffer, 0, buffer.Length);
            stream.Flush();
            stream.Close();
        }
        Console.WriteLine("Wrote 8510x.orig.");
    }
}

Upvotes: 3

Views: 2192

Answers (3)

JaredPar
JaredPar

Reputation: 755397

Try the following

$a = gp "hklm:\HARDWARE\ACPI\DSDT\HP____\8510x\0001000" "00000000"
$a."00000000" | out-file 8610x.orig

Upvotes: -1

Keith Hill
Keith Hill

Reputation: 202032

You don't want to use Out-File because it outputs as a string and uses unicode to boot. The following works based on a similar registry entry:

$b = Get-ItemProperty HKLM:\HARDWARE\ACPI\DSDT\A7546\A7546011\00000011 00000000
$b.'00000000' | Set-Content foo.txt -enc byte

Note that Set-Content is useful when you want more direct control over what gets written to file especially if you want to write raw bytes.

Upvotes: 10

Robert Groves
Robert Groves

Reputation: 7748

$a = gp 'HKLM:\HARDWARE\ACPI\DSDT\HP____\8510x\0001000' '00000000'

if ( test-path 8510x.orig )
{
   echo 'File 8510x.orig already exists.'
}
else
{
   [System.IO.File]::WriteAllBytes("8510x.orig",$a."00000000")
   echo 'Wrote 8510x.orig'
}

I'm leaving my previous answer (above) as an example of accessing .NET objects from PowerShell; but after seeing keith-hill's answer I had to revise mine to use set-content as well:

$a = gp HKLM:\HARDWARE\ACPI\DSDT\HP____\8510x\0001000 00000000

if ( test-path 8510x.orig )
{
   echo 'File 8510x.orig already exists.'
}
else
{
   $a.'00000000' | Set-Content 8510x.orig -enc byte 
   echo 'Wrote 8510x.orig'
}

Upvotes: 4

Related Questions