**I tried n "n" '`n'
Blockquote
**
GC D:\code\ServerList.txt | % {
$Comp = $_
#write-output "server Information"
If (Test-Connection $Comp -Quiet){
$Luser = (Get-WmiObject -class win32_process -Filter
"Name='Explorer.exe'" -ComputerName $Comp | % {$_.GetOwner().User} |
Sort-Object -Unique) -join ","
$Mem = GWMI -Class win32_operatingsystem -computername $COMP
New-Object PSObject -Property #{
"ServerInfo" = ""
Server = $Comp
"CPU usage" = "$((GWMI -ComputerName $COMP win32_processor
| Measure-Object -property LoadPercentage -Average).Average) %"
"Memory usage" = "$("{0:N2}" -f
((($Mem.TotalVisibleMemorySize - $Mem.FreePhysicalMemory)*100)/
$Mem.TotalVisibleMemorySize)) %"
"Total FreeSpace" = "$("{0:N2}" -f ((Get-WmiObject -Class
win32_logicaldisk -ComputerName $COMP -Filter "DriveType = '3'" |
Measure-Object -property FreeSpace -Sum).Sum /1GB)) GB"
"DiskSpace" = "$("{0:N2}" -f ((Get-WmiObject -Class
win32_logicaldisk -ComputerName $COMP -Filter "DriveType = '3'" |
Measure-Object -property Size -Sum).Sum /1GB)) GB"
"Comment" = ""
"logged Users" = $Luser
}
}
Else{
"" | Select #{N="Server";E={$Comp}},"CPU usage","Memory usage","Total
FreeSpace","logged Users","DiskSpace"
}
}| Select "ServerInfo",Server,"logged Users","CPU usage","Memory
usage","Total FreeSpace" ,"DiskSpace", "Comment" |
Export-Csv "D:\code\Diskncpu.csv" -nti –Append
output
desired output
"`r`n"
Needs to be in double quotes I believe.
Use [System.Environment]::NewLine to add new lines anywhere you need.
Having said that I formatted your code for clarity and executed against an array
#("MECDEVAPP01","MECDEVAPP01")| % {
$Comp = $_
#write-output "server Information"
If (Test-Connection $Comp -Quiet){
$Luser = (Get-WmiObject -class win32_process -Filter "Name='Explorer.exe'" -ComputerName $Comp | % {$_.GetOwner().User} | Sort-Object -Unique) -join ","
$Mem = GWMI -Class win32_operatingsystem -computername $COMP
New-Object PSObject -Property #{
"ServerInfo" = ""
Server = $Comp
"CPU usage" = "$((GWMI -ComputerName $COMP win32_processor | Measure-Object -property LoadPercentage -Average).Average) %"
"Memory usage" = "$("{0:N2}" -f ((($Mem.TotalVisibleMemorySize - $Mem.FreePhysicalMemory)*100)/ $Mem.TotalVisibleMemorySize)) %"
"Total FreeSpace" = "$("{0:N2}" -f ((Get-WmiObject -Class win32_logicaldisk -ComputerName $COMP -Filter "DriveType = '3'" | Measure-Object -property FreeSpace -Sum).Sum /1GB)) GB"
"DiskSpace" = "$("{0:N2}" -f ((Get-WmiObject -Class win32_logicaldisk -ComputerName $COMP -Filter "DriveType = '3'" | Measure-Object -property Size -Sum).Sum /1GB)) GB"
"Comment" = ""
"logged Users" = $Luser
}
}
Else{
"" | Select #{N="Server";E={$Comp}},"CPU usage","Memory usage","Total FreeSpace","logged Users","DiskSpace"
}
}| Select "ServerInfo",Server,"logged Users","CPU usage","Memory usage","Total FreeSpace" ,"DiskSpace", "Comment"|
Export-Csv "C:\Users\asarafian\Downloads\Diskncpu.csv" -nti –Append
The csv file is like this
"ServerInfo","Server","logged Users","CPU usage","Memory usage","Total FreeSpace","DiskSpace","Comment"
"","MECDEVAPP01","","7 %","70,24 %","203,97 GB","278,36 GB",""
"","MECDEVAPP01","","0 %","70,25 %","203,97 GB","278,36 GB",""
which is what I would expect from a conversion of a recordset (that's what you are building with all those pipes) into a csv.
I you want to product a formatted text then you cant use csv or you need to combine elements of it.
Try using `r`n for a new line. It needs the new line and carriage return to work.
If I understand you correctly you want a row to appear with a newline character, but instead you get the `r`n litteral characters or anything you try to throw at it.
Minimal testcase I can come up with to reproduce this problem:
> function paste ($separator = '`r`n') {$($input) -join $separator}
> & { echo foo; echo bar; echo baz; } | paste
foo`r`nbar`r`nbaz
Expceted result was
foo
bar
baz
How do you get actual newlines as output instead of literal `r`n? Super simple, just use the suggested answer!
> function paste ($separator = "`r`n") {$($input) -join $separator}
> & { echo foo; echo bar; echo baz; } | paste
foo
bar
baz
Or, if you do not like magic strings:
function paste ($separator = [System.Environment]::NewLine) {$($input) -join $separator}
PS D:\Temp\specs\ProRail.TrackChanges.Specs.Features> & { echo foo; echo bar; echo baz; } | paste
foo
bar
baz
Related
I have powershell script to pull down hotfixID, installedon, lastbootuptime and freespace in C drive. (I googled around and changed couple of things I need.) when the Pc is not reachable it will
Write-Warning "$_ cannot be reached, skipping."
I also want to capture the computer name of the failed PC to my CSV. I tried
| Export-Csv C:\test\computerDetails.csv -NoTypeInformation
or append but seems like its not working. can someone please help? below is my whole script.
(Get-Content C:\test\serverlist.txt).Trim() | ForEach {
If (Test-Connection -ComputerName $_ -Count 1 -Quiet)
{
$update = Get-CimInstance Win32_QuickFixEngineering -ComputerName $_ | Sort-Object InstalledOn -Descending | Select-Object -First 1
$os = Get-CimInstance win32_operatingsystem -ComputerName $_
$disk = Get-WmiObject Win32_LogicalDisk -ComputerName $_ -Filter "DeviceID='C:'"
$props = #{
ComputerName = $_
HotFixID = $update.HotFixID
InstalledOn = $update.InstalledOn
lastbootuptime = $os.LastBootUpTime
FreeSpace_GB = $disk.FreeSpace / 1GB
}
New-Object PsObject -Property $props
}
Else {
Write-Warning "$_ cannot be reached, skipping." | Export-Csv C:\test\computerDetails.csv -NoTypeInformation
}
} | Sort ComputerName |
Select ComputerName,HotFixID,InstalledOn,lastbootuptime,FreeSpace_GB |
Export-Csv C:\test\computerDetails.csv -NoTypeInformation
Main problem with adding it to the CSV is that it is a string. If you treat the erroneous machines the same as successful ones, then you can throw them in the same CSV.
I have added an ArrayList there as the storage variable and then for each computer it creates a temp PSObject to store your results in, overwriting the variable each loop but not before dumping the variable into the ArrayList for export at the end.
$Errors = New-Object System.Collections.ArrayList
(Get-Content C:\test\serverlist.txt).Trim() | ForEach {
$Temp = New-Object -TypeName PSObject
If (Test-Connection -ComputerName $_ -Count 1 -Quiet) {
$update = Get-CimInstance Win32_QuickFixEngineering -ComputerName $_ | Sort-Object InstalledOn -Descending | Select-Object -First 1
$os = Get-CimInstance win32_operatingsystem -ComputerName $_
$disk = Get-WmiObject Win32_LogicalDisk -ComputerName $_ -Filter "DeviceID='C:'"
$props = [ordered]#{
ComputerName = $_
HotFixID = $update.HotFixID
InstalledOn = $update.InstalledOn
lastbootuptime = $os.LastBootUpTime
FreeSpace_GB = $disk.FreeSpace / 1GB
Error = "Success"
}
$Temp | Add-Member -NotePropertyMembers $props -TypeName temp
} Else {
$props = [ordered]#{
ComputerName = $_
Error = "Cannot be reached"
}
$Temp | Add-Member -NotePropertyMembers $props -TypeName temp
Write-Warning "$_ cannot be reached, skipping."
}
$Errors.Add($Temp) > $null
}
$Errors | Export-Csv C:\temp\computerDetails.csv -NoTypeInformation -Append
I have this piece of code that gets the information from the computers in the domain and outputs to a csv file. I tried to add a new line of code to also grab t he Disk information for the computers but I can't get it working as expected.
# Get the list of all computer names and export to CSV file
Get-ADComputer -Filter * | select Name | Export-Csv -Path 'C:\temp\computers.csv' -NoTypeInformation
# Import the computer names from CSV file and get the system information
$computers = Import-Csv “C:\Temp\computers.csv” | ForEach {
$computerSystem = Get-WmiObject Win32_ComputerSystem -ComputerName $_.Name
$computerOS = Get-WmiObject Win32_OperatingSystem -ComputerName $_.Name
$computerCPU = Get-WmiObject Win32_Processor -ComputerName $_.Name
$computerSN = Get-WmiObject Win32_bios -ComputerName $_.Name | Select-Object SerialNumber
$computerDisk = Get-WmiObject win32_logicaldisk -ComputerName $_.Name | Select-Object DeviceId
[PSCustomObject]#{
'PCName' = $computerSystem.Name
'Model' = $computerSystem.Model
'RAM' = "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB)
'CPU' = $computerCPU.Name
'OS' = $computerOS.caption
'SN' = $computerSN.SerialNumber
'User' = $computerSystem.UserName
'Disk' = $computerDisk.DeviceId | Format-Table DeviceId, MediaType, #{n="Size";e={[math]::Round($_.Size/1GB,2)}},#{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}
}
} | Export-Csv 'C:\Temp\system-info.csv' -NoTypeInformation
This is the line of codes for disk.
$computerDisk = Get-WmiObject win32_logicaldisk -ComputerName $_.Name | Select-Object DeviceId
And...
'Disk' = $computerDisk.DeviceId | Format-Table DeviceId, MediaType, #{n="Size";e={[math]::Round($_.Size/1GB,2)}},#{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}
The other parameters work but only the disk info section isn't working. the output is: System.Object[] instead of displaying the info .
This has worked or me somewhat but it only grabs the info for the first drive. Also, the free space is larger than the Disk size which is weird.
$Computers = Import-Csv 'C:\Temp\computers.csv'
$Computers | ForEach {
$computerSystem = Get-WmiObject Win32_ComputerSystem -ComputerName $_.Name
$computerOS = Get-WmiObject Win32_OperatingSystem -ComputerName $_.Name
$computerCPU = Get-WmiObject Win32_Processor -ComputerName $_.Name
$computerSN = Get-WmiObject Win32_bios -ComputerName $_.Name | Select-Object SerialNumber
$computerDisk = Get-WmiObject win32_logicaldisk -ComputerName $_.Name | Select-Object DeviceId, Size, FreeSpace
[PSCustomObject]#{
'PCName' = $computerSystem.Name
'Model' = $computerSystem.Model
'RAM' = "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB)
'CPU' = $computerCPU.Name
'OS' = $computerOS.caption
'SN' = $computerSN.SerialNumber
'User' = $computerSystem.UserName
'Disk' = $computerDisk.DeviceId | Format-Table | Out-String
'Size' = $computerDisk.Size | Format-Table | Out-String
'Free Space' = $computerDisk.FreeSpace | Format-Table | Out-String
}
} | Export-Csv 'C:\Temp\system-info.csv' -NoTypeInformation
You can do this to get the result I think you're after:
$Computers = Import-Csv 'C:\Temp\computers.csv'
$Computers | ForEach {
$computerSystem = Get-WmiObject Win32_ComputerSystem -ComputerName $_.Name
$computerOS = Get-WmiObject Win32_OperatingSystem -ComputerName $_.Name
$computerCPU = Get-WmiObject Win32_Processor -ComputerName $_.Name
$computerSN = Get-WmiObject Win32_bios -ComputerName $_.Name | Select-Object SerialNumber
$computerDisk = Get-WmiObject win32_logicaldisk -ComputerName $_.Name | Select-Object DeviceId, MediaType, #{n="Size";e={[math]::Round($_.Size/1GB,2)}},#{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}
[PSCustomObject]#{
'PCName' = $computerSystem.Name
'Model' = $computerSystem.Model
'RAM' = "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB)
'CPU' = $computerCPU.Name
'OS' = $computerOS.caption
'SN' = $computerSN.SerialNumber
'User' = $computerSystem.UserName
'Disk' = $computerDisk | Format-Table | Out-String
}
} | Export-Csv 'C:\Temp\system-info.csv' -NoTypeInformation
The first problem was that in the $computerDisk = line you were using Select-Object to return only the DeviceID property, but then were later trying to use the other properties.
The second problem was that you need to pipe Format-Table to Out-String when you output it to convert it to string format so that Export-CSV doesn't treat it as an object.
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
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" }
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