Windows OS Licensing Status Script

Hello,

Having issues with a script to output to console and text file the OS licensing status. I only need a zero for unlicensed and a 1 for licensed.

Any help is appreciated.

####### VARIABLES #######
##################################################################################################
### Server list file name. Each server Hostname/FQDN/IP address has to be on new line. 
###This file has to be located on your Desktop.
$serverfile = "servers.txt"
###################################################################################################
####### END OF VARIABLES. DO NOT ALTER ANYTHING BELOW THIS LINE !!! #######
###################################################################################################
$FileDate = Get-Date -Format yyyyMMdd
$xml_output = ".\server-check-$FileDate.xml"
$txt_output = ".\server-check-$FileDate.txt"
$serverlist = ".\$serverfile"
Clear-Host
Function global:Get-RawWMI ([Parameter(ValueFromPipeline=$TRUE,Mandatory=$TRUE,Position=0)][string]$ComputerName)
{
    $COMPobj = Get-WmiObject -Class "Win32_ComputerSystem" -ComputerName $ComputerName -EA SilentlyContinue
		IF(-not $?){return $error[0]}
    $CPUobj = Get-WmiObject -Class "Win32_Processor" -ComputerName $ComputerName -EA SilentlyContinue
		IF(-not $?){return $error[0]}
    $CPUobj | %{
		IF(-not ($_.NumberOfCores)){$_ | Add-Member -MemberType NoteProperty -Name "NumberOfCores" -Value 1}
				}
    $OSobj = Get-WmiObject -Class "Win32_OperatingSystem" -ComputerName $ComputerName -EA SilentlyContinue
		IF(-not $?){return $error[0]}
    $RAMobj = Get-WmiObject -Class "Win32_PhysicalMemory" -ComputerName $ComputerName -EA SilentlyContinue
		IF(-not $?){return $error[0]}
    $MEMobj = Get-WmiObject -Class Win32_PhysicalMemory -cn $ComputerName -EA SilentlyContinue
		IF(-not $?){return $error[0]}
    $DisksObj = Get-WmiObject -Class "Win32_LogicalDisk" -ComputerName $ComputerName -EA SilentlyContinue | Where-Object {($_.Size) -and (($_.MediaType -eq 12) -or ($_.MediaType -eq 0))}
		IF(-not $?){return $error[0]}
    $Mounts = Get-WMIObject -Class "Win32_Volume" -ComputerName $ComputerName -EA SilentlyContinue | Where-Object {$_.Name.Contains(":\") -and ($_.Name.Length -gt 3)}
		IF(-not $?){return $error[0]}
    $NICs = Get-WmiObject -Class "Win32_NetworkAdapterConfiguration" -ComputerName $ComputerName  -EA SilentlyContinue | Where-Object {$_.IpEnabled}
		IF(-not $?){return $error[0]}
    $PageFile = Get-WmiObject -Class "Win32_PageFile" -ComputerName $ComputerName -EA SilentlyContinue
		IF(-not $?){return $error[0]}
    $TimeZone = Get-WmiObject -Class "Win32_TimeZone" -ComputerName $ComputerName -EA SilentlyContinue
		IF(-not $?){return $error[0]}
    $PersRoutes = Get-WmiObject -Class "Win32_IP4PersistedRouteTable" -ComputerName $ComputerName -EA SilentlyContinue
		IF(-not $?){return $error[0]}
    $OSAct = Get-WmiObject -Class SoftwareLicensingProduct -ComputerName $ComputerName -EA SilentlyContinue | Select-Object LicenseStatus
        IF(-not $?){return $error[0]}
    $ClusterObj = Get-WmiObject -ComputerName $ComputerName -Class "MSCluster_Cluster" -Namespace "root\mscluster" -EA SilentlyContinue
		IF($ClusterObj){$Clustering = "FO: $($ClusterObj.Name)"}
		ELSE{
			$ClusterObj = Get-WmiObject -ComputerName $ComputerName -Class "MicrosoftNLB_Cluster" -Namespace "root\MicrosoftNLB" -EA SilentlyContinue
				IF($ClusterObj){$Clustering = "NLB: $($ClusterObj.Name)"}
				ELSE{$Clustering = "N/A"}
			}
    return New-Object PSObject -Property @{
        Computer = $COMPobj
        CPU = $CPUobj
        OS = $OSobj
	OSAct = $OSActObj
        Cluster = $Clustering
        RAM = $RAMobj
	TotalRAM = $MEMobj
        Disks = $DisksObj
        Mounts = $Mounts
        NICs = $NICs
        PageFile = $PageFile
        TimeZone = $TimeZone
        PersRoutes = $PersRoutes
    }
}
##################################################################################################################################

Function global:Screen ([Parameter(ValueFromPipeline=$TRUE,Mandatory=$TRUE,Position=0)][string]$ComputerName,
                        [Parameter(Position=1)][switch]$NoClip)
{
    $CMO = Get-RawWMI -ComputerName $ComputerName
		IF($CMO.Exception){return $CMO.Exception}
		IF($CMO.PageFile){[array]$PageFiles = $CMO.PageFile | %{"$($_.EightDotThreeFileName) ($($_.FileSize/1MB)/$($_.MaximumSize)MB)"}}
    $RemoteRegistry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $ComputerName)
		IF(-not $?){return}
	$dotNETkey = $RemoteRegistry.OpenSubKey("SOFTWARE\Microsoft\NET Framework Setup\NDP")
	$UACkey = $RemoteRegistry.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system")
	$RAMstr = $CMO.RAM | Select-Object -ExpandProperty Capacity | %{($_/1024MB).ToString()}
    [hashtable]$RAMhash = @{}
    $RAMstr | % {
        IF($RAMhash.ContainsKey($_)){$RAMhash.$_++}
        ELSE{$RAMhash += @{$_ = 1}}
        }
	$MEMstr = (($CMO.RAM | Measure-Object -Property Capacity -Sum).Sum)/1GB
    $CPUstr = $CMO.CPU | %{"$(($_.Name).Trim()) $($_.NumberOfCores)-core"}
    [hashtable]$CPUhash = @{}
    $CPUstr | %{
        IF($CPUhash.ContainsKey($_)){$CPUhash.$_++}
        ELSE{$CPUhash += @{$_ = 1}}
        }
    [array]$Disks = $null
    $CMO.Disks | %{
        IF($_.DriveType -eq 4){$_.VolumeName = $_.ProviderName}
        $Disks += "Device Name  - $($_.DeviceID)($($_.VolumeName))`nTotal Used   - $("{0:N2}" -f (($_.Size - $_.FreeSpace)/1GB)) GB`nTotal Volume - $("{0:N2}" -f ($_.Size/1GB)) GB`nFree Space   - $("{0:N2}" -f (($_.FreeSpace)/1GB)) GB`nFile System  - $($_.FileSystem)`n"
        }
    [array]$Mounts = $null
    $CMO.Mounts | %{$Mounts += "$($_.Name) - $("{0:N2}" -f (($_.Capacity - $_.FreeSpace)/1GB)) GB of $("{0:N2}" -f ($_.Capacity/1GB)) GB used )$($_.FileSystem))"}
    [array]$Network = $null
    $CMO.NICs | % {
        [string]$out = "$($_.Description)`n`tIP: `t$($_.IPAddress -join "`n`t`t")"
			IF($_.MacAddress){$out += "`n`tMAC:`t$($_.MacAddress -join "`t`t")"}
			IF($_.DefaultIPGateway){$out += "`n`tGW: `t$($_.DefaultIPGateway -join "`n`t`t")"}
			IF($_.DNSServerSearchOrder){$out += "`n`tDNS:`t$($_.DNSServerSearchOrder -join "`n`t`t")"}
			$Network += $out 
					}
    $LastBoot = ([Management.ManagementDateTimeConverter]::ToDateTime($CMO.OS.LastBootUpTime))
    $LocalTime = ([Management.ManagementDateTimeConverter]::ToDateTime($CMO.OS.LocalDateTime))
    $Uptime = $LocalTime - $LastBoot
    $LocaleCode = $CMO.OS.Locale
    $LocaleInfo = [System.Globalization.CultureInfo]([int]("0x" + $LocaleCode))
    $sysinfo = systeminfo /s $ComputerName /fo csv | ConvertFrom-Csv | select 'OS Name*'
    $outObj = New-Object PSObject -Property @{
        Name = $CMO.Computer.Name
        Domain = $CMO.Computer.Domain
        Platform = $CMO.Computer.Model
        Cluster = $CMO.Cluster
        OS = "$($sysinfo.'OS Name') ($($CMO.OS.OSArchitecture))"
        OSAct = $OSActObj.LicenseStatus -join "`n"
        CPU = ($CPUhash.GetEnumerator() | %{"$($_.Value) x $($_.Name)"}) -join "`n"
        RAM = ($RAMhash.GetEnumerator() | %{"$($_.Value) x $($_.Name) GB"})  -join "`n"
	TotalRAM = ($MEMstr | %{"$_ GB"}) -join "`n"
        Storage = $Disks -join "`n"
        MountPoints = $Mounts -join "`n"
        Network = $Network -join "`n`n"
        PersRoutes = ($CMO.PersRoutes | %{"ND = $($_.Name) GW = $($_.NextHop) MASK = $($_.Mask) METRIC = $($_.Metric1)"}) -join "`n"
        TimeZone = $CMO.TimeZone.Caption
        Locale =  $LocaleInfo.Name
        CountryCode = $CMO.OS.CountryCode
        PageFiles = $PageFiles -join "`n"	
        LastBoot = ([Management.ManagementDateTimeConverter]::ToDateTime($CMO.OS.LastBootUpTime)).ToString()
        UpTime = $Uptime
        dotNET = $dotNETkey.GetSubKeyNames() -join " | "
        UAC = "Enabled:$($UACkey.GetValue("EnableLUA")) | $($UACkey.GetValue("ConsentPromptBehaviorAdmin"))"
        #} | Select-Object Name,Domain,Platform,Cluster,OS,OSAct,CPU,RAM,RAMTotal,Storage,MountPoints,Network,PersRoutes,TimeZone,Locale,CountryCode,LastBoot,UpTime,PageFiles,dotNET,UAC,McAfeeVSEVersion,McAfeeEngineVersion,McAfeeDatVersion,McAfeeDatDate
		} | Select-Object Name,Domain,Platform,Cluster,OS,OSAct,CPU,RAM,TotalRAM,Storage,MountPoints,Network,PersRoutes,TimeZone,Locale,CountryCode,LastBoot,UpTime,PageFiles,dotNET,UAC
    IF(!$NoClip){($outObj | Out-String).Trim() | clip}
    return $outObj
}
##################################################################################################################################
$date_time = Get-Date -Format dd.MM.yyyy
$date_time+= " "
$date_time+= Get-Date -Format HH:mm:ss
$servers = Get-Content $serverlist -ea SilentlyContinue
IF (-Not $?) {
    Write-Host "=============================" -ForegroundColor Magenta
    Write-Host "!File $serverlist does not exist, screening will continue locally!" -ForegroundColor Yellow
    $servers = $env:COMPUTERNAME
    Write-Host "=============================" -ForegroundColor Magenta
}
    Write-Host "===============================================" -ForegroundColor Blue
    Write-Host "Server Pre-Migration Check Script" -ForegroundColor Yellow
    Write-Host "" -ForegroundColor White
    Write-Host "===============================================" -ForegroundColor Blue
    Write-Host "Current Date/Time: $date_time" -ForegroundColor Yellow
    Write-Host "===============================================" -ForegroundColor Blue
    do {
        do {
    Write-Host "===============================================" -ForegroundColor Blue
            write-host "Please select your ouptut type:" -ForegroundColor Cyan
            Write-Host ""
            write-host "T - Output to TXT -> $txt_output" -ForegroundColor White
            write-host "X - Output to XML -> $xml_output" -ForegroundColor White
            write-host "C - Output to CONSOLE" -ForegroundColor White
            write-host ""
            write-host "E - Exit" -ForegroundColor White
            write-host ""
            Write-Host ""
            Write-Host "PLEASE NOTE: Files created before will be replaced with new ones!" -ForegroundColor Red
            Write-Host "If you need previous files, you can rename them before continue." -ForegroundColor Red
            Write-Host ""
            write-host -nonewline "Type your choice and press Enter: " -ForegroundColor White
            $choice = read-host
            write-host ""        
            $ok = $choice -match '^[TXCE]+$'
            if ( -not $ok) { write-host "Invalid selection" -ForegroundColor Red }
        } until ( $ok )
        switch -Regex ( $choice ) {
            "T" # FOR TEXT OUTPUT
            {
                Write-Output "---Server Pre-Migration check---" > $txt_output
                Write-Output "---Output Date/Time: $date_time---" >> $txt_output
                $num = 1
                foreach ($server in $servers) {
                    Write-Host "$num : $server"
                    $txt = screen $server
                    Write-Output "----------------------------" >> $txt_output
                    Write-Output "SERVER NAME: $server" >> $txt_output
                    Write-Output $txt >> $txt_output
                    $num++
                    Write-Host " - DONE" -ForegroundColor Green
                }
                Write-Output "-----------FINISHED------------" >> $txt_output
                Write-Output "UAC:" >> $txt_output
                Write-Output " - First value is if the UAC is Enabled(1) or Disabled(0)" >> $txt_output
                Write-Output " - Second value is for ConsentPromptBehaviorAdmin." >> $txt_output
                Write-Output "   - For more information click here: https://msdn.microsoft.com/en-us/library/cc232761.aspx." >> $txt_output
                Write-Output "---------INTERNAL USE----------" >> $txt_output
                Write-Output "--Server check script" >> $txt_output
                Write-Output ""
                Write-Output ""
            }
            "C" # FOR Console OUTPUT
            {
                Clear-Host
                Write-Host "---Server Pre-Migration check---" -ForegroundColor White
                Write-Host "---Output Date/Time: $date_time---" -ForegroundColor White
                $num = 1
                foreach ($server in $servers) {
                    Write-Host "----------------------------" -ForegroundColor Green
                    Write-Host "$num : $server"
                    screen $server
                    $num++
                }
                Write-Host "-----------FINISHED------------" -ForegroundColor Cyan
                Write-Host ""
                Write-Host ""
            }
            "X" # FOR XML OUTPUT
            {
            
                $num = 1
                Write-Output '' > $xml_output
                Write-Output "" >> $xml_output
                Write-Output "" >> $xml_output
                foreach ($server in $servers) {
                Write-Host "$num : $server"
                $xml = screen $server
                $servername = $xml.Name
                    Write-Output "" >> $xml_output
                        Write-Output "$server" >> $xml_output
                        Write-Output ""$xml.Domain"" >> $xml_output
                        Write-Output ""$xml.Platform"" >> $xml_output
                        Write-Output ""$xml.Cluster"" >> $xml_output
                        $sOS =Get-WmiObject -class Win32_OperatingSystem -ComputerName $server
                        foreach($sProperty in $sOS)
                            {
                               $ossp = $sProperty.ServicePackMajorVersion
                            }
                        Write-Output "$($xml.OS) SP$($ossp)" >> $xml_output
                        Write-Output ""$xml.CPU"" >> $xml_output
                        Write-Output ""$xml.RAM"" >> $xml_output
                        #Write-Output ""$xml.TotalRAM"" >> $xml_output
                        Write-Output ""$xml.dotNET"" >> $xml_output
                        Write-Output ""$xml.Storage"" >> $xml_output
                                $diskinfo = Get-WmiObject Win32_DiskDrive -ComputerName $server | % {
                                  $disk = $_
                                  $partitions = "ASSOCIATORS OF " +"{Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} " +"WHERE AssocClass = Win32_DiskDriveToDiskPartition"
                                  Get-WmiObject -ComputerName $server -Query $partitions | % {
                                    $partition = $_
                                    $drives = "ASSOCIATORS OF " +"{Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} " +"WHERE AssocClass = Win32_LogicalDiskToPartition"
                                    Get-WmiObject -ComputerName $server -Query $drives | % {
                                      New-Object -Type PSCustomObject -Property @{
                                        Disk        = $disk.DeviceID
                                        DiskSize    = $disk.Size
                                        DiskModel   = $disk.Model
                                        Partition   = $partition.Name
                                        RawSize     = $partition.Size
                                        DriveLetter = $_.DeviceID
                                        VolumeName  = $_.VolumeName
                                        Size        = $_.Size
                                        FreeSpace   = $_.FreeSpace
                                      } 
                                    }
                                  }
                                }
                                $b=0
                                foreach ($hdd in $diskinfo) {
                                    $b++
                                    $driveletter=$hdd.DriveLetter
                                    $size=$hdd.Size
                                    $freespace=$hdd.FreeSpace
                                    $disksize=$hdd.DiskSize
                                    $driveSize = ([math]::Round($size / 1GB, 1))
                                    $diskSize = ([math]::Round($disksize / 1GB, 1))
                                    $driveFree = ([math]::Round(($freespace / $Size)*100, 1))
                                    Write-Output "$driveletter $diskSize GB / $driveFree% Free" >> $txt_output #$xml_output | 
                                }
                        $ip = get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $server | Where {$_.IPAddress.length -gt 0}
                        IF ($?) {
                            $a = 0
                            foreach ($ipaddress in $ip) {
                                $a++
                                $ip="IP=$($ipaddress.IPAddress -join "`n") `n"
                                IF ($ipaddress.DefaultIPGateway){$ip+="GW=$($ipaddress.DefaultIPGateway -join "`n") `n"}
                                IF ($ipaddress.MacAddress){$ip+="MAC=$($ipaddress.MacAddress -join "`n") `n"}
                                IF($ipaddress.DNSServerSearchOrder){$ip+="DNS=$($ipaddress.DNSServerSearchOrder -join "`n")"}
                                Write-Output "$ip" >> $xml_output
                            }
                        }
                        Write-Output ""$xml.TimeZone"" >> $xml_output
                        Write-Output ""$xml.Locale"" >> $xml_output
                        Write-Output ""$xml.PageFiles"" >> $xml_output
                        Write-Output ""$xml.LastBoot"" >> $xml_output
                        Write-Output ""$xml.Uptime.ToString()"" >> $xml_output
                        Write-Output ""$xml.UAC"" >> $xml_output
                    Write-Output "" >> $xml_output
                Write-Host " - DONE" -ForegroundColor Green
                $num++
                }
                Write-Output "" >> $xml_output
                Write-Output "" >> $xml_output

            }
$LicenseInfo = Foreach ($ComputerName in (Get-Content '.\serverlist.txt')) { 
    $Temp = Get-CimInstance -ClassName SoftwareLicensingProduct -ComputerName $ComputerName | Select LicenseStatus,Name
    [PSCustomObject][Ordered]@{
        ComputerName = $ComputerName
        OSName       = $Temp.Name
        Licensed     = $Temp.LicenseStatus
    }
}

$LicenseInfo | FT -a 

$LicenseInfo | Export-Csv '.\LicenseInfo.csv' -NoType
cscript c:\windows\system32\slmgr.vbs /dli

Hello Sam,

Here is the problem I have running ciminstance. Some of the servers I’m gathering data from have PowerShell V2.0. I came across some different work around scripts that fix this issue but no success yet.

Thank you