Sorting column for HTML Report from PowerShell - powershell

How do I sort the "Online" column and Uptime column? I would like to show True at the top with the longest uptime at the top, followed by FALSE.
<#
.Synopsis
Query Uptime Details of servers.
.Description
This script helps you to get the uptime details of the servers. It also generates a HTML report
when -HTMLReport switch is used. The report contains the uptime details and a summary of how many
computers reachable and how many are not
.Parameter ComputerName
Computer name(s) for which you want to get the uptime details.
.Parameter HTMLReport
Generates a HTML report in c:\ drive with name uptimereport.html by default. You can override this by
specifying -HTMLFile parameter
.Parameter HTMLFile
Name of the file path where you want to store the report
.Example
Get-UptimeOfServers.ps1 -ComputerName Comp1, Comp2
Gets the Uptime of Comp1 and Comp2
.Example
Get-UptimeOfServers.ps1 -ComputerName Comp1, Comp2 -HTMLReport
Get the uptime of Comp1 and Comp2 and saves the report in HTML format
.Example
Get-Content c:\servers.txt | Get-UptimeOfServers.ps1 -HTMLReport
Get the uptime of computers listed in servers.txt and saves the report in HTML format
.Notes
NAME: Get-UptimeOfServers.ps1
AUTHOR: Sitaram Pamarthi
WEBSITE: http://techibee.com
#>
[cmdletbinding()]
param(
[parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$ComputerName = $env:computername,
[switch]$HTMLReport,
[string]$HTMLFile = "c:\Temp\Uptimereport.html"
)
begin{
if($HTMLReport) {
$Report = "
<html>
<head>
<title> Server Uptime Report </title>
</head>
<body>
<H1 Align=`"Center`"> <B>Server Uptime Report </B></H1>
<br>
<H3 Align=`"Center`"> Report Generated at $(Get-Date)</H3>
<table BORDER=`"1`" CELLPADDING=`"5`" Align=`"Center`">
<tr>
<td font-family: 'Calibri' BGColor=#98C6F3 Align=center><b>Server Name</b></td>
<td font-family: 'Calibri' BGColor=#98C6F3 Align=center><b>Online</b></td>
<td font-family: 'Calibri' BGColor=#98C6F3 Align=center><b>Uptime</b></td>
</tr>"
}
}
process {
$Count=0
$SuccessComps = 0
$UnreachableComps = 0
$FailedComps = 0
$FinalOutput = #()
foreach($Computer in $ComputerName) {
$Count++
$Computer = $Computer.Toupper()
$OutputObj = New-Object -TypeName PSobject
$OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer
$Status = 0
if(Test-Connection -Computer $Computer -count 1 -ea 0) {
$OutputObj | Add-Member -MemberType NoteProperty -Name IsOnline -Value "TRUE"
try {
$Boottime = (Get-WmiObject win32_operatingSystem -computer $Computer -ErrorAction stop).lastbootuptime
$Boottime = [System.Management.ManagementDateTimeconverter]::ToDateTime($BootTIme)
$Now = Get-Date
$span = New-TimeSpan $BootTime $Now
$Uptime = "{0} day(s), {1} hour(s), {2} min(s), {3} second(s)" -f $span.days, $span.hours, $span.minutes, $span.seconds
$OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value $Uptime
$Status=1
$SuccessComps++
} catch {
$OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value "FAILED TO GET"
$FailedComps++
}
} else {
$OutputObj | Add-Member -MemberType NoteProperty -Name IsOnline -Value "FALSE"
$OutputObj | Add-Member -MemberType NoteProperty -Name Uptime -Value ""
$UnreachableComps++
}
$FinalOutput +=$OutputObj
$OutputObj = $OutputObj
if($HTMLReport) {
if($Status) {
$BGColor="GreenYellow"
} else {
$BGColor="OrangeRed"
}
$IsOnline
$Report += " <TR>
<TD BGColor=$BGColor>$($OutputObj.ComputerName)</TD>
<TD BGColor=$BGColor>$($OutputObj.IsOnline)</TD>
<TD BGColor=$BGColor>$($OutputObj.Uptime)</TD>
</TR>"
} else {
$OutputObj
}
}
}
end{
if($HTMLReport) {
$Report +=
$Report | Out-File $HTMLFile -Force
}
}

I think Sort-Object will help you out.
$FinalOutput | Sort-Object IsOnline,uptime -descending
Version 2 you can put span field into
$FinalOutput | sort-Object IsOnline,span -descending | Select-Object ComputerName,IsOnline,Uptime

Related

Update PowerShell Script to Check Remote Services

I am working on a server validation script that runs via PowerShell, and reaches out to collect remote machine information (pulls the list of servers from a text file), such as server uptime and pending reboot. It takes the information, places it in a CSV file and posts it to a HTML (Results) document.
My ask: I'm trying to reach out to these servers (contained on the .txt file) to validate that certain services are in the running state, and if they are, post the status as 'Running' and if not (else), post as 'Not Running'.
Example of getting the list of servers:
$title = 'Important! Please Read'
$message = 'Is this validation going to run against production servers?'
$choice = #(
[System.Management.Automation.Host.ChoiceDescription]::new(
'&Yes', 'This will execute against Production servers' # => This is help message
)
[System.Management.Automation.Host.ChoiceDescription]::new(
'&No', 'This will execute against Non-Production servers' # => This is help message
)
)
$defaultCoice = 0 # => No
$userinput = $host.UI.PromptForChoice($title, $message, $choice, $defaultCoice)
$prodserverlist = if($userinput -eq 0) {
Get-Content '\\networkshare\PostPatchingValidation\ServerListProd.txt'
}
else {
Get-Content '\\networkshare\PostPatchingValidation\ServerListDev.txt'
}
Example of Check Uptime:
Function Uptime($comp){
function WMIDateStringToDate($Bootup) {
[System.Management.ManagementDateTimeconverter]::ToDateTime($Bootup)
}
$NameSpace = "Root\CIMV2"
$wmi = [WMISearcher]""
$wmi.options.timeout = '0:0:10' #set timeout to 10 seconds
$query = 'Select * from Win32_OperatingSystem'
$wmi.scope.path = "\\$comp\$NameSpace"
$wmi.query = $query
Try{
$wmiresult = $wmi.Get()
#$wmiresult
foreach ($wmioutput in $wmiresult){
$Bootup = $wmioutput.LastBootUpTime
$LastBootUpTime = WMIDateStringToDate($Bootup)
$now = Get-Date
$Reporttime = $now - $lastBootUpTime
$d = $Reporttime.Days
$h = $Reporttime.Hours
$m = $Reporttime.Minutes
$a = "Up for: {0} Days, {1} Hours, {2:N0} Minutes" -f $d,$h,$m
return $a
}
}
Example of Posting results to CSV:
foreach($comp in $prodserverlist){
$i++
$ErrorActionPreference = "SilentlyContinue"
Write-Progress -Activity "Server Health Check " -Status ("Checking Server : {0}" -f $comp) -PercentComplete ($i/$prodserverlist.count*100) -Id 0
$ErrorActionPreference = "Continue"
#region Var_Nulling :p
$autoservices= $null
$Reporttimestatus = $null
$service = $null;
$services = $null;
$totalfailednew = $null
#endregion
$Reporttimestatus = uptime -comp $comp
# $services = Get-Service -comp $comp
$pd = PendingReboot $comp
$newobj = $null
$newobj = new-object psobject
$newobj | add-member -membertype noteproperty -name "Server" -value $comp
$newobj | add-member -membertype noteproperty -name "Uptime" -value $Reporttimestatus #-PassThru
$newobj | add-member -membertype noteproperty -name "PendingReboot" -value $pd
$newobj | add-member -membertype noteproperty -name "ServiceCheck" -value $Reporttimestatus
$newobj | ConvertTo-Csv -NoTypeInformation | Out-File "\\networkshare\PostPatchingValidation\result.csv" -Append
$htmlserver = $newobj.Server
$htmluptime = $newobj.Uptime
$htmlpendingreboot = $newobj.PendingReboot
$htmlservicecheck = $newobj.ServiceCheck
$current = "
<tr bgcolor=#CCCCCC>
<td width='14%' align='center'>$htmlserver</td>
<td width='23%' align='center'>$htmluptime</td>
<td width='12%' align='center'>$htmlpendingreboot</td>
<td width='12%' align='center'></td>
</tr>
"
$total += $current
#$newobj | ConvertTo-html -Fragment
#$newobj | ConvertTo-html -Fragment -CssUri \\networkshare\PostPatchingValidation\Style.css | Out-File \\networkshare\PostPatchingValidation\result.html -Append
}
$HTMLEnd = #"
</div>
</body>
</html>
"#
$MainHtml= $html + $total + $HTMLEnd
$MainHtml | Out-File "\\networkshare\PostPatchingValidation\result.html"
Final Screenshot of HTML Document:

I want this powershell script output in special pop window?

Below code was in powershell that code is successfully executed but i want that output in special 'popup window'
$ComputerName = $s = $(Get-WmiObject Win32_Computersystem).name
foreach ($Computer in $ComputerName) {
if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
$Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer | ? {$_.IPEnabled}
foreach ($Network in $Networks) {
$IPAddress = $Network.IpAddress[0]
$SubnetMask = $Network.IPSubnet[0]
$DefaultGateway = $Network.DefaultIPGateway
$DNSServers = $Network.DNSServerSearchOrder
$OutputObj = New-Object -Type PSObject
$OutputObj | Add-Member -MemberType NoteProperty -Name IPAddress -Value $IPAddress
$OutputObj | Add-Member -MemberType NoteProperty -Name SubnetMask -Value $SubnetMask
$OutputObj | Add-Member -MemberType NoteProperty -Name Gateway -Value $DefaultGateway
$OutputObj | Add-Member -MemberType NoteProperty -Name DNSServers -Value $DNSServers
}
}
}
The most familiar data displayer in powershell is using the Out-gridview method:
You can do this if you want to go easy:
$ComputerName = $s = $(Get-WmiObject Win32_Computersystem).name
$Pop_Window = foreach ($Computer in $ComputerName) {
if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
$Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer | ? {$_.IPEnabled}
foreach ($Network in $Networks) {
$IPAddress = $Network.IpAddress[0]
$SubnetMask = $Network.IPSubnet[0]
$DefaultGateway = $Network.DefaultIPGateway
$DNSServers = $Network.DNSServerSearchOrder
$OutputObj | Add-Member -MemberType NoteProperty -Name IPAddress -Value $IPAddress
$OutputObj | Add-Member -MemberType NoteProperty -Name SubnetMask -Value $SubnetMask
$OutputObj | Add-Member -MemberType NoteProperty -Name Gateway -Value $DefaultGateway
$OutputObj | Add-Member -MemberType NoteProperty -Name DNSServers -Value $DNSServers
#output the object:
$OutputObj
}
}
}
$Pop_Window | Out-GridView
If you want to design it on your way, This would be a difficult and a messy task to do in powershell, since you always will have to call System.Windows.Forms class and its sub classes like Labels,Buttons,Texts and more.

