Powershell测试2语句是否为真函数

时间:2019-02-18 05:52:36

标签: function powershell if-statement

Clear-Host
Function First {
    $File1 = "C:\Program Files\WinRAR\WinRAR.exe"
    $TestFile1 = Test-Path $File1
    If ($TestFile1 -eq $True) {Write-Host "Winrar is installed." -F Green -B Black}
    Else {Write-Host "Winrar is not installed." -F Red -B Black}
}
First

Function Second {
    $winrar = Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*
    $winrarCheck = "Winrar"
    $winrarFinal = $winrar | Where {$_.DisplayName -match $winrarCheck} | Format-Table -Property DisplayName,DisplayVersion

    $winrarFinal
    If ($winrarFinal) {Write-Host "Winrar registry check installed." -F Green -B Black}
    Else {Write-Host "Winrar registry check failed." -F Red -B Black}
    }
Second

是否可以使用If语句检查两个函数?我想检查一下这两个函数是否都正确, Write-Host "Program installed." Else Write-Host "Failed to install".

1 个答案:

答案 0 :(得分:2)

我们在这里:

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."
}