I want to convert unit that bytes to kilobytes.
powershell command of bellow entered :
Get-WmiObject -class Win32_PerfFormattedData_Tcpip_NetworkInterface |
select BytesReceivedPersec , BytesSentPersec , name |
Where-Object {$_.name -cnotmatch "isatap"} |
Where-Object {$_.name -cnotmatch "Teredo"} |
Where-Object {$_.name -cnotmatch "로컬"} |
% { '{0,10} {1,20} {2,20}' -f $_.BytesReceivedPersec, $_.BytesSentPersec , $_.name}
output :
627975 483072 Intel[R] 82575L Gigabit Network Connection
But output unit is Bytes
I want to convert unit that bytes to kilobytes.
Add /1kb to the BytesReceived expression and surround them with parentheses:
Get-WmiObject -class Win32_PerfFormattedData_Tcpip_NetworkInterface |
select BytesReceivedPersec , BytesSentPersec , name |
Where-Object {$_.name -cnotmatch "isatap|Teredo|로컬"} |
% { '{0,10} {1,20} {2,20}' -f ($_.BytesReceivedPersec /1kb), ($_.BytesSentPersec /1kb) , $_.name}
Also you can use -cnotmatch {"isatap|Teredo|로컬"} to short the code
Related
I have run the below command to get the output that when was my machine last patched but also need how to get the KB details too and how can I export in csv from SCCM.
$lastpatch=Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object HotfixID, InstalledOn | Select-Object -first 1
"{0:MM/dd/yyyy}" -f $lastpatch.InstalledOn | Write-Output
When I run the below command to also get the HotfixID but I am not getting the result so can someone help me with it.
$lastpatch= Get-HotFix | Sort-Object InstalledOn -Descending | select-object -first 1 | Select-Object InstalledOn, HotfixID
"{0:MM/dd/yyyy}" -f $lastpatch.InstalledOn,$lastpatch.HotfixID | Write-Output
To include the HotfixID, you can make use of a calculated property to have the Select-Object return an object with both wanted properties into the variable $lastPatch.
Once you have that object, it is easy to export to csv:
$lastpatch = Get-HotFix |
Sort-Object InstalledOn -Descending |
Select-Object -First 1 |
Select-Object #{Name = 'InstalledOn'; Expression = {"{0:MM/dd/yyyy}" -f $_.InstalledOn}},
HotfixID
# Output on screen
$lastPatch
# output to csv file
$lastPatch | Export-Csv -Path 'Path\To\lastpatch.csv' -UseCulture -NoTypeInformation
How do I properly use $_ in out-file? Here's my code:
get-content computers.txt |
Where {$_ -AND (Test-Connection $_ -Quiet)} |
foreach { Get-Hotfix -computername $_ } |
Select CSName,Description,HotFixID,InstalledBy,InstalledOn |
convertto-csv | out-file "C:\$_.csv"
I'm trying to execute a get-hotfix for all the computers listed in the text file then I want them to be exported to CSV with the computer name as the filename.
You need one pipeline to process the computers.txt files, and a nested one inside the foreach to process the list of hotfixes for each computer:
get-content .\computers.txt |
Where {$_ -AND (Test-Connection $_ -Quiet)} |
foreach {
Get-Hotfix -computername $_ |
Select CSName,Description,HotFixID,InstalledBy,InstalledOn |
convertto-csv | out-file "C:\$_.csv"
}
Edit: Changed computers.txt to .\computers.txt, as this is required for local paths in powershell
i can see with this:
get-content .\computers.txt | Where {$_ -AND (Test-Connection $_ -Quiet)} | foreach{ Get-Hotfix -id KB4012212 -computername $_ | Select CSName,Description,HotFixID,InstalledBy,InstalledOn | convertto-csv | out-file "C:\$_.csv" }
i can see only in which PC is the fix (KB4012212) installed.
it's possible to see the following
CSNAME Fix(Inst/NotInst)
PC1 FIxInstalled
PC2 FixNotinstalled
PC3 FixnotInstalled
..
..
etc
I monkeyed with this for a while and nothing I found on-line worked until I used this combo.
I used the method is this thread but it was SO slow and I wanted to learn more about using jobs so this is what ended up working for me on Windows 7 PS Ver 4.
All other options were either too slow or did not return data from the remote system.
$VMs = get-content C:\WinVms.txt #Generate your hostnames list however you deem best.
foreach ($vm in $vms)
{
Write-Host "Attempting to get hotfixes on:" $vm
invoke-command -computername $vm -ScriptBlock {start-job -scriptblock {(get-hotfix | sort installedon)[-1]} | wait-job | receive-job} -AsJob
}
start-sleep 60 # give it a minute to complete
get-job | ? { $_.state -eq "Completed"} | receive-job -keep | export-csv c:\temp\win-patch.csv
you can check your failures too like this:
get-job | ? { $_.state -eq "Failed"}
I'm setting up a contacts file in .csv format, as downloaded from google, to read with powershell on my windows 10 laptop. I have a long way to go to make this practical, but the first thing I've tried, and almost succeeded in, is to write a script that prompts the user to enter a name and then responds with the phone number for them. That script looks like this:
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="What's their name?")]
$TheirNameIs
)
Import-Csv "*MYPATH*.csv" |
Sort 'Family name' -descending |
Where-object {$_.Name -eq $TheirNameIs} |
Select-Object -Property 'Name','Phone 1 - Type','Phone 1 - Value'
The problem I am having is Where-object works with -eq to find exact matches to the name the user enters, but I wanted to use -contains so that I could type in a first name and get all the contacts with that value in their name. I tried replacing -eq with -contains but wasn't getting any output unless I used the exact contact name
Where am I going wrong with the Where-object cmdlet?
You could replace the -eq operator by the -like operator and insert wildcards:
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="What's their name?")]
$TheirNameIs
)
Import-Csv "*MYPATH*.csv" |
Sort 'Family name' -descending |
Where-object {$_.Name -like "*$TheirNameIs*"} |
Select-Object -Property 'Name','Phone 1 - Type','Phone 1 - Value'
You could also go for regular expressions and use the -match operator like #Olaf already mentioned. A solution could look like this:
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="What's their name?")]
$TheirNameIs
)
Import-Csv "*MYPATH*.csv" |
Sort 'Family name' -descending |
Where-object {$_.Name -match ".*$TheirNameIs.*"} |
Select-Object -Property 'Name','Phone 1 - Type','Phone 1 - Value'
I want to be able to to output to a log file the top CPU consumers every 5 seconds. That way I will be able to see who uses the most of the cpu during my tests.
I have found this answer very common:
$cpu = Get-Counter -ComputerName localhost "\Process(*)\% Processor Time" `
| Select-Object -ExpandProperty countersamples `
| where {$_.InstanceName -ne 'idle' } `
| where {$_.InstanceName -ne '_total' }`
| Select-Object -Property instancename, cookedvalue `
| Sort-Object -Property cookedvalue -Descending `
| Select-Object -First 5 `
| ft #{L='Date';E={Get-Date}}, InstanceName, #{L='CPU';E={(($_.Cookedvalue/100)/$NumberOfLogicalProcessors).toString('P')}} -HideTableHeaders `
| Format-Table -Auto | Out-String
I have 2 issues with it:
Sometimes I get:
Get-Counter : The data in one of the performance counter samples is not valid. View the Status property for each PerformanceCounterSample object to make sure it contains valid data.
I would like to get the full process name, and not
java 25%
idea64 0.8%
...
I'll try to answer your two questions at once with following script:
Get-Counter "\Process(*)\% Processor Time" -ErrorAction SilentlyContinue `
| select -ExpandProperty CounterSamples `
| where {$_.Status -eq 0 -and $_.instancename -notin "_total", "idle"} `
| sort CookedValue -Descending `
| select TimeStamp,
#{N="Name";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";E={($_.CookedValue/100/$env:NUMBER_OF_PROCESSORS).ToString("P")}} -First 5 `
| ft -a -HideTableHeaders
This results in following table:
24.07.2016 21:00:53 Microsoft Edge Content Process 9,68%
24.07.2016 21:00:53 system 0,77%
24.07.2016 21:00:53 Microsoft Edge 0,39%
24.07.2016 21:00:53 runtimebroker 0,39%
24.07.2016 21:00:53 Host Process for Windows Services 0,39%
As specified, you sometimes get:
Get-Counter : The data in one of the performance counter samples is
not valid. View the Status property for each PerformanceCounterSample
object to make sure it contains valid data.
This is related to process management in windows environment. While you execute query, some processes may appear, some of them may disappear (i.e. wmiprvse process responsible for executing wmi queries). Some processes may require more permissions you have. This all leads to error when obtaining process information. It can be safely skipped using -ErrorAction SilentlyContinue switch and filtered with Status -eq 0 expression.
You also want to see more friendly process name. I don't know if there is better way of getting that name than from executable itself using GetVersionInfo method. If such information is available FileDescription property stores that value. If it's not available then non-friendly process name is used.
you get output something like this
Name CPU CPUPercent Description
---- --- ---------- -----------
chrome 10.4988673 8.79 Google Chrome
powershell_ise 6.5364419 7.16 Windows PowerShell ISE
chrome 38.0174437 4.88 Google Chrome
chrome 26.2549683 4.87 Google Chrome
chrome 16.9417086 3.16 Google Chrome
cavwp 10.2648658 2.67 COMODO Internet Security
chrome 13.1820845 2.44 Google Chrome
chrome 675.016327 2.02 Google Chrome
7.9.7_42331 1037.1570484 1.51 BitTorrent
chrome 340.8777851 1.02 Google Chrome
With
$CPUPercent = #{
Name = 'CPUPercent'
Expression = {
$TotalSec = (New-TimeSpan -Start $_.StartTime).TotalSeconds
[Math]::Round( ($_.CPU * 100 / $TotalSec), 2)
}
}
Get-Process -ComputerName $env:computername |
Select-Object -Property Name, CPU, $CPUPercent, Description |
Sort-Object -Property CPUPercent -Descending |
Select-Object -First 10 |format-table -autosize | out-file c:\pro.log
credit :http://powershell.com/cs/blogs/tips/archive/2013/04/16/documenting-cpu-load-for-running-processes.aspx
Get-Process -ComputerName $env:computername for remote computers you can have in csv
Import-CSV c:\"computers.csv" | % {
$Server = $_.ServerName
$alivetest = Test-Path "\\$Server\c$\"
If ($alivetest -eq "True")
{Get-Process -ComputerName $server |
Select-Object -Property Name, CPU, $CPUPercent, Description |
Sort-Object -Property CPUPercent -Descending |
Select-Object -First 10 |format-table -autosize | out-file c:\pro.log}
}}
I wanted to extract a list of users logged on to remote pc, the ps names would be fed in using a .csv file.
I was able to get a command
Get-WmiObject Win32_LoggedOnUser -ComputerName $Computer | Select Antecedent -Unique
to query the user names, could any one help me more on how to write this code?
Assuming the csv file contains a ComputerName header:
Import-Csv computers.csv | Foreach-Object{
Get-WmiObject Win32_LoggedOnUser -ComputerName $_.ComputerName | Select-Object __SERVER,Antecedent -Unique | Foreach-Object {
$domain,$user = [regex]::matches($_.Antecedent,'="([^"]+)"') | Foreach-Object {$_.Groups[1].Value}
$_ | Select-Object __SERVER,#{Name='Domain';Expression={$domain}},#{Name='User';Expression={$user}}
}
}