想要使用PowerShell将不同的字符串分成多个部分的通用方法

问题描述 投票:0回答:1

我正在研究一种从注册表读取软件的UninstallStrings的方法。然后,我尝试执行这些字符串以卸载软件。

当我打印出包含字符串信息的变量时,它会正确打印整个字符串(带有参数),但是我无法运行这些字符串。此问题有多个部分。

某些安装字符串的格式如下

c:\file path\blah\app.exe /uninstall
"c:\file path\blah\app.exe" /uninstall
c:\file path\blah\app.exe --uninstall
'c:\file path\blah\app.exe' /uninstall

我想做的是找出能够以“通用”方式运行卸载程序的最佳方法。有没有办法有效地做到这一点?

我尝试以两种不同的方式执行字符串。

    & $uninstaller

    Start-Process -FilePath cmd.exe -ArgumentList '/c', $uninstaller -Wait 

他们似乎都不起作用。没有错误,但它们似乎没有运行,因为当我检查该应用程序时,它仍然已安装。

而且我尝试了几种分割文本的方法。


    $Uninstaller.split("/")[0]
    $Uninstaller.split("/",2)[1]
    $($Uninstaller) | Invoke-Expression
    $Uninstaller.Substring(0,$Uninstaller.lastIndexOf('.exe '))
    $Uninstaller.split('^(*?\.exe) *')

提前感谢!

string powershell split uninstall
1个回答
0
投票

想通了。也许有更好的方法可以这样做,但这似乎对我有用。

CLS

$Software = "OneDrive"
$Filter = "*" + $Software + "*"
$Program = $ProgUninstall = $FileUninstaller = $FileArg = $NULL

try 
{
    if (Test-Path -Path "HKLM:\SOFTWARE\WOW6432Node") 
    {
        $programs = Get-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" -ErrorAction Stop
    }

    $programs += Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" -ErrorAction Stop
    $programs += Get-ItemProperty -Path "Registry::\HKEY_USERS\*\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" -ErrorAction SilentlyContinue
} 
catch 
{
    Write-Error $_
    break
}

foreach($Program in $Programs)
{
    $ProgDisplayName = $Program.DisplayName
    $ProgUninstall = $Program.UninstallString

    if($ProgDisplayName -like $Filter)
    {
        if($ProgUninstall -like "msiexec*")
        {
            $FileUninstaller = $ProgUninstall.split(" ")[0]
            $FileArg = ($($ProgUninstall).split(" ",2)[1])
        }
        else
        {
            if(($ProgUninstall -like '"*"*') -or ($ProgUninstall -like "'*'*"))
            {
                #String has quotes, don't need to do anything

            }
            else
            {
                if($NULL -ne $ProgUninstall)
                {
                    #String doesn't have quotes so we should add them
                    $ProgUninstall = '"' + ($ProgUninstall.Replace('.exe','.exe"'))                    
                }
            }

            #Let's grab the uninstaller and arguments
            $FileUninstaller = $ProgUninstall.split('"')[1]
            $FileArg = $ProgUninstall.split('"')[-1]
        }

        #Debug
        #$FileUninstaller
        #$FileArg

        #Run the Uninstaller
        Start-Process $FileUninstaller -ArgumentList $FileArg -wait -ErrorAction SilentlyContinue
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.