Is it possible to adjust this code to export all lines outside foreach loop:
This works fine (inside loop):
$vms = Get-VM | Where { $_.State –eq ‘Running’ } | Select-Object -ExpandProperty Name
foreach($vm in $vms) {
# Get network interface details
$out = Get-VMNetworkAdapter -vmname $vm | select VMName, MacAddress, IPAddresses
$vm_name = $out.VMName | Get-Unique
$ip = ($out.IPAddresses | ForEach-Object {
$_ | ? {$_ -notmatch ':'}
}) -join " "
# If more than 1 MAC , put it in same row separated by space (00:15:5D:58:12:5E 00:15:5D:58:12:5F )
$mac = ($out.MacAddress | ForEach-Object {
$_.Insert(2,":").Insert(5,":").Insert(8,":").Insert(11,":").Insert(14,":")
}) -join ' '
$results = #()
$comp = Get-WmiObject Win32_ComputerSystem | Select-Object -ExpandProperty name
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name "VM NAME" -Value $vm_name
$obj | Add-Member -MemberType NoteProperty -Name "IP ADDRESS" -Value $ip
$obj | Add-Member -MemberType NoteProperty -Name "MAC ADDRESS" -Value $mac
$obj | Add-Member -MemberType NoteProperty -Name "HYPER-V HOST" -Value $comp
$results += $obj
Write-Output $results
$results| Export-Csv -Path "c:\1.csv" -NoTypeInformation -append
}
However, when i move $results| Export-Csv -Path "c:\1.csv" -NoTypeInformation -append outside loop,
only one (last) line is saved to CSV
Inside loop, $results variable contains all lines, when i move this variable outside loop write-host $results only one (last) line is printed
For what it's worth, your code can be condensed quite a bit. Many of your steps are not necessary:
$results = Get-VM | Where State –eq Running | Get-VMNetworkAdapter | ForEach-Object {
[pscustomobject]#{
'VM NAME' = $_.VMName
'IP ADDRESS' = ($_.IPAddresses -notmatch ':') -join ' '
'MAC ADDRESS' = ($_.MacAddress -replace '(..)(..)(..)(..)(..)','$1:$2:$3:$4:$5:') -join ' '
'HYPER-V HOST' = $env:COMPUTERNAME
}
}
$results | Export-Csv -Path "c:\1.csv" -NoTypeInformation
Notes:
You can pipe the VMs that Get-VM returns directly into Get-VMNetworkAdapter
If you filter on a single property you don't need a script block for Where-Object. Where State -eq Running is a bit easier to write and read than Where { $_.State -eq 'Running' }.
$_.IPAddresses -notmatch ':' Operators like -notmatch work on arrays. 'a','b','0','c' -notmatch '\d' will return 'a','b','c'.
The same goes for -replace. 'a0','b1','c2' -replace '\d','' will return return 'a','b','c'. No foreach loops necessary at all.
$env:COMPUTERNAME should be faster than using WMI to get the computer name
Any object you create in a script block (like the ForEach-Object {...} script block) that you do not assign to a variable will be in the script block's output. This is why $results = ... | ForEach-Object {...} works. There is no need to explicitly create arrays with #() and add values to them.
Casting a hash table to [pscustomobject] is much easier than using Add-Member.
Figured it out:
moved $results variable outside loop (make it "global")
$vms = Get-VM | Where { $_.State –eq ‘Running’ } | Select-Object -ExpandProperty Name
$results = #()
foreach($vm in $vms) {
# Get network interface details
$out = Get-VMNetworkAdapter -vmname $vm | select VMName, MacAddress, IPAddresses
# Remove duplicate VM names
$vm_name = $out.VMName | Get-Unique
# In case more than 1 IP, put it in same row separated by space (192.168.1.1, 192.168.1.2)
$ip = ($out.IPAddresses | ForEach-Object {
$_ | ? {$_ -notmatch ':'}
}) -join " "
# If more than 1 MAC , put it in same row separated by space (00:15:5D:58:12:5E 00:15:5D:58:12:5F )
$mac = ($out.MacAddress | ForEach-Object {
$_.Insert(2,":").Insert(5,":").Insert(8,":").Insert(11,":").Insert(14,":")
}) -join ' '
$comp = Get-WmiObject Win32_ComputerSystem | Select-Object -ExpandProperty name
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name "VM NAME" -Value $vm_name
$obj | Add-Member -MemberType NoteProperty -Name "IP ADDRESS" -Value $ip
$obj | Add-Member -MemberType NoteProperty -Name "MAC ADDRESS" -Value $mac
$obj | Add-Member -MemberType NoteProperty -Name "HYPER-V HOST" -Value $comp
$results += $obj
}
$results| Export-Csv -Path "c:\1.csv" -NoTypeInformation
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 a script powershell to get PercentProcessorTime of processes.
$Processes = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
$Processes | %{ New-Object psobject -Property `
#{ Time = $_.PercentProcessorTime;
Name = ($_.name -replace "#\d+", "" )}}`
| ?{ $_.Name -notmatch "_Total|Idle" } `
| Group-Object Name `
| %{ New-Object psobject -Property `
#{ Name = $_.Name;
Sum = ($_.Group | Measure-Object Time -Sum ).Sum }} `
| Format-Table
Format of result as below:
But I want to format result as below to insert to database:
OK |Idle=100 System=6 smss=0 csrss=0 wininit=0 services=0 lsass=0 lsm=0 svchost=18 ICTrigger=0 nvvsvc=0 ICDCMGR64=0 svchost#2=0 winlogon=0 svchost#3=0 svchost#4=0 svchost#5=0 igfxCUIService=0 svchost#6=0 spoolsv=0 svchost#7=0 armsvc=0 ShieldStart=0 svchost#8=0 GateMan=0 HeciServer=0 Jhi_service=0 NHCAAgent=0 nvxdsync=0 nvvsvc#1=0 nscp=0 PaSvc=0 pcdrmsvc=0 NSCHIM=0 ASDSvc=0 secugate64=0 WindowsSecuService=0 WinFil32=0 WmiPrvSE=0 svchost#9=0 papersrv64=0 WUDFHost=0 svchost#10=0 svchost#11=0 WmiP rvSE#1=0 PaTray=0 unsecapp=0 WmiPrvSE#2=0 LMS=0 SWMAgent=0
Please help me to solve it.
Thanks very much ^^
I don't think there is an "easy", builtin command for it, but it doesn't take much to update the function to do what you want:
$Processes = (get-wmiobject Win32_PerfFormattedData_PerfProc_Process)
$procStrings = #()
$Processes | %{ New-Object psobject -Property `
#{ Time = $_.PercentProcessorTime;
Name = ($_.name -replace "#\d+", "" )}}`
| ?{ $_.Name -notmatch "_Total|Idle" } `
| Group-Object Name `
| %{
$procStrings += "$($_.Name)=$(($_.Group | Measure-Object Time -Sum ).Sum)"}
$procStrings -join " "
Basically, I added an array to hold the string key/value paris and replaced the final New-Object with code to create the desired string. Finally it is joined with spaces to create the final string.
You could absolutely skip the array part and just build up the string directly, instead of creating an array, I just like that approach :)
It doesn't include the "OK |" in the beginning, i don't know what you constitutes an OK, but I'm sure you can add yourself to get what you want :)
I got this code, which returns number of bytes:
$size = Get-ChildItem $userAccount.homeDirectory -Recurse | Measure-Object -Property Length -Sum
This works fine, but is not very user friendly, so I want to convert to megabytes or gigabytes.
After googling and looking at examples, I've tried this:
$size = "{0:N2}" -f ((Get-ChildItem $userAccount.homeDirectory -Recurse | Measure-Object -Property Length -Sum).Sum / 1MB)
However, PowerShell returns nothing.
Any idea why?
Edit: Posting complete code.
Function:
Function Get-ADHomeDirectorySize
{
Param
(
[Parameter(ValueFromPipeline=$true,Mandatory=$true)]
[Microsoft.ActiveDirectory.Management.ADUser]$User
)
Begin
{
$HomeD = #()
$size = $nul
}
Process
{
ForEach($userAccount in $User)
{
$userAccount = Get-ADUser $userAccount -properties homeDirectory
$size = "{0:N2}" -f ((Get-ChildItem $userAccount.homeDirectory -Recurse | Measure-Object -Property Length -Sum).Sum / 1MB)
If($userAccount.homeDirectory -eq $nul)
{
Write-Host "`nERROR -- User: $userAccount has no Home Directory`n" -foregroundcolor red
Return
}
$obj = New-Object System.Object
$obj | add-member -type NoteProperty -name User -value $userAccount.Name
$obj | add-member -type NoteProperty -name HomeDirectory -value $userAccount.homeDirectory
$obj | add-member -type NoteProperty -name HomeDirectorySize -value $size.sum
$HomeD += $obj
}
}
End
{
$HomeD
}
}
Script to generate report based on an input list of user IDs:
Get-Content brukerlistetest.txt | Foreach-Object {Get-ADUser $_ -properties homeDirectory | ? {$_.homeDirectory -ne $nul} | Get-ADHomeDirectorySize | sort HomeDirectorySize | Format-Table -HideTableHeaders | out-file output.txt -width 120 -append}
You can perform math operations on your first example:
$size = (Get-ChildItem $userAccount.homeDirectory -Recurse | Measure-Object -Property Length -Sum) / 1MB # or / 1GB
PowerShell has constants that define bytes.
If you want it to be a string, you can use a string subexpression:
$size = "$((GCI $userAccount.homeDirectory -Recurse | Measure Length -Sum) / 1MB)MB"
How does one lists the processes using CPU > 1% by piping the output from Get-Process to Where-Object?
Complete beginner to powershell all i can think is something like this
Get-Process | Where-Object { CPU_Usage -gt 1% }
If you want CPU percentage, you can use Get-Counter to get the performance counter and Get-Counter can be run for all processes. So, to list processes that use greater than say 5% of CPU use:
(Get-Counter '\Process(*)\% Processor Time').CounterSamples | Where-Object {$_.CookedValue -gt 5}
This will list the processes that was using >5% of CPU at the instance the sample was taken. Hope this helps!
There are several points to note here:
first, you have to use the $_ variable to refer to the object currently coming from the pipe.
second, Powershell does not use % to express percentage -- instead, % represents the modulus operator. So, when ou want percentage, you have to transform your number by yourself by simply multiplying it by 0.01.
third, the Get-Process cmdlet does not have a field CPU_Usage; a summary on its output can be found here. About the field CPU is says: "The amount of processor time that the process has used on all processors, in seconds." So be clear on what you can expect from the numbers.
Summarizing the command can be written as
Get-Process | Where-Object { $_.CPU -gt 100 }
This gives you the processes which have used more than 100 seconds of CPU time.
If you want something like a relative statement, you first have to sum up all used times, and later divide the actual times by the total time. You can get the total CPU time e.g. by
Get-Process | Select-Object -expand CPU | Measure-Object -Sum | Select-Object -expand Sum
Try to stack it together with the previous command.
Further improving earlier answers by adding dynamic detection of the number of logic cores so the percentage can be adjusted back to what us common mortals expect to see, where 100% means all of the CPU bandwidth of the machine, and there is no value greater than 100%. Includes a filter set at 10%, which one can adjust as appropriate. The assumption is that people will be interested in finding processes with high overload processor usage and not want to list the numerous idle processes of the machine.
$NumberOfLogicalProcessors=(Get-WmiObject -class Win32_processor | Measure-Object -Sum NumberOfLogicalProcessors).Sum
(Get-Counter '\Process(*)\% Processor Time').Countersamples | Where cookedvalue -gt ($NumberOfLogicalProcessors*10) | Sort cookedvalue -Desc | ft -a instancename, #{Name='CPU %';Expr={[Math]::Round($_.CookedValue / $NumberOfLogicalProcessors)}}
Sample output:
InstanceName CPU %
------------ -----
_total 100
idle 100
I was looking for a solution to get cpu, mem utilization by process. All solutions I tried where I would get the cpu but those numbers were not matching with taskmanager. So I wrote my own. Following will provide accurate cpu utilization by each process. I tested this on a I7 laptop.
$Cores = (Get-WmiObject -class win32_processor -Property numberOfCores).numberOfCores;
$LogicalProcessors = (Get-WmiObject –class Win32_processor -Property NumberOfLogicalProcessors).NumberOfLogicalProcessors;
$TotalMemory = (get-ciminstance -class "cim_physicalmemory" | % {$_.Capacity})
$DATA=get-process -IncludeUserName | select #{Name="Time"; Expression={(get-date(get-date).ToUniversalTime() -uformat "%s")}},`
ID, StartTime, Handles,WorkingSet, PeakPagedMemorySize, PrivateMemorySize, VirtualMemorySize,`
#{Name="Total_RAM"; Expression={ ($TotalMemory )}},`
CPU,
#{Name='CPU_Usage'; Expression = { $TotalSec = (New-TimeSpan -Start $_.StartTime).TotalSeconds
[Math]::Round( ($_.CPU * 100 / $TotalSec) /$LogicalProcessors, 2) }},`
#{Name="Cores"; Expression={ ($Cores )}},`
#{Name="Logical_Cores"; Expression={ ($LogicalProcessors )}},`
UserName, ProcessName, Path | ConvertTo-Csv
Or as [pscustomobject]:
$cpu = Get-WmiObject –class Win32_processor -Property NumberOfCores, NumberOfLogicalProcessors
$mem = (Get-CimInstance -class cim_physicalmemory | measure capacity -sum).sum
$epoch = get-date(get-date).ToUniversalTime() -uformat "%s"
get-process -IncludeUserName |
% {
if ($_.starttime -gt 0) {
$ts = (New-TimeSpan -Start $_.StartTime -ea si).TotalSeconds
$cpuusage = [Math]::Round( $_.CPU * 100 / $ts / $cpu.numberoflogicalprocessors, 2)
} else {
$cpuusage = 0
}
[pscustomobject] #{
"Time" = $epoch
"Total_RAM" = $mem
"CPU_Usage" = $cpuusage
"Cores" = $cpu.numberofcores
"Logical Cores" = $cpu.numberoflogicalprocessors
"UserName" = $_.username
"ProcessName" = $_.processname
"Path" = $_.path
"CPU" = $_.CPU
"ID" = $_.ID
"StartTime" = $_.StartTime
"Handles" = $_.Handles
"WorkingSet" = $_.WorkingSet
"PeakPagedMemorySize" = $_.PeakPagedMemorySize
"PrivateMemorySize" = $_.PrivateMemorySize
"VirtualMemorySize" = $_.VirtualMemorySize
}
}
In addition to Get-Counter, you can also use Get-WmiObect to list and filter processes.
powershell "gwmi Win32_PerfFormattedData_PerfProc_Process -filter 'PercentProcessorTime > 1' | Sort PercentProcessorTime -desc | ft Name, PercentProcessorTime"
Alternatively, for Get-Counter, here is an example showing number format conversion to get rid of the annoying decimal places of the CookedValue.
In addition to filtering, this example also illustrates sorting, limiting columns, and output formatting:
powershell "(Get-Counter '\Process(*)\% Processor Time').Countersamples | Where cookedvalue -gt 3 | Sort cookedvalue -Desc | ft -a instancename, #{Name='CPU %';Expr={[Math]::Round($_.CookedValue)}}"
Get-Process is not the right cmdlet as it doesn't provide instantaneous CPU utilization.
You can also get the total load for all processors:
powershell "gwmi win32_processor | Measure-Object LoadPercentage -Average | ft -h Average"
Or,
typeperf -sc 4 "\Processor(_Total)\% Processor Time"
I'd like to Add my version of code just to assist anyone that is having trouble with the same issues.
I needed one that gave me the CPU and Memory and this my take on the subject. It can export over time if you setup a scheduled task in windows, and it appends to a CSV file output and you can get multiple processes.
$Cores = (Get-WmiObject -class win32_processor -Property numberOfCores).numberOfCores;
$LogicalProcessors = (Get-WmiObject –class Win32_processor -Property NumberOfLogicalProcessors).NumberOfLogicalProcessors;
$TotalMemory = (get-ciminstance -class "cim_physicalmemory" | % {$_.Capacity})
#EDIT the PATH for the CSV output to be located
$PATH = "C:\temp"
#You can add more processes here as variables or just CommaSeperate them like below
$Process1 = 'explorer'
$Process2 = 'chrome'
Get-Process -Name $Process1,$Process2 | select #{N="TimeStamp";E={Get-Date -Format 'dd/MM/yyyy HH:mm:ss.fff'}},
ID,
name,
Handles,
PeakPagedMemorySize,
PrivateMemorySize,
VirtualMemorySize,
#{Name="Memory_MB"; Expression = {[Math]::Round(($_.workingSet / 1mb),2)}},
#{Name='CPU_Usage'; Expression = { $TotalSec = (New-TimeSpan -Start $_.StartTime).TotalSeconds [Math]::Round( ($_.CPU * 100 / $TotalSec) /$LogicalProcessors, 2) }},
#{Name="Cores"; Expression={ ($Cores )}},
#{Name="Logical_Cores"; Expression={ ($LogicalProcessors )}},
Path | Export-Csv -Path "$PATH\CPU_MEMORY_$env:COMPUTERNAME.csv" -NoTypeInformation -Append
I know this is above the OP's question and goes a bit further but I hope this helps!
To invoke vs. multible servers in parallel, and return process, cpu usage, servername, and corecount the following works well.
It will take 10 samples over 10sec and average the value. You can change this with the MaxSamples parameter.
I reckon its a less elegant version of what Emrah Saglam is doing, i just get scared and confused by all his pipes :)
$allServers = "server1", "PC001", "server2"
#Change value of MaxSamples to the number of samples to take. Samples are taken in 1sec intervals
$CPUUsage = Invoke-Command -ComputerName $allServers -ScriptBlock {
$counters = (Get-Counter "\Process(*)\% Processor Time" -MaxSamples 10).CounterSamples | Sort-Object -Property CookedValue -Descending
[int]$coreCount = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors
$counters | ForEach-Object {
Add-Member -MemberType NoteProperty -Name "CPU_PCT" -Value ([math]::Round($_.CookedValue / $coreCount))[0] -InputObject $_
Add-Member -MemberType NoteProperty -Name "Host" -Value ($_.Path -replace "^\\\\|\\process.*$","") -InputObject $_
Add-Member -MemberType NoteProperty -Name "CoreCount" -Value $coreCount -InputObject $_
}
$counters | Select-Object InstanceName,CPU_PCT,Host,Path,CoreCount
}
#Unhash to see all samples:
#$CPUUsage | Sort-Object -Property Host,CPU_PCT -Descending | Select-Object -Property Host,InstanceName,CPU_PCT,Path,CoreCount | Out-GridView -Title "CPU Usage"
#Group samples, add wanted values and take average. Add values to new object
$CPUUsageGrouped = $CPUUsage | Group-Object -Property InstanceName,Host
$CPUUsageGrouped | ForEach-Object {
Add-Member -MemberType NoteProperty -Name "CPUavg" -Value (($_.Group.CPU_PCT | Measure-Object -Sum).Sum / $_.Count) -InputObject $_
Add-Member -MemberType NoteProperty -Name "CPUmin" -Value ($_.Group.CPU_PCT | Sort-Object)[0] -InputObject $_
Add-Member -MemberType NoteProperty -Name "CPUmax" -Value ($_.Group.CPU_PCT | Sort-Object)[$_.Count -1] -InputObject $_
Add-Member -MemberType NoteProperty -Name "Host" -Value $_.Group.Host[0] -InputObject $_
Add-Member -MemberType NoteProperty -Name "CoreCount" -Value $_.Group.CoreCount[0] -InputObject $_
Add-Member -MemberType NoteProperty -Name "InstanceName" -Value $_.Group.InstanceName[0] -InputObject $_
}
#Sort the grid view with the build in search functions
$CPUUsageGrouped | Sort-Object -Property Host,CPUavg -Descending | Select-Object -Property Host,InstanceName,CPUavg,CoreCount,CPUmin,CPUmax | Out-GridView -Title "CPU Usage"
How about this for one process?
$sleepseconds = 1
$numcores = 4
$id = 5244
while($true) {
$cpu1 = (get-process -Id $id).cpu
sleep $sleepseconds
$cpu2 = (get-process -Id $id).cpu
[int](($cpu2 - $cpu1)/($numcores*$sleepseconds) * 100)
}
$Result = Invoke-Command -ComputerName $ServerName -ScriptBlock {
Get-Counter "\Process(*)\% Processor Time" -ErrorAction SilentlyContinue `
| Select-Object -ExpandProperty CounterSamples `
| Where-Object {$_.Status -eq 0 -and $_.instancename -notin "_total", "idle", "" -and $_.CookedValue/$env:NUMBER_OF_PROCESSORS -gt 0} `
| Sort-Object CookedValue -Descending `
| Select-Object #{N="ServerName";E={$env:COMPUTERNAME}},
#{N="ProcessName";E={
$friendlyName = $_.InstanceName
try {
$procId = [System.Diagnostics.Process]::GetProcessesByName($_.InstanceName)[0].Id
$proc = Get-WmiObject -Query "SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId =$procId"
$procPath = ($proc | where { $_.ExecutablePath } | select -First 1).ExecutablePath
$friendlyName = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($procPath).FileDescription
} catch { }
$friendlyName
}},
#{N="CPU_Percent";E={[System.Math]::Round(($_.CookedValue/$env:NUMBER_OF_PROCESSORS), 2)}},
#{N="TimeStamp";E={Get-Date -Format 'dd/MM/yyyy HH:mm:ss.fff'}} -First 10 `
$Result
}
# If you want to export result to your SQL Server table you can use DbaTools Powershell Modules.
$Result | Select -Property ServerName, ProcessName, CPU_Percent, TimeStamp | ConvertTo-DbaDataTable | Write-DbaDbTableData -SqlInstance $OutInstance -Database $OutDB -Schema dbo -Table WindowsTopCPUProcesses