Remove white spaces between commands output in powershell - powershell

I've got an script and I want to remove the white spaces that powershell puts by default in the output result. Is there any way of doing it?
=======Computer1=======
Microsoft Windows 8.1 Pro
Name : Computer1
Model : Vostro 200
Manufacturer : Dell Inc.
SerialNumber : 012345
This is what I want:
=======Computer1=======
Microsoft Windows 8.1 Pro
Name : Computer1
Model : Vostro 200
Manufacturer : Dell Inc.
SerialNumber : 012345
This is my script:
$Computers=Import-Csv C:\Powershell\test.csv
$ResultsPath="C:\Powershell\test.txt"
foreach ($i in $Computers.Name) {
"="*7 + $i + "="*7
if (Test-Connection $i -quiet) {
(Get-WmiObject -class Win32_OperatingSystem -ComputerName $i).Caption
Get-WmiObject -class Win32_Computersystem -ComputerName $i | Select-Object Name, Model, Manufacturer | Format-List
Get-WmiObject win32_SystemEnclosure -ComputerName $i | Select-Object SerialNumber | Format-List }
else { "nothing" }
}

While Trim will do what you need, this is not a PowerShell way. Here is revised script, that works with objects internally and writes output the way you want.
$Computers = Import-Csv 'C:\Powershell\test.csv'
$ResultsPath = 'C:\Powershell\test.txt'
foreach ($i in $Computers.Name) {
$Header = '='*7 + $i + '='*7
Write-Output $Header
if (Test-Connection $i -quiet)
{
$Os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $i | Select-Object -ExpandProperty Caption
$Info = Get-WmiObject -Class Win32_Computersystem -ComputerName $i | Select-Object Name, Model, Manufacturer
$Sn = Get-WmiObject -Class Win32_SystemEnclosure -ComputerName $i | Select-Object -ExpandProperty SerialNumber
$PC = New-Object -TypeName psobject -Property #{
OperatingSystem = $Os
Name = $Info.Name
Model = $Info.Model
Manufacturer = $Info.Manufacturer
SerialNumber = $Sn
} | Select-Object OperatingSystem, Name, Model, Manufacturer, SerialNumber
Write-Output ($PC | Format-List | Out-String).Trim()
}
else
{
Write-Output 'nothing'
}
}

Convert output to string and trim it:
"="*7 + $i + "="*7
if (Test-Connection $i -quiet) {
(Get-WmiObject -class Win32_OperatingSystem -ComputerName $i).Caption
(Get-WmiObject -class Win32_Computersystem -ComputerName $i | Select-Object Name, Model, Manufacturer | Format-List | Out-String).Trim()
(Get-WmiObject win32_SystemEnclosure -ComputerName $i | Select-Object SerialNumber | Format-List | Out-String).Trim() }
else { "nothing" }

Related

Format output in Powershell

I have a small code in my script that is working well. I'm just annoyed with the output..
My output looks like this:
11.11.111.123
Model
-----
HP ZBook Studio G5
csname : XXXXXXX
LastBootUpTime : 22/Apr/2022 08:10:57
But I want it like this:
IP Address: 11.11.111.123
Model: HP ZBook Studio G5
csname: xxxxx
LastBootUpTime: 22/Apr/2022 08:10:57
This is the script:
Get-WmiObject Win32_NetworkAdapterConfiguration -Computername $pcName |
Where { $_.IPAddress } |
Select -Expand IPAddress |
Where { $_ -like '10.11*' -or $_ -like '10.12*'}
Get-WmiObject -Class Win32_ComputerSystem -Computername $pcName | Select Model
Get-WmiObject win32_operatingsystem -Computername $pcName -ea stop | select csname, #{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}} | format-list
Since the output is produced by 3 different classes the way around it is create a new object to merge them:
$IPs = Get-CimInstance Win32_NetworkAdapterConfiguration -ComputerName $pcName |
Where-Object { $_.IPAddress -like '10.11*' -or $_.IPAddress -like '10.12*' }
$Model = (Get-CimInstance -Class Win32_ComputerSystem -ComputerName $pcName).Model
$OS = Get-CimInstance win32_operatingsystem -EA Stop -ComputerName $pcName
[pscustomobject]#{
'IP Address' = $IPs.IpAddress -join ', '
Model = $Model
csname = $OS.CSName
LastBootUpTime = $OS.LastBootUpTime.ToString()
}

i trying to collect different info with Get-ADComputer, Get-WmiObject and Get-windowsfeature

