确定Powershell中的32/64位

确定Powershell中的32/64位,powershell,Powershell,我正在尝试创建一对代码行,如果机器是32/64位的,那么它将从WMI中提取,如果机器是64位的,那么就这样做。。。。如果是32位,请执行此操作 有人能帮忙吗 [IntPtr]::Size -eq 4 # 32 bit IntPtr的大小在32位机器上为4字节,在64位机器上为8字节() -编辑,抱歉,忘记包含更多代码来解释用法 if($env:PROCESSOR_ARCHITECTURE -eq "x86") { #If the powershell console is x86, crea

我正在尝试创建一对代码行,如果机器是32/64位的,那么它将从WMI中提取,如果机器是64位的,那么就这样做。。。。如果是32位,请执行此操作

有人能帮忙吗

[IntPtr]::Size -eq 4 # 32 bit

IntPtr的大小在32位机器上为4字节,在64位机器上为8字节()

-编辑,抱歉,忘记包含更多代码来解释用法

if($env:PROCESSOR_ARCHITECTURE -eq "x86")
 {
#If the powershell console is x86, create alias to run x64 powershell console.
 set-alias ps64 "$env:windir\sysnative\WindowsPowerShell\v1.0\powershell.exe"

$script2=[ScriptBlock]::Create("#your commands here, bonus is the script block expands variables defined above")

ps64 -command $script2
 }
 Else{
 #Otherwise, run the x64 commands.

假设您至少运行Windows 7,以下操作应该可以正常工作

包括一个在64位机器上运行的32位版本powershell中为我工作的示例:

gwmi win32_operatingsystem | select osarchitecture
返回64位的“64位”

if ((gwmi win32_operatingsystem | select osarchitecture).osarchitecture -eq "64-bit")
{
    #64 bit logic here
    Write "64-bit OS"
}
else
{
    #32 bit logic here
    Write "32-bit OS"
}

环境中有两个布尔静态方法可以检查和比较,一个查看PowerShell进程,一个查看底层操作系统

if ([Environment]::Is64BitProcess -ne [Environment]::Is64BitOperatingSystem)
{
"PowerShell process does not match the OS"
}

这与前面的答案类似,但无论64位/64_位/64位/64位格式如何,都将得到正确的结果

if ((Get-WmiObject win32_operatingsystem | select osarchitecture).osarchitecture -like "64*")
{
#64bit code here
Write "64-bit OS"
}
else
{
#32bit code here
Write "32-bit OS"
}

两条线拼在一起形成了一条漂亮的单线:

Write-Host "64bit process?:"$([Environment]::Is64BitProcess) ;Write-Host "64bit OS?:"$([Environment]::Is64BitOperatingSystem);

重用Guvante的答案创建全局布尔值

$global:Is64Bits=if((gwmi win32_operatingsystem | select osarchitecture).osarchitecture -eq "64-bit"){$true}else{$false}

如何将其放入if语句中,以便将代码放在32位cpu和64位cpu之后。我尝试了你的线路,但运气不好,尽管我相信还有更多的问题。在64位版本的Windows上运行的32位版本的powershell中,此返回为真。抱歉,忘了包含处理在x64或x86 powershell中运行的代码。在较新版本的windows ex.8.1I上运行这样会很好吗?我认为不会有任何问题,只要Powershell环境变量
$env:PROCESSOR_ARCHITECTURE
可用。我将如何将其放入和if语句中?这只会告诉您正在运行的Powershell版本。调出一个32位窗口进行验证。“在32位机器上IntPtr的大小为4字节,在64位机器上为8字节”不正确。此代码检查进程(而不是操作系统)是否为32位。请参阅链接文档,其中(emphasis mine)“此进程中指针或句柄的大小,以字节为单位。此属性的值在32位进程中为4,在64位进程中为8。”较旧的操作系统没有osarchitecture属性fwiw。较旧的操作系统是什么?我们只有Windows7和UP7,我觉得你很好。Vista可能是最后一个没有它的版本。64位并不总是有保证的,我遇到了一个用户,他的回答是“64位”。@QuickNull:你能扩展这个评论吗?此逻辑可能完全无法检测64位(如其他注释中所述),但我想不出它会错误检测64位的情况。
[Environment]:Is64BitOperatingSystem
此变量在较旧的环境中不可用,例如Windows 7上的Powershell 2.0@Guvante的答案似乎有效。@dmattp和是在.NET 4.0中引入的-最初由PowerShell 3.0使用-而在Vista/Server 2008中引入的。在较旧的系统上,用户可以自己选择。
$global:Is64Bits=if((gwmi win32_operatingsystem | select osarchitecture).osarchitecture -eq "64-bit"){$true}else{$false}