有没有办法将此Powershell脚本转换为C#

时间:2019-05-09 03:15:30

标签: c# powershell

我想将此代码转换为C#。

Function CheckFileInstalled {

param (
    [string]$pathProg     = "C:\Program Files\WinRAR\WinRAR.exe",
    [string]$nameProg     = "Winrar"
)

$testFileProg = Test-Path $pathProg

$x86 = ((Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall") |
    Where-Object { $_.GetValue( "DisplayName" ) -like "*$nameProg*" } ).Length -gt 0;

$x64 = ((Get-ChildItem "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall") |
    Where-Object { $_.GetValue( "DisplayName" ) -like "*$nameProg*" } ).Length -gt 0;


return ( $testFileProg -and ($x86 -or $x64) )

}

if( CheckFileInstalled ) {
    Write-Host "Program installed." 
}
else {
    Write-Host "Failed to install."
}

1 个答案:

答案 0 :(得分:2)

尝试一下,但是您可能需要管理员权限才能注册

public bool CheckFileInstalled(string pathProg, string nameProg)
{
    bool pathExist = Directory.Exists(pathProg);
    bool x86 = false;
    bool x64 = false;

    RegistryKey x86Key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall", true);
    if(x86Key.GetValueNames().Contains(nameProg)) x86 = true;

    RegistryKey x64Key = Registry.LocalMachine.OpenSubKey(@"Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall", true);
    if(x64Key.GetValueNames().Contains(nameProg)) x64 = true;

    return (pathExist && (x86 || x64));
}