I am trying to collect different properties from all computer listed from my AD but I can't get format to recolected querys
I run get-adcomputer query
$computerList = Get-ADComputer -Filter 'Name -like "SCPW*" -and ObjectClass -eq "Computer"' | Select-Object -Property Name,objectClass`
I collect info from al computer listed in $computerlist
$list = foreach ($computer in $computerList) {Get-WmiObject -Class Win32_Product | Select-Object -Property Name }
$WFeature = foreach ($computer in $computerList) {Get-windowsfeature | Where {$_.installed -Eq $true} | Select-Object -Property Name}
$Wrole = foreach ($computer in $computerList) {Get-WmiObject -Class Win32_ServerFeature -Property * | select pscomputername,name }
Finally I try to list all info collected in a unique table with
%{[PSCustomObject]#{
'ComputerName' = $computer.Name
'features' = $WFeature.name
'Role' = $Wrole.name
'list' = $list.name
} } | Format-table
but the table listed is only in one line
ComputerName features Role list
------------ -------- ---- ----
SCPWEXC0101 {File-Services, FS-FileServer, Remote-Desktop-Services, RDS-RD-Server...} {Web Server (IIS), File Services, Print and Document Services, Remote Desktop Services...} {Microsoft Ap...
the table listed only in one line (screenshot)
I really will be much gratefull if somebody give me some help, I'm learning PS and I really lossed with this query. I've been running Ps 5.1
Thanks!!
You will have to put the queries inside a loop for each single computer to keep the correlation between the collected information and the computer name. Something like this should get you started:
$computerList = Get-ADComputer -Filter 'Name -like "SCPW*" -and ObjectClass -eq "Computer"'
$Result =
foreach ($computer in $computerList) {
$CimSession = New-CimSession -ComputerName $computer.name
[PSCustomObject]#{
ComputerName = $computer.Name
WindowsFeatureList = (Get-windowsfeature -ComputerName $computer.name | Where-Object { $_.installed } | Select-Object -Property Name) -join ', '
W32ServerFeatureList = (Get-CimInstance -CimSession $CimSession -ClassName Win32_ServerFeature | Select-Object -Property Name) -join ', '
W32ProductList = (Get-CimInstance -CimSession $CimSession -ClassName Win32_Product | Select-Object -Property Name) -join ', '
}
}
$Result

Variable is array instead of string?

I wrote this small script and when I test Write-Host $serial it appears fine, but when it is running in the background $serial seems to contain an array.
It tries to rename computer to C000#{SerialNumber=F7ZL3F2} instead of just C000F7ZL3F2.
What should I do to just get string not this array?
Import-Module ActiveDirectory
Get-ADComputer -Filter {Name -like 'DESKTOP-*'} -Properties * | Select Name, DNSHostName | ForEach-Object {
$rtn = Test-Connection -CN $_.dnshostname -Count 1 -BufferSize 16 -Quiet
if ($rtn -match 'True') {
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name | Select-String SerialNumber
$serial = "C000$serial"
// Write-Host $serial
Rename-Computer -ComputerName $_.name -NewName $serial -DomainCredential $mycreds -Force -Restart
}
}
There are two mistakes to be pointed out in your code -
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name | Select-String SerialNumber
The Select-String cmdlet searches for text and text patterns in input strings and files. Where as the basetype output of Get-WMIObject Win32_Bios is System.Management.ManagementBaseObject
(Get-WMIObject Win32_Bios).Gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True ManagementObject System.Management.ManagementBaseObject
In such cases, instead of Select-String, you can use Select-Object to choose amongst the properties. Since, Serial Number is one of the properties returned by your input command.
$serial = "C000$serial"
The output of $serial will be something like this:
SerialNumber
5CXXXXYYYXZZZ
Again, you can call it directly by $serial.SerialNumber. So your overall code will be
Import-Module ActiveDirectory
Get-ADComputer -Filter {Name -like 'DESKTOP-*'} -Properties * | Select Name, DNSHostName | ForEach-Object {
$rtn = Test-Connection -CN $_.dnshostname -Count 1 -BufferSize 16 -Quiet
if ($rtn -match 'True') {
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name |
Select-Object SerialNumber
$serial = "C000$($serial.SerialNumber)"
Rename-Computer -ComputerName $_.name -NewName $serial -DomainCredential $mycreds -Force -Restart
}
}
Or you can use -ExpandProperty parameter of the Select-Object cmdlet like
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name |
Select-Object -ExpandProperty SerialNumber
$serial = "C000$serial"
Try changing this line:
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name |
Select-String SerialNumber
to this:
$serial = (Get-WMIObject Win32_Bios -ComputerName $_.name).SerialNumber
or this:
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name |
Select-Object -ExpandProperty SerialNumber
Why are you using Select-String? I would use Select-Object and then -ExpandProperty
Import-Module ActiveDirectory
Get-ADComputer -Filter {Name -like 'DESKTOP-*'} -Properties * | Select Name, DNSHostName | ForEach-Object {
$rtn = Test-Connection -CN $_.dnshostname -Count 1 -BufferSize 16 -Quiet
if ($rtn -match 'True') {
$serial = Get-WMIObject Win32_Bios -ComputerName $_.name | Select-Object -ExpandProperty SerialNumber
$serial = "C000$serial"
// Write-Host $serial
Rename-Computer -ComputerName $_.name -NewName $serial -DomainCredential $mycreds -Force -Restart
}
}

How to extract server information

Objective: How to extract server information?
For each server name listed in servers.txt, I would like to get the following information (in this format):
Server name, IP Address, OS name, Total Physical Memory, Processors, each drive letter and size, System Model
Comma separated and new line for each server.
Below is my PowerShell code. Can your guys give a hint on why this does not work? Also why I get an error with New-Object statement?
foreach ($ComputerName in (Get-Content -Path .\servers.txt)) {
$HashProps = #{
'tHostname' = Get-WmiObject Win32_Computersystem -ComputerName $ComputerName | Select-Object -ExpandProperty Name
'tIP' = [System.Net.Dns]::GetHostAddresses($computername)
'tOS' = Get-WmiObject -ComputerName $ComputerName -Class Win32_OperatingSystem | Select-Object -ExpandProperty Caption
'tMemory' = Get-WmiObject Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | foreach { "$("{0:n2}" -f ( $_.Sum/1GB ) )" }
'tcpu' = Get-WmiObject Win32_processor | Select-Object name, numberofcores
'tDisks' = Get-WmiObject Win32_LogicalDisk | foreach { "$($_.DeviceID) $("{0:n2}" -f ( $_.Size/ 1GB ) )" }
'tsysmodel' = Get-Wmiobject Win32_computersystem | Select-Object model
}
New-Object -TypeName psObject -Property $HashProps |
ConvertTo-Csv -NoTypeInformation | Out-File -Append .\output.csv
}
I am open for a other approach, if this is easier.
Have you verified that each of those lines actually return what you want?
I just threw this into the ISE and it works fine:
$f = gwmi win32_computersystem | select name,model,totalphysicalmemory
$hash = #{
'name' = $f.name
'model' = $f.model
'memory' = $("{0:n2}" -f ( $f.totalphysicalmemory/1GB ) )
}
New-Object -TypeName psobject -Property $hash | ConvertTo-Csv -NoTypeInformation | Out-File -Append .\test.csv
Also, if you want the properties to appear in a specific order in the CSV, it will take some additional magic, otherwise they're put in alphabetically.
A little bit pimped, maybe this will help you:
$Servers = Foreach ($ComputerName in (Get-Content -Path .\Servers.txt)) {
$CS = Get-WmiObject Win32_ComputerSystem -ComputerName $ComputerName
$OS = Get-WmiObject Win32_OperatingSystem -ComputerName $ComputerName
$PM = Get-WmiObject Win32_PhysicalMemory -ComputerName $ComputerName
$PR = Get-WmiObject Win32_processor -ComputerName $ComputerName
$LD = Get-WmiObject Win32_LogicalDisk -ComputerName $ComputerName
$IP = [System.Net.Dns]::GetHostAddresses($ComputerName)
[PSCustomObject]#{
ServerName = $CS | Select-Object -ExpandProperty Name
IPAddress = $IP | Select-Object -ExpandProperty IPAddressToString
OS = $OS | Select-Object -ExpandProperty Caption
Memory = $PM | Measure-Object -Property Capacity -Sum | foreach { "$("{0:n2}" -f ( $_.Sum/1GB ) )" }
CPU = $PR | Select-Object Name, NumberOfCores
Disks = $LD | foreach { "$($_.DeviceID) $("{0:n2}" -f ( $_.Size/ 1GB ) )" }
Model = $CS | Select-Object -ExpandProperty Model
}
}
$File = Join-Path $env:TEMP 'Ouptut.csv'
$Servers | Export-Csv -Path $File -NoTypeInformation -Delimiter ';'
Start-Process $File

How to store data from foreach function in HTML file in powershell and get Physicall ram

I have written a for each file which stores the BIOS information of the systems in a network and the result is being displayed on my console but I want them to be in a HTML file in an order.
Code:
$arrComputers = get-Content -Path "C:\Computers.txt"
foreach ($strComputer in $arrComputers)
{
$colItems = get-wmiobject -class "Win32_BIOS" -namespace "root\CIMV2" `
-computername $strComputer
foreach ($objItem in $colItems)
{
write-host "Computer Name: " $strComputer
write-host "BIOS Version: " $objItem.BIOSVersion
}
$colItems1 = get-wmiobject -class Win32_logicaldisk -Filter "DeviceID = 'C:'" -computername $strComputer
foreach ($objItem1 in $colItems1)
{
$e=$objItem1.freeSpace/1GB
write-host "Total Space: " $e
}
$colItems4 = Get-WMIObject -class Win32_PhysicalMemory -computername $strComputer
$colItems5=$colItems4 | Measure-Object -Property capacity -Sum
foreach ($objItem4 in $colItems5)
{
$e4=$colItems5.Sum/1GB
write-host "Memory : " $e4
}
}
Can you please help me in saving all the above data in HTML
You need to look at the ConvertTo-Html cmdlet.
Get-WmiObject -Class Win32_BIOS -ComputerName localhost,$env:COMPUTERNAME |
Select PSComputerName,Version,SerialNumber |
ConvertTo-Html |
Out-File c:\test3.html
Another method based on OPs update:
$arrComputers = get-Content -Path "C:\Computers.txt"
$arrComputers | ForEach-Object { Get-WMIObject -Class Win32_BIOS -ComputerName $_ } |
Select PSComputerName, Version, Manufacturer |
ConvertTo-Html |
Out-File C:\test4.html