Encontre dinamicamente o Chrome na máquina Windows do usuário final

Encontre dinamicamente o Chrome na máquina Windows do usuário final

Então, procurei em todos os lugares que pude pensar sobre isso e não consigo descobrir. Espero que a resposta seja muito simples. Aqui está a situação:

Estou criando um link de atalho para um usuário final. Vamos chamá-lo de "shortcut.lnk". Podemos presumir que eles têm o Chrome instalado e que “myFolder” está em sua área de trabalho. A chave é que este aplicativo precisa ser aberto no Chrome, não no navegador padrão do usuário. Atualmente, tenho o seguinte como "Destino" do atalho.lnk:

%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe --app=%USERPROFILE%\Desktop\myFolder\path\to\app.html

Isso funciona nas 3 máquinas em que testei. No entanto, percebi pela pesquisa que o Chrome às vezes é instalado em AppData ou em outros locais, em vez de Arquivos de Programas.

Minha pergunta é: existe uma maneira de determinar dinamicamente onde o Chrome está instalado em sua máquina Windows de forma que eu possa anexá-lo ao "Destino" do atalho.lnk?

Responder1

Existe uma maneira de determinar dinamicamente onde o Chrome está instalado?

O comando a seguir determinará onde o Chrome está instalado e definirá a CHROMEPATHvariável de ambiente com este valor:

for /f "usebackq tokens=1,2,3,4,5" %a in (`reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\ /s /f \chrome.exe ^| findstr Application`) do set CHROMEPATH=%c%d%e

Exemplo de saída:

echo %CHROMEPATH%
C:\ProgramFiles(x86)\Google\Chrome\Application\chrome.exe

Para usar em um arquivo em lote, você precisa dobrar as porcentagens da seguinte forma:

for /f "usebackq tokens=1,2,3,4,5" %%a in (`reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\ /s /f \chrome.exe ^| findstr Application`) do set CHROMEPATH=%%c%%d%%e

Responder2

Encontrei o mesmo problema e, como o script criado por @DavidPostill não funcionou no PowerShell, criei o meu próprio com base na resposta dele.

function Find-PSFilePathInRegistry {
    param (
        [string]$FileName
    )
    $str = reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\ /s /f \chrome.exe | findstr Default
    # regex to find the drive letter until $FileName
    if ($str -match "[A-Z]\:.+$FileName") {
        return @{
            success = $true
            path = $Matches[0]
        }
    }
    else {
        return @{
            success = $false
            path = ""
        }
    }
}

Use da seguinte forma:

$res = Find-FilePathInRegistry "chrome.exe"
$res.success
True
$res.path
C:\Program Files\Google\Chrome\Application\chrome.exe

Se não for encontrado, $res.successserá $false.

Responder3

Então comecei a precisar disso para localizar aplicativos a fim de criar novos atalhos em endpoints. Essa função me economizou MUITO TEMPO, pois minha necessidade de encontrar o executável do Chrome em um ambiente onde o Chrome às vezes está em dois lugares tornou minha vida muito mais fácil! Obrigado! Fiz alguns ajustes e quero compartilhar de volta, então...

<#
.SYNOPSIS
Searches the Windows registry for the path of a specified application file.

.DESCRIPTION
The Find-PSFilePathInRegistry function searches the Windows registry for the path of a specified application file. It allows you to locate the installation directory of an application by searching through the registry keys associated with installed software.

.PARAMETER FileName
Specifies the name of the application file to search for in the registry.

.OUTPUTS
Outputs a custom object with the following properties:
- Success: Indicates whether the search was successful (true/false).
- Path: The full path to the specified application file.
- AppDir: The directory where the application file is located.

.EXAMPLE
Find-PSFilePathInRegistry -FileName "chrome.exe"
Searches the Windows registry for the path of the Google Chrome executable file.

.EXAMPLE
Find-PSFilePathInRegistry -FileName "notepad.exe"
Searches the Windows registry for the path of the Notepad executable file.

.NOTES
The function searches the following registry keys:
- HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
- HKCU:\Software\Microsoft\Windows\CurrentVersion\App Paths
#>
function Find-PSFilePathInRegistry {
    param (
        [string]$FileName
    )

    # Define an array of common registry locations where application paths are stored
    $registryKeys = @(
        "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\App Paths"
    )

    # Iterate through each registry key
    foreach ($key in $registryKeys) {
        if (Test-Path $key) {
            # Get the default value (which usually contains the path) for the specified file name
            $value = Get-ItemProperty -Path "$key\$FileName" -Name "(default)" -ErrorAction SilentlyContinue
            if ($value) {
                $appDir = Split-Path -Path $value.'(default)' -Parent
                return @{
                    Success = $true
                    Path = $value.'(default)'
                    AppDir = $appDir
                }
            }
        }
    }

    # If the path is not found in any of the registry keys, return failure
    return @{
        Success = $false
        Path = ""
        AppDir = ""
    }
}

informação relacionada