IT

컴퓨터에서 .NET Framework 버전을 반환하는 PowerShell 스크립트?

lottoking 2020. 5. 29. 08:05
반응형

컴퓨터에서 .NET Framework 버전을 반환하는 PowerShell 스크립트?


컴퓨터에서 .NET Framework 버전을 반환하는 PowerShell 스크립트는 무엇입니까?

내 첫 번째 추측은 WMI와 관련된 것입니다. 더 좋은 것이 있습니까?

.NET을 설치할 때마다 최신 버전 만 반환합니다 (각 라인마다).


레지스트리를 사용하려면 4.x Framework의 정식 버전을 얻으려면 재귀를 사용해야합니다. 이전 답변은 내 시스템에서 .NET 3.0 (3.0 아래에 중첩 된 WCF 및 WPF 번호가 더 높음-설명 할 수 없음)의 루트 번호를 반환하고 4.0에 대해서는 아무것도 반환하지 않습니다. .

편집 : .Net 4.5 이상에서는 약간 다시 변경되었으므로 이제 릴리스 값을 .Net 버전 번호 로 변환하는 방법을 설명하는 멋진 MSDN 기사가 있습니다.

이것은 나에게 잘 보입니다 (3.0에서 WCF & WPF에 대한 별도의 버전 번호를 출력합니다. 그게 뭔지 모르겠습니다). 또한 4.0에서 ClientFull모두 출력합니다 (둘 다 설치되어있는 경우).

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version,Release -EA 0 |
Where { $_.PSChildName -match '^(?!S)\p{L}'} |
Select PSChildName, Version, Release

MSDN 기사를 기반으로 조회 테이블을 작성하고 4.5 이후 릴리스의 마케팅 제품 버전 번호를 반환 할 수 있습니다.

$Lookup = @{
    378389 = [version]'4.5'
    378675 = [version]'4.5.1'
    378758 = [version]'4.5.1'
    379893 = [version]'4.5.2'
    393295 = [version]'4.6'
    393297 = [version]'4.6'
    394254 = [version]'4.6.1'
    394271 = [version]'4.6.1'
    394802 = [version]'4.6.2'
    394806 = [version]'4.6.2'
    460798 = [version]'4.7'
    460805 = [version]'4.7'
    461308 = [version]'4.7.1'
    461310 = [version]'4.7.1'
    461808 = [version]'4.7.2'
    461814 = [version]'4.7.2'
    528040 = [version]'4.8'
    528049 = [version]'4.8'
}

# For One True framework (latest .NET 4x), change the Where-Oject match 
# to PSChildName -eq "Full":
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
  Get-ItemProperty -name Version, Release -EA 0 |
  Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} |
  Select-Object @{name = ".NET Framework"; expression = {$_.PSChildName}}, 
@{name = "Product"; expression = {$Lookup[$_.Release]}}, 
Version, Release

사실,이 답변을 계속 업데이트해야하므로 해당 웹 페이지의 마크 다운 소스에서 위의 스크립트를 약간 추가하여 생성하는 스크립트가 있습니다. 이것은 아마도 어느 시점에서 깨질 것이므로 현재 사본을 위에 보관하고 있습니다.

# Get the text from github
$url = "https://raw.githubusercontent.com/dotnet/docs/master/docs/framework/migration-guide/how-to-determine-which-versions-are-installed.md"
$md = Invoke-WebRequest $url -UseBasicParsing
$OFS = "`n"
# Replace the weird text in the tables, and the padding
# Then trim the | off the front and end of lines
$map = $md -split "`n" -replace " installed [^|]+" -replace "\s+\|" -replace "\|$" |
    # Then we can build the table by looking for unique lines that start with ".NET Framework"
    Select-String "^.NET" | Select-Object -Unique |
    # And flip it so it's key = value
    # And convert ".NET FRAMEWORK 4.5.2" to  [version]4.5.2
    ForEach-Object { 
        [version]$v, [int]$k = $_ -replace "\.NET Framework " -split "\|"
        "    $k = [version]'$v'"
    }

