I want this powershell script output in special pop window? - powershell

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.

Related

If Else Loop not working in Powershell Inventory Script

Note – I am not a coding expert so please be gentle 😊 Any assistance/guidance much appreciated
Issue is that my pieced together Powershell script is not working as correctly. I am guessing it will take a coding guru two seconds to help resolve.
The basics of the script is that it performs a basic audit of a list of servers from a text file and outputs the results to a csv. For each server it will test WMI connection and if successful will collect columns of data i.e Name, IP Address, Uptime etc. If WMI connection fails then it should just log a few columns of data i.e. WMI Result, Ping Result etc All results should be piped to the same single output csv
The script works perfectly if the first server in the list’s WMI connection succeeds. All 16 x columns of csv output file are populated for every server in list.
WorkingExample
If the first server in the list’s WMI connection fails then the output fails. Only 4 x columns of csv output file are populated for every server in list.
FailingExample
Hopefully the screenshots of the output csv's help
Powershell Code below
<#
.DESCRIPTION - Auditing Script - Construction Phase !!!
- Create folder called 'Audit' under C:\Temp
- Create text file called 'Servers.txt' and place in newly created C:\Temp\Audit folder
- Servers.txt should contain a list of server names you wish to audit\target
.Author MCD
#>
########## Output Folder ##########
$outputFolderName = 'Audit ' + $(Get-Date -f dd-MM-yyyy)
$outputpath = "C:\temp\Audit\$outputFolderName"
If(!(test-path $outputpath))
{
New-Item -ItemType Directory -Force -Path $outputpath | out-null
}
########## Prompt 1 ##########
Add-Type -AssemblyName Microsoft.VisualBasic
$ClientName = [Microsoft.VisualBasic.Interaction]::InputBox('Please enter Client\Customer name i.e. Contoso Ltd', 'User')
Start-Sleep -s 2
#Manual Input File Location
$computers = Get-Content -path c:\temp\audit\Servers.txt
########## Create an Empty Array ##########
$report = #()
########## Main Start ##########
Foreach ($Computer in $Computers)
{
########## WMI/Ping Test ##########
$wmi = gwmi win32_bios -ComputerName $computer -ErrorAction SilentlyContinue
$Ping = Test-Connection -ComputerName $computer -Quiet -count 2
########## Main If Else Loop ##########
if ($wmi)
{
$WMIResult = 'Server IS Contactable'
########## HW/Serial No/Bios ##########
$Bios = Get-WmiObject -Class win32_bios -ComputerName $Computer
$systemBios = $Bios.serialnumber
$Hardware = Get-WmiObject -Class Win32_computerSystem -ComputerName $Computer
########## OS Version/Last Reboot ##########
$OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer
$lastBoot = $OS.ConvertToDateTime($OS.LastBootUpTime)
$uptimeDays = ((get-date) - ($os.ConvertToDateTime($os.lastbootuptime))).Days
########## Network Info ##########
$Networks = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $Computer | Where-Object {$_.IPEnabled}
$IPAddress = ($Networks.IpAddress | where {$_ -notmatch ":"}) -join "`n"
$MACAddress = ($Networks.MACAddress) -join "`n"
$IpSubnet = ($Networks.IpSubnet | ? { $_ -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' }) -join "`n"
$DefaultGateway = ($Networks.DefaultIPGateway) -join "`n"
########## LastLogon/Created ##########
$LastLogonDate = Get-ADComputer $computer -Properties * | select -ExpandProperty LastLogonDate
$Created = Get-ADComputer $computer -Properties * | select -ExpandProperty Created
########## OUTPUT ##########
$tempreport = New-Object -TypeName PSObject
$tempreport | Add-Member -MemberType NoteProperty -Name ServerName -Value $Computer.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name Client_Customer -Value $ClientName.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name WMI_Connection -Value $WMIResult
$tempreport | Add-Member -MemberType NoteProperty -Name Pingable -Value $Ping
$tempreport | Add-Member -MemberType NoteProperty -Name Manufacturer -Value $Hardware.Manufacturer
$tempreport | Add-Member -MemberType NoteProperty -Name Model -Value $Hardware.Model
$tempreport | Add-Member -MemberType NoteProperty -Name Operating_System -Value $OS.Caption
$tempreport | Add-Member -MemberType NoteProperty -Name IP_Address -Value $IPAddress
$tempreport | Add-Member -MemberType NoteProperty -Name Default_Gateway -Value $DefaultGateway
$tempreport | Add-Member -MemberType NoteProperty -Name MAC_Address -Value $MACAddress
$tempreport | Add-Member -MemberType NoteProperty -Name IpSubnet -Value $IpSubnet
$tempreport | Add-Member -MemberType NoteProperty -Name Last_ReBoot -Value $lastboot
$tempreport | Add-Member -MemberType NoteProperty -Name Uptime_Days -Value $uptimeDays
$tempreport | Add-Member -MemberType NoteProperty -Name Last_Logon -Value $LastLogonDate
$tempreport | Add-Member -MemberType NoteProperty -Name Created -Value $Created
$tempreport | Add-Member -MemberType NoteProperty -Name Serial_Number -Value $systemBios
$report += $tempreport
} else {
$WMIResult = 'Server NOT Contactable'
$tempreport = New-Object PSObject
$tempreport | Add-Member -MemberType NoteProperty -Name ServerName -Value $Computer.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name Client_Customer -Value $ClientName.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name WMI_Connection -Value $WMIResult
$tempreport | Add-Member -MemberType NoteProperty -Name Pingable -Value $Ping
$report += $tempreport
}
}
########## EXPORT TO CSV ##########
$CSVFileName = $ClientName + ' Server Inventory ' + $(Get-Date -f dd-MM-yyyy) + '.csv'
$report | Export-Csv "$outputpath\$CSVFileName" -NoTypeInformation
<#
.END
#>
The issue is that the two objects you are creating don't contain the same properties. Arrays will report the information based on the properties in the first object. So if the first object fails, then all the others will report back the same four properties when the array is output.
My suggestion for dealing with this in the most simple way is to add the additional properties to the failing object, setting the values as $null. This should see that your CSV receives all the properties as intended.
<#
.DESCRIPTION - Auditing Script - Construction Phase !!!
- Create folder called 'Audit' under C:\Temp
- Create text file called 'Servers.txt' and place in newly created C:\Temp\Audit folder
- Servers.txt should contain a list of server names you wish to audit\target
.Author MCD
#>
########## Output Folder ##########
$outputFolderName = 'Audit ' + $(Get-Date -f dd-MM-yyyy)
$outputpath = "C:\temp\Audit\$outputFolderName"
If(!(test-path $outputpath)) {
New-Item -ItemType Directory -Force -Path $outputpath | out-null
}
########## Prompt 1 ##########
Add-Type -AssemblyName Microsoft.VisualBasic
$ClientName = [Microsoft.VisualBasic.Interaction]::InputBox('Please enter Client\Customer name i.e. Contoso Ltd', 'User')
Start-Sleep -s 2
#Manual Input File Location
$computers = Get-Content -path c:\temp\audit\Servers.txt
########## Create an Empty Array ##########
$report = #()
########## Main Start ##########
Foreach ($Computer in $Computers) {
########## WMI/Ping Test ##########
$wmi = gwmi win32_bios -ComputerName $computer -ErrorAction SilentlyContinue
$Ping = Test-Connection -ComputerName $computer -Quiet -count 2
########## Main If Else Loop ##########
if ($wmi) {
$WMIResult = 'Server IS Contactable'
########## HW/Serial No/Bios ##########
$Bios = Get-WmiObject -Class win32_bios -ComputerName $Computer
$systemBios = $Bios.serialnumber
$Hardware = Get-WmiObject -Class Win32_computerSystem -ComputerName $Computer
########## OS Version/Last Reboot ##########
$OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer
$lastBoot = $OS.ConvertToDateTime($OS.LastBootUpTime)
$uptimeDays = ((get-date) - ($os.ConvertToDateTime($os.lastbootuptime))).Days
########## Network Info ##########
$Networks = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $Computer | Where-Object {$_.IPEnabled}
$IPAddress = ($Networks.IpAddress | where {$_ -notmatch ":"}) -join "`n"
$MACAddress = ($Networks.MACAddress) -join "`n"
$IpSubnet = ($Networks.IpSubnet | ? { $_ -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' }) -join "`n"
$DefaultGateway = ($Networks.DefaultIPGateway) -join "`n"
########## LastLogon/Created ##########
$LastLogonDate = Get-ADComputer $computer -Properties * | select -ExpandProperty LastLogonDate
$Created = Get-ADComputer $computer -Properties * | select -ExpandProperty Created
########## OUTPUT ##########
$tempreport = New-Object -TypeName PSObject
$tempreport | Add-Member -MemberType NoteProperty -Name ServerName -Value $Computer.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name Client_Customer -Value $ClientName.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name WMI_Connection -Value $WMIResult
$tempreport | Add-Member -MemberType NoteProperty -Name Pingable -Value $Ping
$tempreport | Add-Member -MemberType NoteProperty -Name Manufacturer -Value $Hardware.Manufacturer
$tempreport | Add-Member -MemberType NoteProperty -Name Model -Value $Hardware.Model
$tempreport | Add-Member -MemberType NoteProperty -Name Operating_System -Value $OS.Caption
$tempreport | Add-Member -MemberType NoteProperty -Name IP_Address -Value $IPAddress
$tempreport | Add-Member -MemberType NoteProperty -Name Default_Gateway -Value $DefaultGateway
$tempreport | Add-Member -MemberType NoteProperty -Name MAC_Address -Value $MACAddress
$tempreport | Add-Member -MemberType NoteProperty -Name IpSubnet -Value $IpSubnet
$tempreport | Add-Member -MemberType NoteProperty -Name Last_ReBoot -Value $lastboot
$tempreport | Add-Member -MemberType NoteProperty -Name Uptime_Days -Value $uptimeDays
$tempreport | Add-Member -MemberType NoteProperty -Name Last_Logon -Value $LastLogonDate
$tempreport | Add-Member -MemberType NoteProperty -Name Created -Value $Created
$tempreport | Add-Member -MemberType NoteProperty -Name Serial_Number -Value $systemBios
$report += $tempreport
}
else {
$WMIResult = 'Server NOT Contactable'
$tempreport = New-Object PSObject
$tempreport | Add-Member -MemberType NoteProperty -Name ServerName -Value $Computer.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name Client_Customer -Value $ClientName.ToUpper()
$tempreport | Add-Member -MemberType NoteProperty -Name WMI_Connection -Value $WMIResult
$tempreport | Add-Member -MemberType NoteProperty -Name Pingable -Value $Ping
$tempreport | Add-Member -MemberType NoteProperty -Name Manufacturer -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Model -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Operating_System -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name IP_Address -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Default_Gateway -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name MAC_Address -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name IpSubnet -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Last_ReBoot -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Uptime_Days -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Last_Logon -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Created -Value $null
$tempreport | Add-Member -MemberType NoteProperty -Name Serial_Number -Value $null
$report += $tempreport
}
}
########## EXPORT TO CSV ##########
$CSVFileName = $ClientName + ' Server Inventory ' + $(Get-Date -f dd-MM-yyyy) + '.csv'
$report | Export-Csv "$outputpath\$CSVFileName" -NoTypeInformation

The term 'Win32_computerSystem' is not recognized as the name of a cmdlet

I'm fairly new to Powershell scripting and have been playing around with a script I found online which queries all the systems in my domain and outputs bits of hardware information in a CSV. The script:
$testcomputers = Get-Content -Path 'C:\scripts\computers.txt'
$exportLocation = 'C:\scripts\pcInventory.csv'
foreach ($computer in $testcomputers) {
if (Test-Connection -ComputerName $computer -Quiet -count 2){
Add-Content -value $computer -path c:\scripts\livePCs.txt
}else{
Add-Content -value $computer -path c:\scripts\deadPCs.txt
}
}
$computers = Get-Content -Path 'C:\scripts\livePCs.txt'
foreach ($computer in $computers) {
$Bios = Win32_computerSystem -Computername $Computer
$Sysbuild = Get-WmiObGet-WmiObject win32_bios -Computername $Computer
$Hardware = Get-WmiObjectject Win32_WmiSetting -Computername $Computer
$OS = Get-WmiObject Win32_OperatingSystem -Computername $Computer
$Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer | Where-Object {$_.IPEnabled}
$driveSpace = Get-WmiObject win32_volume -computername $Computer -Filter 'drivetype = 3' |
Select-Object PScomputerName, driveletter, label, #{LABEL='GBfreespace';EXPRESSION={'{0:N2}' -f($_.freespace/1GB)} } |
Where-Object { $_.driveletter -match 'C:' }
$cpu = Get-WmiObject Win32_Processor -computername $computer
$username = Get-ChildItem "\\$computer\c$\Users" | Sort-Object LastWriteTime -Descending | Select-Object Name, LastWriteTime -first 1
$totalMemory = [math]::round($Hardware.TotalPhysicalMemory/1024/1024/1024, 2)
$lastBoot = $OS.ConvertToDateTime($OS.LastBootUpTime)
$IPAddress = $Networks.IpAddress[0]
$MACAddress = $Networks.MACAddress
$systemBios = $Bios.serialnumber
$OutputObj = New-Object -Type PSObject
$OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper()
$OutputObj | Add-Member -MemberType NoteProperty -Name Manufacturer -Value $Hardware.Manufacturer
$OutputObj | Add-Member -MemberType NoteProperty -Name Model -Value $Hardware.Model
$OutputObj | Add-Member -MemberType NoteProperty -Name Processor_Type -Value $cpu.Name
$OutputObj | Add-Member -MemberType NoteProperty -Name System_Type -Value $Hardware.SystemType
$OutputObj | Add-Member -MemberType NoteProperty -Name Operating_System -Value $OS.Caption
$OutputObj | Add-Member -MemberType NoteProperty -Name Operating_System_Version -Value $OS.version
$OutputObj | Add-Member -MemberType NoteProperty -Name Operating_System_BuildVersion -Value $SysBuild.BuildVersion
$OutputObj | Add-Member -MemberType NoteProperty -Name Serial_Number -Value $systemBios
$OutputObj | Add-Member -MemberType NoteProperty -Name IP_Address -Value $IPAddress
$OutputObj | Add-Member -MemberType NoteProperty -Name MAC_Address -Value $MACAddress
$OutputObj | Add-Member -MemberType NoteProperty -Name Last_User -Value $username.Name
$OutputObj | Add-Member -MemberType NoteProperty -Name User_Last_Login -Value $username.LastWriteTime
$OutputObj | Add-Member -MemberType NoteProperty -Name C:_FreeSpace_GB -Value $driveSpace.GBfreespace
$OutputObj | Add-Member -MemberType NoteProperty -Name Total_Memory_GB -Value $totalMemory
$OutputObj | Add-Member -MemberType NoteProperty -Name Last_ReBoot -Value $lastboot
$OutputObj | Export-Csv $exportLocation -Append -NoTypeInformation
}
When I run the script, I get the errors below and not quite sure how to address them. I've also noticed that the line supposed to output the system's RAM always outputs 0. Any guidance would be much appreciated. I'm running Powershell 3 on Windows 7 if that makes any difference.
Win32_computerSystem : The term 'Win32_computerSystem' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
Get-WmiObGet-WmiObject : The term 'Get-WmiObGet-WmiObject' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
Get-WmiObjectject : The term 'Get-WmiObjectject' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
Syntax errors
Line 15:
$Bios = Win32_computerSystem -Computername $Computer
You forgot to prefix Win32_ComputerSystem with Get-WmiObject. It's attempting to run Win32_ComputerSystem as a command, not evaluate a WMI class. To fix it, change the line to look like this:
$Bios = Get-WmiObject Win32_ComputerSystem -ComputerName $Computer
Line 16:
$Sysbuild = Get-WmiObGet-WmiObject win32_bios -Computername $Computer
There is no cmdlet called Get-WmiObGet-WmiObject. Change it to Get-WmiObject:
$Sysbuild = Get-WmiObject Win32_Bios -ComputerName $Computer
Line 17:
$Hardware = Get-WmiObjectject Win32_WmiSetting -Computername $Computer
This is another typo when trying to call Get-WmiObject. Correct the mispelling and it should work:
$Hardware = Get-WmiObject Win32_WmiSetting -ComputerName $Computer
Why your RAM is always zero
Simply put, you're using the wrong WMI class when you set $Hardware. You can get the physical memory information from the Win32_PhysicalMemory class. Replace line 17 with:
$Hardware = Get-WmiObject Win32_PhysicalMemory -ComputerName $Computer
and when you get the $totalRam, you can use the following calculation:
$totalRamBytes = 0
$Hardware.Capacity | Foreach-Object { $totalRamBytes += $_ }
$totalRamGb = $totalRamBytes / 1GB

How to get name and in a sequence in Powershell

When I run the below code I get an error with Model Number in which the heading is not being displayed and one more thing is i am unable to get all the three of them in a sequence.
$arrComputers = get-Content -Path "C:\Desktop\Computers.txt"
$e=$arrComputers | ForEach-Object {Get-WMIObject -Class Win32_BIOS -ComputerName $_ } |Select PSComputerName, Version,Manufacturer,Status,BIOSVersion,SerialNumber |ConvertTo-Html -fragment
$e2=$arrComputers |ForEach-Object { get-wmiobject -class Win32_logicaldisk -Filter "DeviceID = 'C:'" -ComputerName $_ } | select freeSpace,size | ConvertTo-Html -fragment
$e3=$arrComputers |ForEach-Object { get-wmiobject -class "Win32_ComputerSystem" -ComputerName $_ } | select Model| ConvertTo-Html -fragment
ConvertTo-HTML -Body "$e $e2 $e3" -Title "List of Computers" | Out-File C:\Users\Desktop\gf.html
Its a lot easier to make all of the WMI calls into a single object. It is much easier to handle formatting. I think I got everything that you were wanting:
function GetCompInfoWork
{
param (
[string]$computername,[string]$logfile
)
$pc = Get-WmiObject Win32_ComputerSystem -ComputerName $computername
$bios = Get-WmiObject win32_bios -ComputerName $computername
$disk = Get-WmiObject win32_logicalDisk -Filter "DeviceID= 'C:'" `
-computername $computername
$obj = New-Object -TypeName PSObject
$obj | Add-Member -MemberType NoteProperty `
-Name PSCompName -Value ($bios.PSComputerName)
$obj | Add-Member -MemberType NoteProperty `
-Name Version -Value ($bios.version)
$obj | Add-Member -MemberType NoteProperty `
-Name Manufacturer -Value ($bios.manufacturer)
$obj | Add-Member -MemberType NoteProperty `
-Name Status -Value ($bois.status)
$obj | Add-Member -MemberType NoteProperty `
-Name SerialNumber -Value ($bios.serialnumber)
$obj | Add-Member -MemberType NoteProperty `
-Name DiskSize -Value ($disk.size / 1GB -as [int])
$obj | Add-Member -MemberType NoteProperty `
-Name SysDriveFree -Value ($disk.freespace / 1GB -as [int])
$obj | Add-Member -MemberType NoteProperty `
-Name ComputerName -Value ($pc.model)
Write-Output $obj
}
function Get-CompInfo
{
param ([string[]]$computername,[string]$logfile )
BEGIN
{
$usedParamater = $False
if ($PSBoundParameters.ContainsKey('computername')) {
$usedParamater = $True
}
}
PROCESS {
if ($usedParamater)
{
foreach ($computer in $computername)
{
Getcompinfowork -computername $computer `
-logfile $logfile
}
}
else
{
Getcompinfowork -computername $_ `
-logfile $logfile
}
}
END {}
}
Get-Content C:\Users\Kev\Desktop\computers.txt| Get-CompInfo | ConvertTo-Html | Out-File C:\Users\kev\Desktop\Output.html

No way to export tables in PowerShell?

OK, everything about PowerShell has been fantastic so far, but for something that is so great they sure made exporting results to files complicated as hell. Anyway, how can I get the Export $Results variable to a deliminated file so it can be imported to Excel?
Final script
[cmdletbinding()]
[cmdletbinding()]
param(
[parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$ComputerName = "HellBombs-PC"
)
begin {
$UninstallRegKey="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
}
process {
foreach($Computer in $ComputerName) {
Write-Verbose "Working on $Computer"
if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
$HKLM = [microsoft.win32.registrykey]::OpenRemoteBaseKey('LocalMachine',$computer)
$UninstallRef = $HKLM.OpenSubKey($UninstallRegKey)
$Applications = $UninstallRef.GetSubKeyNames()
foreach ($App in $Applications) {
$AppRegistryKey = $UninstallRegKey + "\\" + $App
$AppDetails = $HKLM.OpenSubKey($AppRegistryKey)
$AppGUID = $App
$AppDisplayName = $($AppDetails.GetValue("DisplayName"))
$AppVersion = $($AppDetails.GetValue("DisplayVersion"))
$AppPublisher = $($AppDetails.GetValue("Publisher"))
$AppInstalledDate = $($AppDetails.GetValue("InstallDate"))
$AppUninstall = $($AppDetails.GetValue("UninstallString"))
if(!$AppDisplayName) {
continue
}
$OutputObj = New-Object -TypeName PSobject
$OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper()
$OutputObj | Add-Member -MemberType NoteProperty -Name AppName -Value $AppDisplayName
$OutputObj | Add-Member -MemberType NoteProperty -Name AppVersion -Value $AppVersion
$OutputObj | Add-Member -MemberType NoteProperty -Name AppVendor -Value $AppPublisher
$OutputObj | Add-Member -MemberType NoteProperty -Name InstalledDate -Value $AppInstalledDate
$OutputObj | Add-Member -MemberType NoteProperty -Name UninstallKey -Value $AppUninstall
$OutputObj | Add-Member -MemberType NoteProperty -Name AppGUID -Value $AppGUID
$Result += #($OutputObj)
}
}
}
$Result | select -Property * | export-csv -notypeinformation -path Info.txt
}
end {}
Use export-csv.
Try:
$Result | select -Property * | export-csv -notypeinformation -append -path .\test.txt

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