How do I include on certain values when summing from a powershell array?

I want to get a sum for the total space a SQL server is using for Data and Log files.
From a few other sources on the internet I have the following code: (Yes, I'm a Powershell Noob)
$servers = "SQLSERVER1"
$array = #()
foreach($server in $servers){
$sysinfo = Get-WmiObject Win32_Volume -ComputerName $server
for($i = 0;$i -lt $sysinfo.Count; $i++){
$sname = $sysinfo[$i].SystemName
$servername = $server
$label = $sysinfo[$i].Label
if(($label) -and (!($label.Contains("FILLER")))){
write-host "Processing $label from $server"
$name = $sysinfo[$i].Name
$capacity = [math]::round(($sysinfo[$i].Capacity/1GB),2)
$fspace = [math]::round(($sysinfo[$i].FreeSpace/1GB),2)
$sused = [math]::round((($sysinfo[$i].Capacity - $sysinfo[$i].FreeSpace)/1GB),2)
$fspacepercent = [math]::Round((($sysinfo[$i].FreeSpace*100)/$sysinfo[$i].Capacity),2)
$obj = New-Object PSObject
$obj | Add-Member -MemberType NoteProperty -Name "ServerName" -Value $server
$obj | Add-Member -MemberType NoteProperty -Name "Label" -Value $label
$obj | Add-Member -MemberType NoteProperty -Name "Name" -Value $name
$obj | Add-Member -MemberType NoteProperty -Name "Used(GB)" -Value $sused
$array += $obj
}
}
$array += write-output " "
$totalSize = ($array | Measure-Object 'Used(GB)' -Sum).Sum
$array += $totalsize
$array += write-output " "
}
$totalsize
This gives me the result of:
Processing Recovery from SQL-Group1-DB
Processing System from SQL-Group1-DB
Processing SQLInstall from SQL-Group1-DB
Processing OCTOPUS from SQL-Group1-DB
Processing SQL_DATA from SQL-Group1-DB
Processing SQL_LOG from SQL-Group1-DB
Processing TEMP_DB from SQL-Group1-DB
Processing SSS_X64FREV_EN-US_DV9 from SQL-Group1-DB
274.92
Of course that has included EVERY drive on the server.
I only want the SQL_DATA and SQL_LOG drives included.
Any ideas on how to achieve this?
(Happy to use entirely different code if it works)
TIA
If you do not want the info for all drives on the server, you could limit the results of the Get-WmiObject cmdlet in the $sysinfo variable by using a Where-Object{} clause like:
$sysinfo = Get-WmiObject Win32_Volume -ComputerName $server |
Where-Object { 'SQL_DATA', 'SQL_LOG' -contains $_.Label }

Issue with foreach loop (Combining Commands)

The script below works out great for identifying licensing for each individual host across multiple vCenters. What I am trying to include is the tag for each host as well. When I run the command individually it works fine, however when I run it as part of the code it is not functioning correctly. I highlighted the section if anyone can please take a look thanks. The line of code with the issue is commented out within the script below.
I attempted pushing this into a variable outside and insideof the foreach loop but I am receiving either 0 output, or the same output across each object.
Below is the actual command I put inside the foreach loop which is not functional.
(Get-VMhost | where{$_.Category -like "*Host*"})
$sw = [Diagnostics.Stopwatch]::StartNew()
# Declare our list of vCenters
[array]$vclistall = "vcenter01"
# Ensure were not connected to any vcenters
if ($DefaultVIServer.Count -gt 0) {
Disconnect-VIServer * -Confirm:$false -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Force:$true > $null
}
[array]$report = $null
foreach ($ScriptVCInstance in $vclistall) {
$connection = Connect-VIServer $ScriptVCInstance -ErrorAction SilentlyContinue
if ($connection) {
Write-Host "Collecting License Assets on vCenter $($ScriptVCInstance)"
# Get the license manager assets
$LicenseManager = Get-view LicenseManager
$LicenseAssignmentManager = Get-View $LicenseManager.LicenseAssignmentManager
$licenses = $LicenseAssignmentManager.GetType().GetMethod("QueryAssignedLicenses").Invoke($LicenseAssignmentManager, #($null))
#Format the asset into an object
foreach ($license in $Licenses) {
$object = New-Object -TypeName PSObject
$object | Add-Member -MemberType NoteProperty -Name "vCenter" -Value $($connection.name)
$object | Add-Member -MemberType NoteProperty -Name "Entity" -Value $($license.EntityDisplayName)
$object | Add-Member -MemberType NoteProperty -Name "Display Name" -Value $($license.Properties | where{$_.Key -eq 'ProductName'} | select -ExpandProperty Value)
$object | Add-Member -MemberType NoteProperty -Name "Product Version" -Calue $($License.Properties | where{$_.Key -eq 'FileVersion'} | select -ExpandProperty Value)
$object | Add-Member -MemberType NoteProperty -Name "License" -Value $($license.AssignedLicense.LicenseKey)
$object | Add-Member -MemberType NoteProperty -Name "License Name" -Value $($license.AssignedLicense.Name)
$object | Add-Member -MemberType NoteProperty -Name "Cost Unit" -Value $($license.Properties | where{$_.Key -eq 'CostUnit'} | select -ExpandProperty Value)
$object | Add-Member -MemberType NoteProperty -Name "Used License" -Value $($license.Properties | where{$_.Key -eq 'EntityCost'} | select -ExpandProperty Value)
$object | Add-Member -MemberType NoteProperty -Name "Total Licenses" -Value $($license.AssignedLicense.Total)
# Issue--> $object | Add-Member -MemberType NoteProperty -Name "Tag" -Value $(Get-VMhost | where{$_.Category -like "*Host*"})
$report += $object
if ($DefaultVIServer.Count -gt 0) {
Disconnect-VIServer * -Confirm:$false -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Force:$true > $null
}
} #end foreach $license
} else { # Else for if $connection
Write-warning "Not connected to vCenter $($ScriptVCInstance)"
} # endif $connection
} # End foreach $ScriptVCInstance
# write-out as a CSV file
Write-host "Exporting CSV $($env:USERPROFILE)\Licensed-Assets.csv"
$report | Sort-object "vCenter","License","Entity" | Export-csv "$($env:USERPROFILE)\Licensed-Assets.csv" -NoTypeInformation -UseCulture
$sw.Stop()
$sw.Elapsed

Function to return information in a custom object

I have a function that iterates through all HDD's on a computer, and returns information about those drives and their mapping to physical drives in an array.
I would like this function to return the information in a custom object.
Here is the function:
##--------------------------------------------------------------------------
## FUNCTION.......: Get-HDDInfo
## PURPOSE........:
## REQUIREMENTS...:
## NOTES..........:
##--------------------------------------------------------------------------
Function Get-HDDInfo {
[CmdletBinding()]
Param([Parameter(Mandatory = $True,
ValueFromPipeLine = $True,
Position = 0)]
[String[]]$ComputerName
)#END: Param
$W32_DD = #(gwmi Win32_DiskDrive -ComputerName $ComputerName)
$Array = #()
$W32_DD | foreach {
$query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" `
+ $_.DeviceID + "'} WHERE ResultClass=Win32_DiskPartition"
$Array += $_.Name
$Array += $_.Model
<#
$obj = New-Object PSObject
$obj.PSObject.typenames.insert(0,'JoeIT.Custom.SystemInfo')
$obj | Add-Member -MemberType NoteProperty -Name `
"PDCaption" -Value $_.Name
$obj | Add-Member -MemberType NoteProperty -Name `
"PDModel" -Value $_.Model
$Array += $obj
#>
Get-WmiObject -Query $query | foreach {
$Array += $_.Name
$Array += $_.Description
$Array += $_.PrimaryPartition
#$obj = New-Object PSObject
<#
$obj.PSObject.typenames.insert(0,'JoeIT.Custom.SystemInfo')
$obj | Add-Member -MemberType NoteProperty -Name `
"DPName" -Value $_.Name
$obj | Add-Member -MemberType NoteProperty -Name `
"DPDescription" -Value $_.Description
$obj | Add-Member -MemberType NoteProperty -Name `
"DPPrimary" -Value $_.PrimaryPartition
#>
$query2 = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" `
+ $_.DeviceID + "'} WHERE ResultClass=Win32_LogicalDisk"
Get-WmiObject -Query $query2 | ForEach {
$Array+= $_.Name
$Used = [math]::round($_.Size/1024/1024/1024,0)
$Free = [math]::round($_.FreeSpace/1024/1024/1024,0)
$Array += [String]$Used +"GB"
$Array += [String]$Free +"GB"
#Return $Array;
#$Array = $Null
}
<#
$Array += $obj
$obj = $Null
#>
}#END: Get-WmiObject -Query
}#END: $W32_DD | foreach
##----------------------------------------------------------------------
## Store results in custom Object
##----------------------------------------------------------------------
Return $Array
}#END: Function Get-HDDInfo
The stuff that is commented out is from my attempts to get the information into a custom object. Maybe I'm just a bit burnt out, but I just can't seem to make this work right. As you see it, the commented out code tries to overwrite named properties - I knew that when I wrote it, but for some reason I expected it to work anyway ;)
Maybe I shouldn't work three weeks without a day off, but my brain just isn't letting me solve this problem.
What I want is to be able to do something like this:
$test = (get-hddinfo $SVR01)
$test.PhysicalDrive1
$test.Partition1
$test.DriveLetter1
$test.TotalSize1
$test.FreeSpace1
This would query a computer named SVR01, and write out the first physical HDD, the first logical partition of that drive, the assigned drive letter, total size of the disk, and free space on the disk.
I could then do something like
$test.PhysicalDrive2
$(same code here for the second physical drive)
What the hell am I doing wrong?
Try this:
[CmdletBinding()]
Param([Parameter(Mandatory = $True,
ValueFromPipeLine = $True,
Position = 0)]
[String[]]$ComputerName
)
$W32_DD = #(gwmi Win32_DiskDrive -ComputerName $ComputerName)
$a = new-object System.Object
$sc3 = 1
$sc2 = 1
$sc1 = 1
$W32_DD | foreach {
$query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" `
+ $_.DeviceID + "'} WHERE ResultClass=Win32_DiskPartition"
$a | Add-Member -type NoteProperty -name DiskDriveName$sc1 -value $_.Name
$a | Add-Member -type NoteProperty -name DiskDriveModel$sc1 -value $_.Model
Get-WmiObject -Query $query | foreach {
$a | Add-Member -type NoteProperty -name PartitionName$sc2 -value $_.Name
$a | Add-Member -type NoteProperty -name PartitionDescription$sc2 -value $_.Description
$a | Add-Member -type NoteProperty -name PrimaryPartition$sc2 -value $_.PrimaryPartition
$query2 = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" `
+ $_.DeviceID + "'} WHERE ResultClass=Win32_LogicalDisk"
Get-WmiObject -Query $query2 | ForEach {
$a | Add-Member -type NoteProperty -name LogicalDiskName$sc3 -value $_.Name
$Used = [math]::round($_.Size/1024/1024/1024,0)
$Free = [math]::round($_.FreeSpace/1024/1024/1024,0)
$a | Add-Member -type NoteProperty -name UsedSpace$sc3 -value $([String]$Used +"GB")
$a | Add-Member -type NoteProperty -name FreeSpace$sc3 -value $([String]$Free +"GB")
$sc3++
}
$sc2++
}
$sc1++
}
Return $a
Here is a way, it's not exactly what you want but it gives you a way to do it :
##--------------------------------------------------------------------------
## FUNCTION.......: Get-HDDInfo
## PURPOSE........:
## REQUIREMENTS...:
## NOTES..........:
##--------------------------------------------------------------------------
Function Get-HDDInfo
{
[CmdletBinding()]
Param([Parameter(Mandatory = $True, ValueFromPipeLine = $True, Position = 0)]
[String[]]$ComputerName)#END: Param
$W32_DD = #(gwmi Win32_DiskDrive -ComputerName $ComputerName)
$ArrayofPD = #()
foreach ($dd in $W32_DD)
{
$query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + $dd.DeviceID + "'} WHERE ResultClass=Win32_DiskPartition"
# create a new physical disc object
$PDobj = New-Object PSObject
$PDobj | Add-Member -MemberType NoteProperty -Name "PDCaption" -Value $dd.Name
$PDobj | Add-Member -MemberType NoteProperty -Name "PDModel" -Value $dd.Model
$ArrayofLD = #()
$diskParts = Get-WmiObject -Query $query
foreach ($diskPart in $diskParts)
{
# create a new logical disc object
$LDobj = New-Object PSObject
$LDobj | Add-Member -MemberType NoteProperty -Name "DPName" -Value $diskPart.Name
$LDobj | Add-Member -MemberType NoteProperty -Name "DPDescription" -Value $diskPart.Description
$LDobj | Add-Member -MemberType NoteProperty -Name "DPPrimary" -Value $diskPart.PrimaryPartition
$query2 = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + $diskPart.DeviceID + "'} WHERE ResultClass=Win32_LogicalDisk"
$LogicalDisk = Get-WmiObject -Query $query2
if ($LogicalDisk -ne $null)
{
$LDobj | Add-Member -MemberType NoteProperty -Name "LGName" -Value $LogicalDisk.Name
$Used = [math]::round($LogicalDisk.Size/1024/1024/1024,0)
$Free = [math]::round($LogicalDisk.FreeSpace/1024/1024/1024,0)
$LDobj | Add-Member -MemberType NoteProperty -Name "UsedSpace" -Value $([String]$Used +"GB")
$LDobj | Add-Member -MemberType NoteProperty -Name "FreeSpace" -Value $([String]$Free +"GB")
}
$ArrayofLD += $LDobj
}
$PDobj | Add-Member -MemberType NoteProperty -Name "LogicalDisks" -Value $ArrayofLD
$ArrayofPD += $PDobj
}
##----------------------------------------------------------------------
## Store results in custom Object
##----------------------------------------------------------------------
Return $ArrayofPD
}#END: Function Get-HDDInfo
Clear-Host
$a = Get-HDDInfo localhost
$a
Dot source the function for me it gives :
PS C:\Users\JPB\Documents> $a = Get-HDDInfo localhost
PS C:\Users\JPB\Documents> $a
PDCaption PDModel LogicalDisks
--------- ------- ------------
\\.\PHYSICALDRIVE0 ST9500420AS {#{DPName=Disque n° 0, partition n° 0; DPD...
\\.\PHYSICALDRIVE1 ST932042 3AS USB Device {#{DPName=Disque n° 1, partition n° 0; DPD...
And :
PS C:\Users\JPB\Documents> $a[0].LogicalDisks
DPName DPDescription DPPrimary
------ ------------- ---------
Disque n° 0, partition n° 0 Système de fichiers installable True
Disque n° 0, partition n° 1 Système de fichiers installable True