Monday, September 7, 2020

Power Shell Script - Get the OS build of Remote machines

 #add your hostname in a text file -d:\path.txt and Output will come in D:excel.csv

#Requires -Version 3.0
Function Get-LHSWindowsVersion
{
<#
.SYNOPSIS
    Get Windows version information from local or Remote Computer

.DESCRIPTION
Get Windows version information from local or Remote Computer.
    Get Windows Version information using CIM and Registry(over CIM).

.PARAMETER ComputerName
    The computer name(s) to retrieve the info from.
    Default to local Computer.

    When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that
    is used only to run the specified command and is then closed. If you need a persistent connection,
    use the Session parameter.

.PARAMETER CimSession
    Specifies the CIM sessions to use for this cmdlet.
    Enter a variable that contains the CIM session or a command that creates or
    gets the CIM session, such as the New-CimSession or Get-CimSession cmdlets.
    For more information, see about_CimSessions.

.PARAMETER Credential
    Alternate Credential to connect to the remote Computer.
    The default is the current user.

.EXAMPLE
    To List DefaultDisplayProperties from local Computer

    Get-LHSWindowsVersion

    ComputerName OSName                          ReleaseId MUILanguages
    ------------ ------                          --------- ------------
    PC1          Microsoft Windows 10 Enterprise 1709      de-DE

.EXAMPLE
    To list all Properties use Select * or Format-List *

    Get-LHSWindowsVersion -ComputerName PC2 | select *

    ComputerName                : PC2
    OSName                      : Microsoft Windows 10 Enterprise
    ReleaseId                   : 1709
    Version                     : 10.0.16299
    ServicePackMajorVersion     : 0
    ServicePackMinorVersion     : 0
    OSArchitecture              : 64-Bit
    OSLanguage                  : 1031
    MUILanguages                : de-DE
    WindowsDirectory            : C:\Windows
    Universal_Unique_Identifier : C8783A42-8BC7-5936-6E7D-AC4CF7E8E812
    BuildNumber                 : 16299
    SerialNumber                : 00329-00000-00003-AA779
    InstallDate                 : 13.11.2018 08:32:54
    LastBootUpTime              : 07.01.2019 10:56:09

.EXAMPLE
    Exaple to use pipeline input for ComputerName

    'Server1','Server2' | Get-LHSWindowsVersion

    ComputerName OSName                                 ReleaseId MUILanguages
    ------------ ------                                 --------- ------------
    Server1      Microsoft Windows Server 2016 Standard 1607      en-US
    Server2      Microsoft Windows Server 2016 Standard 1607      en-US

.EXAMPLE
    To list OS Information using existent CIMSessions as pipeline input

    Get-CimSession | Get-LHSWindowsVersion

.EXAMPLE
    To list OS Information using an existent CIMSession and using Parameter -CimSession

    $CimSession = New-CimSession -ComputerName Server1 -SessionOption (New-CimSessionOption -Protocol Dcom)
    Get-LHSWindowsVersion -CimSession $CimSession

.INPUTS
    you can pipe input ComputerNames or CimSessions to this Function

.OUTPUTS
    PSCustomObject with the following TypeNames

    TypeNames:
    ------------------
    LHS.Windows.Version
    System.Management.Automation.PSCustomObject
    System.Object

.NOTES
    Windows Universal Unique Identifier (UUID)
    Every Windows installation has a unique UUID that you can use to distinguish machines.
    While computer names can change, the UUID won’t.

    AUTHOR  : Pasquale Lantella
    LASTEDIT: 08.01.2019
    KEYWORDS: Windows,Version,UUID
    Version : 1.0
    History :

.LINK
    about_CimSessions

.LINK

#Requires -Version 3.0
#>

[cmdletbinding(DefaultParameterSetName = 'Default')]

[OutputType([System.Management.Automation.PSCustomObject])]
#[OutputType('LHS.Windows.Version')]

Param(

    [Parameter(ParameterSetName='Default',Position=0,
        ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,
        HelpMessage='An array of computer names. The default is the local computer.')]
    [alias("CN")]
    [string[]]$ComputerName = $Env:COMPUTERNAME,

    [Parameter(
        ParameterSetName='CimSession',Position=0,
        ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
    [ValidateNotNullorEmpty()]
    [Microsoft.Management.Infrastructure.CimSession[]]$CimSession,

    [parameter(ParameterSetName='Default',Position=1)]
    [Alias('RunAs')]
    [System.Management.Automation.PSCredential]
    [System.Management.Automation.Credential()]
    $Credential = [System.Management.Automation.PSCredential]::Empty

)

BEGIN {

    Set-StrictMode -Version 3.0
    ${CmdletName} = $Pscmdlet.MyInvocation.MyCommand.Name

    # custom PSTypeName for Output Objects
    $TypeName = 'LHS.Windows.Version'
    $TypeData = @{
        TypeName = $TypeName
        DefaultDisplayPropertySet = @('ComputerName','OSName','ReleaseId','MUILanguages')
        ErrorAction = 'SilentlyContinue'
    }
    Update-TypeData @TypeData

} # end BEGIN

PROCESS {

    switch ($PsCmdlet.ParameterSetName)
    {
        'Default'
        {
            #process computer names individually
            ForEach ($Computer in $ComputerName)
            {
                    IF (Test-Connection -ComputerName $Computer -count 2 -quiet)
                {
                    $CimSessionTemp = $null
                    Try
                    {
                        Test-WSMan -ComputerName $Computer -ErrorAction Stop | Out-Null

                        $SessionParams = @{
                              ComputerName  = $Computer
                              ErrorAction = 'Stop'
                              SessionOption = (New-CimSessionOption -Protocol DCOM -ErrorAction Stop)
                        }
                        if ($PSBoundParameters['Credential'])
                        {
                            Write-Verbose "Adding alternate credential for CIMSession"
                            $SessionParams.Credential = $Credential
                        }
                        Write-Verbose "Creating CimSession.."
                        $CimSessionTemp = (New-CimSession @SessionParams)
                    }
                    Catch
                    {
                        Write-Verbose "[PROCESS] \\$Computer Test-WSMan failed! `n if the remote computer is running PowerShell 2.0 this will fail. You have to manually create a CIMSession with a CIMSessionOption to use the DCOM protocol."
                        Write-Verbose "[PROCESS] $($_.exception.message)"
                        Write-Verbose "Trying using DCOM Protocol"
                        Try
                        {
                            $SessionParams = @{
                                  ComputerName  = $Computer
                                  ErrorAction = 'Stop'
                                  SessionOption = (New-CimSessionOption -Protocol DCOM -ErrorAction Stop)
                            }
                            if ($PSBoundParameters['Credential'])
                            {
                                Write-Verbose "Adding alternate credential for CIMSession"
                                $SessionParams.Credential = $Credential
                            }
                            Write-Verbose "Creating CimSession.."
                            $CimSessionTemp = (New-CimSession @SessionParams)

                        }
                        Catch
                        {
                            Write-Warning "[PROCESS] $_"
                        }

                    } # catch

                    Try
                    {
                        [uint32]$HKLM = 2147483650
                        $RegKey = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
                        $RegValue = 'ReleaseId'

                        $Params = @{
                            Namespace = 'root\default'
                            ClassName = 'StdRegProv'
                            MethodName = 'GetStringValue'
                            CimSession = $CimSessionTemp
                            Arguments = @{hDefKey=$HKLM; sSubKeyName =$RegKey; sValueName = $RegValue}
                        }
                        $ReleaseId = $null
                        $ReleaseId = Invoke-CimMethod @Params -ErrorAction Stop |
                            Select-Object -ExpandProperty sValue

                        $OperatingSystem = $null
                        $OperatingSystem = Get-CimInstance -ClassName Win32_OperatingSystem -CimSession $CimSessionTemp -Property * -ErrorAction Stop

                        #Windows Universal Unique Identifier (UUID)
                        $UUID = $null
                        $UUID = Get-CimInstance -ClassName Win32_ComputerSystemProduct -CimSession $CimSessionTemp -ErrorAction Stop | Select-Object -ExpandProperty UUID
                    }
                    Catch
                    {
                        Write-Error "[PROCESS] $_"
                    }

                    foreach ($OS in $OperatingSystem)
                    {
                        $OutputObj = [pscustomobject][Ordered] @{
                            PSTypeName = $TypeName
                            ComputerName = $Computer
                            OSName = $OS.Caption
                            ReleaseId = $ReleaseId
                            Version = $OS.Version
                            ServicePackMajorVersion = $OS.ServicePackMajorVersion
                            ServicePackMinorVersion = $OS.ServicePackMinorVersion
                            OSArchitecture = $OS.OSArchitecture
                            OSLanguage = $Os.OSLanguage
                            MUILanguages = $OS.MUILanguages -join ','
                            WindowsDirectory = $OS.WindowsDirectory
                            Universal_Unique_Identifier = $UUID
                            BuildNumber = $OS.BuildNumber
                            SerialNumber = $OS.SerialNumber
                            InstallDate = $OS.InstallDate
                            LastBootUpTime = $OS.LastBootUpTime
                        }
                        $OutputObj
                    }

                    If($CimSessionTemp) { Remove-CimSession -CimSession $CimSessionTemp -ErrorAction SilentlyContinue }
                }
                Else
                {
                    Write-Warning "\\$Computer computer DO NOT reply to ping."
                } # end IF (Test-Connection $Computer -quiet)
            } # end ForEach ($Computer in $computerName)

        } # end 'Default'

        'CimSession'
        {
            Write-Verbose "[PROCESS] connecting via existing CIMSessions"

            foreach ($Session in $CimSession)
            {
                Try
                {
                    [uint32]$HKLM = 2147483650
                    $RegKey = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
                    $RegValue = 'ReleaseId'

                    $Params = @{
                        Namespace = 'root\default'
                        ClassName = 'StdRegProv'
                        MethodName = 'GetStringValue'
                        CimSession = $Session
                        Arguments = @{hDefKey=$HKLM; sSubKeyName =$RegKey; sValueName = $RegValue}
                    }
                    $ReleaseId = $null
                    $ReleaseId = Invoke-CimMethod @Params -ErrorAction Stop |
                        Select-Object -ExpandProperty sValue

                    $OperatingSystem = $null
                    $OperatingSystem = Get-CimInstance -ClassName Win32_OperatingSystem -CimSession $Session -Property * -ErrorAction Stop

                    #Windows Universal Unique Identifier (UUID)
                    $UUID = $null
                    $UUID = Get-CimInstance -ClassName Win32_ComputerSystemProduct -CimSession $Session -ErrorAction Stop | Select-Object -ExpandProperty UUID
                }
                Catch
                {
                    Write-Error $_
                }

                foreach ($OS in $OperatingSystem)
                {
                    $OutputObj = [pscustomobject][Ordered] @{
                        PSTypeName = $TypeName
                        ComputerName = $OS.PSComputerName
                        OSName = $OS.Caption
                        ReleaseId = $ReleaseId
                        Version = $OS.Version
                        ServicePackMajorVersion = $OS.ServicePackMajorVersion
                        ServicePackMinorVersion = $OS.ServicePackMinorVersion
                        OSArchitecture = $OS.OSArchitecture
                        OSLanguage = $Os.OSLanguage
                        MUILanguages = $OS.MUILanguages -join ','
                        WindowsDirectory = $OS.WindowsDirectory
                        Universal_Unique_Identifier = $UUID
                        BuildNumber = $OS.BuildNumber
                        SerialNumber = $OS.SerialNumber
                        InstallDate = $OS.InstallDate
                        LastBootUpTime = $OS.LastBootUpTime
                    }
                    $OutputObj
                }

            } # foreach ($Session in $CimSession)
        } # 'CimSession'
    } # end switch ($PsCmdlet.ParameterSetName)


} # end PROCESS

END { Write-Verbose "Function ${CmdletName} finished." }

} # end Get-LHSWindowsVersion

Get-Content "d:\path.txt" | Get-LHSWindowsVersion | Export-Csv -path d:\excel.csv

cm

No comments: