【问题标题】:How to check if a program is installed and install it if it is not?如何检查程序是否安装,如果没有安装?
【发布时间】:2015-10-21 03:45:06
【问题描述】:

由于完整性检查,我宁愿不使用 WMI。

这是我没有的:

$tempdir = Get-Location
$tempdir = $tempdir.tostring()

$reg32 = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
$reg64 = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"

if((Get-ItemProperty $reg32 | Select-Object DisplayName | Where-Object { $_.DisplayName -Like '*Microsoft Interop Forms*' } -eq $null) -Or (Get-ItemProperty $reg64 | Select-Object DisplayName | Where-Object { $_.DisplayName -Like '*Microsoft Interop Forms*' } -eq $null))
        {
        (Start-Process -FilePath $tempdir"\microsoft.interopformsredist.msi" -ArgumentList "-qb" -Wait -Passthru).ExitCode
        }

它总是返回 false。如果我将它切换到-ne $null,它总是返回true,所以我知道它正在检测$null 输出,尽管我相信(但可能是错误的),Get-ItemProperty 返回的结果应该算作除$null.

【问题讨论】:

  • 你看过 Chocolatey chocolatey.org 吗?包装很容易制作,所有繁重的工作都为您完成。

标签: powershell if-statement installation powershell-4.0


【解决方案1】:
$tempdir = Get-Location
$tempdir = $tempdir.tostring()
$appToMatch = '*Microsoft Interop Forms*'
$msiFile = $tempdir+"\microsoft.interopformsredist.msi"
$msiArgs = "-qb"

function Get-InstalledApps
{
    if ([IntPtr]::Size -eq 4) {
        $regpath = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
    }
    else {
        $regpath = @(
            'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
            'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
        )
    }
    Get-ItemProperty $regpath | .{process{if($_.DisplayName -and $_.UninstallString) { $_ } }} | Select DisplayName, Publisher, InstallDate, DisplayVersion, UninstallString |Sort DisplayName
}

$result = Get-InstalledApps | where {$_.DisplayName -like $appToMatch}

If ($result -eq $null) {
    (Start-Process -FilePath $msiFile -ArgumentList $msiArgs -Wait -Passthru).ExitCode
}

【讨论】:

  • 不客气。那你能把它标记为答案吗?(它是向下箭头下的勾号)。
  • 我发现这非常有用,您介意解释一下代码:If ([IntPtr]::Size -eq 4) 正在检查什么吗?谢谢!
  • @Bajan 这是一种确定操作系统架构的方法。 [IntPtr] 属性的值在 32 位进程中为 4,在 64 位进程中为 8。
  • @ChrisVermeijlen; $msiArgs 只是一个变量,用于存储您要传递给 MSI 的参数,在上面的示例中,我们只是传递“-qb”。您可以存储任何其他 MSI 参数,例如“/norestart ALLUSERS=2”等。“-wait -Passthru”是 Start-Process cmdlet 的参数:docs.microsoft.com/en-us/powershell/module/…
  • @Tom Padilla - 是的,如果脚本是独立的,则不需要它,但 OP 在其原始代码中包含它以输出 ExitCode。
猜你喜欢
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-06
  • 2012-09-30
相关资源
最近更新 更多