Encuentre Chrome dinámicamente en la máquina Windows del usuario final

Encuentre Chrome dinámicamente en la máquina Windows del usuario final

Entonces, he buscado esto en todos los lugares que se me ocurren y no puedo resolverlo. Espero que la respuesta sea muy simple. Aquí está la situación:

Estoy creando un enlace de acceso directo para un usuario final. Lo llamaremos "shortcut.lnk". Podemos suponer que tienen Chrome instalado y que "myFolder" está en su escritorio. La clave es que esta aplicación debe abrirse en Chrome, no en el navegador predeterminado del usuario. Actualmente, tengo lo siguiente como "Destino" de atajo.lnk:

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

Esto funciona en las 3 máquinas en las que lo he probado. Sin embargo, según una investigación, he notado que Chrome a veces se instala en AppData u otras ubicaciones en lugar de Archivos de programa.

Mi pregunta es la siguiente: ¿hay alguna manera de determinar dinámicamente dónde está instalado Chrome en su máquina con Windows de manera que pueda adjuntarlo al "Destino" de atajo.lnk?

Respuesta1

¿Existe alguna forma de determinar dinámicamente dónde está instalado Chrome?

El siguiente comando determinará dónde está instalado Chrome y establecerá la CHROMEPATHvariable de entorno en 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

Salida de ejemplo:

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

Para usarlo en un archivo por lotes, debe duplicar los porcentajes de la siguiente manera:

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

Respuesta2

Me encontré con el mismo problema y, dado que el script creado por @DavidPostill no funcionó en PowerShell, hice el mío propio según su respuesta.

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

Utilice de la siguiente manera:

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

Si no se encuentra, $res.successserá $false.

Respuesta3

Entonces me encontré con la necesidad de esto para localizar aplicaciones con el fin de crear nuevos accesos directos en los puntos finales. ¡Esta función me ahorró MUCHO TIEMPO ya que mi necesidad de encontrar el ejecutable de Chrome en un entorno en el que Chrome a veces está en dos lugares ha hecho mi vida mucho más fácil! ¡Gracias! Le hice algunos ajustes y quiero compartirlo, así que...

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

información relacionada