Qual é a melhor maneira de programa contra x64 variabilidade vs. x86 do powershell

StackOverflow https://stackoverflow.com/questions/602060

  •  03-07-2019
  •  | 
  •  

Pergunta

Temos vários scripts que usamos para instalar e configurar as dependências de apoio os sistemas que mantêm. Corremos estes a qualquer hora que estabelecer um dev, teste, demonstração, trem, prod, etc. ambiente. Nós muitas vezes achamos que temos de lidar com x64 vs x86 arquitetura, especialmente onde os scripts do PowerShell estão em causa.

Por exemplo, eu tenho um script que utiliza os do Windows PowerShell Extensions Installer para determinar se um programa / patch foi instalado. O script não funciona em um ambiente x64 sem invocar explicitamente PowerShell (x86), o qual, não está no caminho por padrão. À medida que a porta esses scripts para a plataforma x64 seria ótimo para manter um único conjunto de scripts que trabalham em powershell em ambas as arquiteturas e só chamar o código x86 quando necessário.

Alguém sabe de uma estratégia para fazer isso?

Foi útil?

Solução 2

O msgoodies blogue tem esta sugestão para determinar a arquitetura . Pode-se usar essa abordagem para determinar a arquitetura e invocar o PowerShell x86 quando há uma incompatibilidade conhecida.

Outras dicas

eu me deparo com esta questão muito com meus scripts de configuração. A abordagem básica eu dou é para

  1. Use várias funções para testar se eu estou em um ambiente de 64 bits ( http://blogs.msdn.com/jaredpar/archive/2008/10/16/powershell-and-64-bit-windows-helper-functions.aspx )
  2. Invoke x86 / x64 PowerShell com base nas necessidades de um determinado script

Infelizmente um monte de presente é feito de uma forma força bruta. Cada entrada de configuração especial, que é x 86/64 x dependente essencialmente tem 2 caminhos de código (uma para cada arquitectura).

A única exceção real eu fui capaz de fazer é teste para o existince de determinados programas no disco. Eu tenho uma função útil (Get-ProgramFiles32) que torna mais fácil para testar programas.

if ( test-path (join-path Get-ProgramFiles32 "subversion") ) { ...

Aqui estão todas as funções auxiliares que eu tenho em minha biblioteca comum que lidam com 32/64 diferenças bits.

# Get the path where powershell resides.  If the caller passes -use32 then 
# make sure we are returning back a 32 bit version of powershell regardless
# of the current machine architecture
function Get-PowerShellPath() {
    param ( [switch]$use32=$false,
            [string]$version="1.0" )

    if ( $use32 -and (test-win64machine) ) {
        return (join-path $env:windir "syswow64\WindowsPowerShell\v$version\powershell.exe")
    }

    return (join-path $env:windir "System32\WindowsPowerShell\v$version\powershell.exe")
}


# Is this a Win64 machine regardless of whether or not we are currently 
# running in a 64 bit mode 
function Test-Win64Machine() {
    return test-path (join-path $env:WinDir "SysWow64") 
}

# Is this a Wow64 powershell host
function Test-Wow64() {
    return (Test-Win32) -and (test-path env:\PROCESSOR_ARCHITEW6432)
}

# Is this a 64 bit process
function Test-Win64() {
    return [IntPtr]::size -eq 8
}

# Is this a 32 bit process
function Test-Win32() {
    return [IntPtr]::size -eq 4
}

function Get-ProgramFiles32() {
    if (Test-Win64 ) {
        return ${env:ProgramFiles(x86)}
    }

    return $env:ProgramFiles
}

function Invoke-Admin() {
    param ( [string]$program = $(throw "Please specify a program" ),
            [string]$argumentString = "",
            [switch]$waitForExit )

    $psi = new-object "Diagnostics.ProcessStartInfo"
    $psi.FileName = $program 
    $psi.Arguments = $argumentString
    $psi.Verb = "runas"
    $proc = [Diagnostics.Process]::Start($psi)
    if ( $waitForExit ) {
        $proc.WaitForExit();
    }
}

# Run the specified script as an administrator
function Invoke-ScriptAdmin() {
    param ( [string]$scriptPath = $(throw "Please specify a script"),
            [switch]$waitForExit,
            [switch]$use32=$false )

    $argString = ""
    for ( $i = 0; $i -lt $args.Length; $i++ ) {
        $argString += $args[$i]
        if ( ($i + 1) -lt $args.Length ) {
            $argString += " "
        }
    }

    $p = "-Command & "
    $p += resolve-path($scriptPath)
    $p += " $argString" 

    $psPath = Get-PowershellPath -use32:$use32
    write-debug ("Running: $psPath $p")
    Invoke-Admin $psPath $p -waitForExit:$waitForExit
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top