Powershell ScriptBlock,带有'cmd / c'和'$ using'不一致的行为

时间:2017-08-04 17:39:13

标签: powershell

我的代码:

Clear-Host

$installed_softwares = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall  |
    Get-ItemProperty | Where-Object {$_.DisplayName -like "*" } | Select-Object -Property *

$csv = Import-Csv('C:\<...>\softwares.csv')

$softwares_to_remove = @()
foreach ($line in $csv) {
    $info = New-Object System.Object
    $info | Add-Member -type NoteProperty -name Name -value $line.Software
    $info | Add-Member -type NoteProperty -name Version -value $line.Version
    $info | Add-Member -type NoteProperty -name Publisher -value $line.Publisher
    $softwares_to_remove += $info
}

ForEach ($installed_software in $installed_softwares) {
    ForEach ($software_to_remove in $softwares_to_remove) {
        If ($software_to_remove.Name -eq $installed_software.DisplayName -And $software_to_remove.Version -eq $installed_software.DisplayVersion -And $software_to_remove.Publisher -eq $installed_software.Publisher) {
            Write-Host 'Tring to remove:' $installed_software.DisplayName, $installed_software.DisplayVersion, $installed_software.Publisher, $installed_software.UninstallString

            If (($installed_software.UninstallString).ToLower() -match '^msiexec') {
                Write-Host 'Skipped: ' $installed_software.DisplayName
                Write-Host ''
            } Else {
                # Working: .\<SOFTWARE>\uninst.exe /S
                $full_path = $installed_software.UninstallString
                if ($full_path -like '* *') {
                    if ($full_path -notlike '"*') {
                        $full_path = '"' + $full_path + '"'
                    }
                }

                write-host $full_path, $full_path.GetType()

                Invoke-Command -ComputerName localhost -ScriptBlock { cmd /c $using:full_path /S}
                Write-Host 'Removed:' $installed_software.DisplayName
                Write-Host ''
            }
        }
    }
}

输出:

Tring to remove: BitComet 1.36 1.36 CometNetwork C:\Program Files (x86)\BitComet\uninst.exe
"C:\Program Files (x86)\BitComet\uninst.exe" System.String
Removed: BitComet 1.36

Tring to remove: qBittorrent 3.3.14 3.3.14 The qBittorrent project "C:\Program Files (x86)\qBittorrent\uninst.exe"
"C:\Program Files (x86)\qBittorrent\uninst.exe" System.String
Removed: qBittorrent 3.3.14

Tring to remove: Steam 2.10.91.91 Valve Corporation C:\Program Files (x86)\Steam\uninstall.exe
"C:\Program Files (x86)\Steam\uninstall.exe" System.String
Removed: Steam

Tring to remove: Viber 6.8.6.5 Viber Media Inc. MsiExec.exe /I{05247C1B-0AD7-43B0-B6F9-D29B376ADC9A}
Skipped: Viber

目前,我通过Powershell ISE本地运行它作为本地管理员启动,但想法是在完成后远程运行它。有时在我运行此脚本多次后卸载的唯一软件是qBittorrent,但它没有完美地执行它,因为它将控件面板中的“添加/删除程序”中的条目保留,如果它是手册卸载这不会发生。

为什么此代码有这种不一致的行为?如何解决?

0 个答案:

没有答案