# And output the whole script
@"
`$Lookup = @{
$map
}

# For extra effect we could get the Windows 10 OS version and build release id:
try {
    `$WinRelease, `$WinVer = Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" ReleaseId, CurrentMajorVersionNumber, CurrentMinorVersionNumber, CurrentBuildNumber, UBR
    `$WindowsVersion = "`$(`$WinVer -join '.') (`$WinRelease)"
} catch {
    `$WindowsVersion = [System.Environment]::OSVersion.Version
}

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
    Get-ItemProperty -name Version, Release -EA 0 |
    # For The One True framework (latest .NET 4x), change match to PSChildName -eq "Full":
    Where-Object { `$_.PSChildName -match '^(?!S)\p{L}'} |
    Select-Object @{name = ".NET Framework"; expression = {`$_.PSChildName}}, 
                @{name = "Product"; expression = {`$Lookup[`$_.Release]}}, 
                Version, Release,
    # Some OPTIONAL extra output: PSComputerName and WindowsVersion
    # The Computer name, so output from local machines will match remote machines:
    @{ name = "PSComputerName"; expression = {`$Env:Computername}},
    # The Windows Version (works on Windows 10, at least):
    @{ name = "WindowsVersion"; expression = { `$WindowsVersion }}
"@

gci 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' |
sort pschildname -des                                  |
select -fi 1 -exp pschildname

이 답변이 설치되어 있으면 4.5가 반환되지 않습니다. @Jaykul의 대답은 재귀를 사용합니다.


[environment]::Version

Version현재 PSH 사본이 사용하는 CLR 인스턴스를 제공합니다 ( 여기에 설명되어 있음 ).


스크립트에 v4.8 지원이 추가되었습니다.

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version,Release -EA 0 |
Where { $_.PSChildName -match '^(?![SW])\p{L}'} |
Select PSChildName, Version, Release, @{
  name="Product"
  expression={
      switch -regex ($_.Release) {
        "378389" { [Version]"4.5" }
        "378675|378758" { [Version]"4.5.1" }
        "379893" { [Version]"4.5.2" }
        "393295|393297" { [Version]"4.6" }
        "394254|394271" { [Version]"4.6.1" }
        "394802|394806" { [Version]"4.6.2" }
        "460798|460805" { [Version]"4.7" }
        "461308|461310" { [Version]"4.7.1" }
        "461808|461814" { [Version]"4.7.2" }
        "528040|528049" { [Version]"4.8" }
        {$_ -gt 528049} { [Version]"Undocumented version (> 4.8), please update script" }
      }
    }
}

올바른 구문 :

[System.Runtime.InteropServices.RuntimeEnvironment]::GetSystemVersion()
#or
$PSVersionTable.CLRVersion

GetSystemVersion함수는 다음과 같은 문자열을 반환합니다.

v2.0.50727        #PowerShell v2.0 in Win 7 SP1

또는 이런

v4.0.30319        #PowerShell v3.0 (Windows Management Framework 3.0) in Win 7 SP1

$PSVersionTable읽기 전용 개체입니다. CLRVersion 속성은 다음과 같은 구조화 된 버전 번호입니다.

Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      30319  18444   

osx의 powershell에서 탭 완성을 통해 이것을 발견했습니다.

[System.Runtime.InteropServices.RuntimeInformation]::get_FrameworkDescription() .NET Core 4.6.25009.03


간단한 스크립트를 사용하여 모든 플랫폼 및 아키텍처에서이를 수행 할 수있는 확실한 방법은 없습니다. 확실하게 수행하는 방법을 배우려면 블로그 게시물 업데이트 된 샘플 .NET Framework 검색 코드에서보다 심도있는 검사를 시작하십시오 .


예쁘지 않은. 확실히 예쁘지 않은 :

ls $Env:windir\Microsoft.NET\Framework | ? { $_.PSIsContainer } | select -exp Name -l 1

이것은 작동하거나 작동하지 않을 수 있습니다. 그러나 최신 버전에 관한 한, 이전 버전 (1.0, 1.1)의 경우 비어있는 폴더가 있지만 최신 폴더는 아니므로 적절한 프레임 워크를 설치 한 후에 만 ​​나타납니다.

그래도 더 좋은 방법이 있어야한다고 생각합니다.


원격 워크 스테이션에 설치된 .NET 버전을 찾으 려면 스크립트 페이지를 참조하십시오 .

이 스크립트는 네트워크의 여러 컴퓨터에 대한 .NET 버전을 찾는 데 유용 할 수 있습니다.


좋은 해결책

다운로드 가능한 DotNetVersionLister 모듈 (레지스트리 정보 및 일부 버전-마케팅-버전 룩업 테이블을 기반으로)을 사용해보십시오 .

다음과 같이 사용됩니다.

PS> Get-DotNetVersion -LocalHost -nosummary


ComputerName : localhost
>=4.x        : 4.5.2
v4\Client    : Installed
v4\Full      : Installed
v3.5         : Installed
v3.0         : Installed
v2.0.50727   : Installed
v1.1.4322    : Not installed (no key)
Ping         : True
Error        :

또는 .NET Framework> = 4. *에 대해서만 테스트하려는 경우 다음과 같이하십시오 .

PS> (Get-DotNetVersion -LocalHost -nosummary).">=4.x"
4.5.2

그러나 호환되지 않기 때문에 PS v2.0 ( Win 7 , Win Server 2010 표준) 과 같이 작동하지 않습니다 (설치 / 가져 오기) .

아래의 "레거시"기능에 대한 동기

(이 글을 건너 뛰고 아래 코드를 사용할 수 있습니다)

일부 컴퓨터 에서는 PS 2.0 으로 작업 해야했고 위의 DotNetVersionLister를 설치 / 가져올 수 없었 습니다 .
다른 컴퓨터 에서는 두 개의 회사 사용자 지정 의 도움을 받아 PS 2.0 에서 PS 5.1 ( .NET Framework> = 4.5 필요 ) 로 업데이트하려고했습니다 . 관리자에게 설치 / 업데이트 프로세스를 잘 안내하려면 기존의 모든 컴퓨터 및 PS 버전에서이 기능으로 .NET 버전을 결정해야합니다. 따라서 우리는 아래 기능을 사용하여 모든 환경에서 더 안전하게 결정했습니다 ...Install-DotnetLatestCompanyInstall-PSLatestCompany

레거시 PS 환경을위한 기능 (예 : PS v2.0 )

따라서 다음 코드와 아래 (추출 된) 사용 예제가 여기에 유용합니다 (여기의 다른 답변을 바탕으로).

function Get-DotNetVersionByFs {
  <#
    .SYNOPSIS
      NOT RECOMMENDED - try using instead:
        Get-DotNetVersion 
          from DotNetVersionLister module (https://github.com/EliteLoser/DotNetVersionLister), 
          but it is not usable/importable in PowerShell 2.0 
        Get-DotNetVersionByReg
          reg(istry) based: (available herin as well) but it may return some wrong version or may not work reliably for versions > 4.5 
          (works in PSv2.0)
      Get-DotNetVersionByFs (this):  
        f(ile) s(ystem) based: determines the latest installed .NET version based on $Env:windir\Microsoft.NET\Framework content
        this is unreliable, e.g. if 4.0* is already installed some 4.5 update will overwrite content there without
        renaming the folder
        (works in PSv2.0)
    .EXAMPLE
      PS> Get-DotnetVersionByFs
      4.0.30319
    .EXAMPLE
      PS> Get-DotnetVersionByFs -All
      1.0.3705
      1.1.4322
      2.0.50727
      3.0
      3.5
      4.0.30319
    .NOTES
      from https://stackoverflow.com/a/52078523/1915920
  #>
    [cmdletbinding()]
  param(
    [Switch]$All  ## do not return only latest, but all installed
  )
  $list = ls $Env:windir\Microsoft.NET\Framework |
    ?{ $_.PSIsContainer -and $_.Name -match '^v\d.[\d\.]+' } |
    %{ $_.Name.TrimStart('v') }
  if ($All) { $list } else { $list | select -last 1 }
}


function Get-DotNetVersionByReg {
  <#
    .SYNOPSIS
      NOT RECOMMENDED - try using instead:
        Get-DotNetVersion
          From DotNetVersionLister module (https://github.com/EliteLoser/DotNetVersionLister), 
          but it is not usable/importable in PowerShell 2.0. 
          Determines the latest installed .NET version based on registry infos under 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP'
    .EXAMPLE
        PS> Get-DotnetVersionByReg
        4.5.51209
    .EXAMPLE
        PS> Get-DotnetVersionByReg -AllDetailed
        PSChildName                                          Version                                             Release
        -----------                                          -------                                             -------
        v2.0.50727                                           2.0.50727.5420
        v3.0                                                 3.0.30729.5420
        Windows Communication Foundation                     3.0.4506.5420
        Windows Presentation Foundation                      3.0.6920.5011
        v3.5                                                 3.5.30729.5420
        Client                                               4.0.0.0
        Client                                               4.5.51209                                           379893
        Full                                                 4.5.51209                                           379893
    .NOTES
      from https://stackoverflow.com/a/52078523/1915920
  #>
    [cmdletbinding()]
    param(
        [Switch]$AllDetailed  ## do not return only latest, but all installed with more details
    )
    $Lookup = @{
        378389 = [version]'4.5'
        378675 = [version]'4.5.1'
        378758 = [version]'4.5.1'
        379893 = [version]'4.5.2'
        393295 = [version]'4.6'
        393297 = [version]'4.6'
        394254 = [version]'4.6.1'
        394271 = [version]'4.6.1'
        394802 = [version]'4.6.2'
        394806 = [version]'4.6.2'
        460798 = [version]'4.7'
        460805 = [version]'4.7'
        461308 = [version]'4.7.1'
        461310 = [version]'4.7.1'
        461808 = [version]'4.7.2'
        461814 = [version]'4.7.2'
    }
    $list = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
        Get-ItemProperty -name Version, Release -EA 0 |
        # For One True framework (latest .NET 4x), change match to PSChildName -eq "Full":
        Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} |
        Select-Object `
           @{
               name = ".NET Framework" ; 
               expression = {$_.PSChildName}}, 
           @{  name = "Product" ; 
               expression = {$Lookup[$_.Release]}}, 
           Version, Release
    if ($AllDetailed) { $list | sort version } else { $list | sort version | select -last 1 | %{ $_.version } }
}

사용법 예 :

PS> Get-DotNetVersionByFs
4.0.30319

PS> Get-DotNetVersionByFs -All
1.0.3705
1.1.4322
2.0.50727
3.0
3.5
4.0.30319

PS> Get-DotNetVersionByReg
4.5.51209

PS> Get-DotNetVersionByReg -AllDetailed

.NET Framework                   Product Version        Release
--------------                   ------- -------        -------
v2.0.50727                               2.0.50727.5420
v3.0                                     3.0.30729.5420
Windows Communication Foundation         3.0.4506.5420
Windows Presentation Foundation          3.0.6920.5011
v3.5                                     3.5.30729.5420
Client                                   4.0.0.0
Client                           4.5.2   4.5.51209      379893
Full                             4.5.2   4.5.51209      379893

컴퓨터에 Visual Studio를 설치 한 경우 Visual Studio Developer 명령 프롬프트를 열고 다음 명령을 입력하십시오. clrver

해당 컴퓨터에 설치된 모든 .NET Framework 버전이 나열됩니다.


일반적인 아이디어는 다음과 같습니다.

이름이 패턴 v number dot number 와 일치하는 컨테이너 인 컨테이너 인 .NET Framework 디렉토리에서 하위 항목을 가져옵니다 . 내림차순으로 정렬하고 첫 번째 객체를 가져 와서 name 속성을 반환합니다.

스크립트는 다음과 같습니다.

(Get-ChildItem -Path $Env:windir\Microsoft.NET\Framework | Where-Object {$_.PSIsContainer -eq $true } | Where-Object {$_.Name -match 'v\d\.\d'} | Sort-Object -Property Name -Descending | Select-Object -First 1).Name

PowerShell 에서이 작업을 시도했습니다.

(Get-ItemProperty "HKLM : Software \ Microsoft \ NET Framework Setup \ NDP \ v4 \ Full"). 버전


I'm not up on my PowerShell syntax, but I think you could just call System.Runtime.InteropServices.RuntimeEnvironment.GetSystemVersion(). This will return the version as a string (something like v2.0.50727, I think).

참고URL : https://stackoverflow.com/questions/3487265/powershell-script-to-return-versions-of-net-framework-on-a-machine

반응형