I have this code in powershell which works perfectly and now I am trying to rewrite it in c#.
$admin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
$basePath = “HKLM:SoftwarePoliciesMicrosoftWindowsPowerShellTranscription”
if (test-path $basePath){$vt = get-itemproperty $basepath |foreach-object {$_.EnableTranscripting}
if ($vt -eq 1 -and $admin -eq $true){Remove-Item $basepath -Force -Recurse}elseif($vt -eq 1 -and $admin -eq $false){exit}};
Here is the c# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Security.Principal;
using Microsoft.Win32;
public class Program
{
static bool IsHighIntegrity()
{
// returns true if the current process is running with adminstrative privs in a high integrity context
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
static string GetReg()
{
string defaultkey = "";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Policies\Microsoft\Windows\Powershell\Transcription"))
{
if (key != null)
{
Object o = key.GetValue("");
if (o != null)
{
defaultkey = o.ToString();
}
}
} }
static void Main(){
if (IsHighIntegrity())
{
string RegPath = "Software\Policies\Microsoft\Windows\Powershell\Transcription";
string RegPath1 = "SOFTWARE\WOW6432Node\Policies\Microsoft\Windows\PowerShell\Transcription";
if (defaultkey == 1){
try
{
Console.Write("[*] Attempting to delete registry tree: {0}... ", RegPath);
Registry.LocalMachine.DeleteSubKeyTree(RegPath);
Console.Write("[*] Attempting to delete registry tree: {0}... ", RegPath1);
Registry.LocalMachine.DeleteSubKeyTree(RegPath1);
Console.WriteLine("Done.");
}
catch (Exception ex)
{
Console.WriteLine("FAILURE.");
Console.WriteLine("Reason:");
Console.WriteLine(ex);
}
}
Console.WriteLine("[*] All Done.");
}
else
{
if (defaultkey == 1){
Environment.Exit(1);
}
}
}
}
I get the following errors while trying to compile:
test.cs(22,21): error CS0161: 'Program.GetReg()': not all code paths return a value
test.cs(47,6): error CS0103: The name 'defaultkey' does not exist in the current context
test.cs(69,6): error CS0103: The name 'defaultkey' does not exist in the current context
The errors are pretty verbose but after reading through literature such as:https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.registry.getvalue?redirectedfrom=MSDN&view=dotnet-plat-ext-5.0#Microsoft_Win32_Registry_GetValue_System_String_System_String_System_Object_
and stack overflow questions, I cannot figure out why I am not receiving a value.
All help appreciated
question from:
https://stackoverflow.com/questions/65909562/errors-while-translating-registry-checks-from-powershel-to-c-sharp 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…