views:

617

answers:

3

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.");
    }
}
A: 

Try the following

$a = gp "hklm:\HARDWARE\ACPI\DSDT\HP____\8510x\0001000" "00000000"
$a."00000000" | out-file 8610x.orig
JaredPar
Note: out-file will not keep the data in binary format. It will take the byte array and write each byte out as a display number.
Robert
Yes, Out-File is not a good choice. It is meant to write data to a file in the same way as it is displayed in the console.
JasonMArcher
+4  A: 
$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'
}
Robert
+10  A: 

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.

Keith Hill
+1 I didn't know about Set-Content. Nice!
Robert