I am trying to match the boot up time with the file modified date to be within a couple minutes of each other.
I can get the data but don't know how to do the computations. Here is what I get:
PS E:\> $disk=gci -Attributes hidden E:\filename.ext | Select LastWriteTime
PS E:\> $disk
LastWriteTime
-------------
6/23/2014 12:55:48 PM
PS E:\> $boottime=Get-CimInstance -ClassName win32_operatingsystem | select last bootuptime
PS E:\> $boottime
lastbootuptime
--------------
6/23/2014 12:55:39 PM
What I am looking for in English is a way to say "If lastwritetime is within 5 minutes of lastboot time, then all is good. If not, all is bad"
How can I do that with powershell?
I would subtract the datetimes and use the resulting TimeSpan object. Also, note that using the -ExpandProperty is needed to get a bare value with select-object.
$disk=gci -Attributes hidden E:\filename.ext | Select -ExpandProperty LastWriteTime
$boottime=Get-CimInstance -ClassName win32_operatingsystem | select -ExpandProperty lastbootuptime
if(($disk-$bootTime).TotalMinutes -lt 5){
"all is good"
}
Well, those are both dates and times, that's for sure. The issue is that the Get-WMI is returning some crazy CimInstance object that is relatively useless. What you can do with that is feed it to Get-Date, and that produces a [DateTime] object, and that is very useful! Try this out:
$boottime=get-date (Get-CimInstance -ClassName win32_operatingsystem | select -expand lastbootuptime)
Then you can do something like:
IF($Disk.Lastwritetime -lt $boottime.addminutes(5)){"All is good!"} else {"There is a disturbance in the force!"}
Related
I have my first small project and I just started a PowerShell (total beginner).
We have three different shared C:\ drives and I need to output each disk storage info (e.g. total and free space) by using Powershell script.
Here is the script I made, but these three results are all the same even though they have different free spaces and total.
Can anyone please advise me on what is wrong with my ps script?
Plus, in the result, I don't want to display any other drives (e.g D and E) but only the C drive. How to do so?
[Script]
Set-Location -Path \\vm1\c$
Get-WmiObject -Class win32_logicaldisk | Format-Table DeviceId, #{n='Size'; e={[math]::Round($_.Size/1GB, 2)}}, #{n="FreeSpace"; e={[math]::Round($_.FreeSpace/1GB, 2)}}
Set-Location -Path \\vm2\c$
Get-WmiObject -Class win32_logicaldisk | Format-Table DeviceId, #{n='Size'; e={[math]::Round($_.Size/1GB, 2)}}, #{n="FreeSpace"; e={[math]::Round($_.FreeSpace/1GB, 2)}}
Set-Location -Path \\vm3\c$
Get-WmiObject -Class win32_logicaldisk | Format-Table DeviceId, #{n='Size'; e={[math]::Round($_.Size/1GB, 2)}}, #{n="FreeSpace"; e={[math]::Round($_.FreeSpace/1GB, 2)}}
[Result]
DeviceId Size FreeSpace
-------- ---- ---------
C: 473.95 114.22
D: 0 0
E: 0 0
DeviceId Size FreeSpace
-------- ---- ---------
C: 473.95 114.22
D: 0 0
E: 0 0
DeviceId Size FreeSpace
-------- ---- ---------
C: 473.95 114.22
D: 0 0
E: 0 0
Setting location to an UNC Path does not mean you're actually querying the win32_logicaldisk of that remote host, you need to use the -ComputerName Parameter to query the remote hosts information. Also worth noting, you should start using Get-CimInstance instead of Get-WmiObject (no longer available in newer versions of PowerShell).
As for displaying only the C drive, for this you can use -Filter. I've also added PSComputerName to your Format-Table returned properties so you can know which host the output belongs to.
$vms = 'vm1', 'vm2', 'vm3'
Get-CimInstance -Class win32_logicaldisk -Filter "DeviceID='C:'" -ComputerName $vms |
Format-Table #(
'PSComputerName'
'DeviceId'
#{ N='Size'; E={ [math]::Round($_.Size/1GB, 2) }}
#{ N='FreeSpace'; E={ [math]::Round($_.FreeSpace/1GB, 2) }}
)
Set-Location -Path \vm1\c$ does not work this way. it sets the default location on the filesystem for the current powershell session but does not influence get-wmiobject. to query remote computer you must use the parameter -computername.
you should use the cim cmdlets as they replace the wmi-object cmdlet. the parameter -computername supports an array as input so you only need to call get-wmiobject/get-ciminstance one time and if you only want to know about the C:\ drive, you can query for it:
$computers = #('vmName1','vmName2','nmName3')
Get-CimInstance -ComputerName $computers -Query "select freeSpace from win32_loogicaldoisk where deviceId='C:'" | select-object pscomputername,deviceid,freeSpace
I have written this script to get some information about my Virtual Machine. When I execute this script the last two cmdlets (lines) don't execute, but when I execute them alone they run properly.
Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | Select-Object DeviceID, SystemName,
#{n='Size (GB)'; e={$_.Size / 1GB -as [int]}},
#{n='Freespace (GB)'; e={$_.Freespace / 1GB -as [int]}};
$TotalMemory = (Get-CimInstance Win32_OperatingSystem).TotalVisibleMemorySize / (1024*1024)
$UsedMemory = (Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory / (1024*1024)
$TotalMemory = [math]::Round($TotalMemory,2)
$UsedMemory = [math]::Round($UsedMemory,2)
$TotalMemory
$UsedMemory
Get-CimInstance Win32_Processor | Select-Object -Property NumberOfCores;
Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Sum | Select-Object Sum;
What is the problem?
Any comments would be appreciated.
This question has been asked a million times. Format-table is being implicitly run, and it doesn't handle different sets of columns well. All the objects are there. You can pipe the whole script to format-list. You can put get-date at the very beginning. A known object with a format file at the beginning fixes it. You can output more than 4 properties with the first object. I tried to ask for a warning to be added a while ago: format-table should at least warn when it doesn't display properties #7871
Looks like out-gridview has similar struggles: Not all properties displayed
This appears to be one of PowerShell's weird quirks. I am not sure why it happens, but if someone else does I will happily edit my answer to include it.
You will need to specifically tell it to write the output to the console. There are a couple ways of doing this.
The first, and probably messiest, would be to pass it as a parameter to Write-Host or Write-Output.
Write-Host (Get-CimInstance Win32_Processor | Select-Object -Property NumberOfCores)
Write-Host (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Sum | Select-Object Sum)
(Another way of doing this would be to assign them both to variables, and pass the variables to the cmdlet)
The second way would be to pipe it to Write-Host or Write-Output
Get-CimInstance Win32_Processor | Select-Object -Property NumberOfCores | Write-Host
Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Sum | Select-Object Sum | Write-Host
And finally, the third (and in my opinion cleanest) way would be to pipe it to a code block that references the property directly
Get-CimInstance Win32_Processor | %{$_.NumberOfCores}
Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Sum | %{$_.Sum}
Hope this helps!
When I look at the Win32_ComputerSystem class, it shows loads of properties like Status, PowerManagementCapabilities, etc. However, when in PowerShell I do the below I only get back a couple:
PS C:\Windows\System32\drivers> Get-WmiObject -Class "Win32_computersystem"
Domain : YYY.com
Manufacturer : VMware, Inc.
Model : VMware Virtual Platform
Name : LONINEGFQEF58
PrimaryOwnerName : Authorised User
TotalPhysicalMemory : 2147016704
How can I see all properties?
Try this:
Get-WmiObject -Class "Win32_computersystem" | Format-List *
Get-WmiObject -Class "Win32_computersystem" | Format-List -Property *
For certain objects, PowerShell provides a set of formatting instructions that can affect either the table or list formats. These are usually meant to limit the display of reams of properties down to just the essential properties. However there are times when you really want to see everything. In those cases Format-List * will show all the properties. Note that in the case where you're trying to view a PowerShell error record, you need to use "Format-List * -Force" to truly see all the error information, for example,
$error[0] | Format-List * -force
Note that the wildcard can be used like a traditional wilcard this:
Get-WmiObject -Class "Win32_computersystem" | Format-List M*
If you want to know what properties (and methods) there are:
Get-WmiObject -Class "Win32_computersystem" | Get-Member
You can also use:
Get-WmiObject -Class "Win32_computersystem" | Select *
This will show the same result as Format-List * used in the other answers here.
I like
Get-WmiObject Win32_computersystem | format-custom *
That seems to expand everything.
There's also a show-object command in the PowerShellCookbook module that does it in a GUI. Jeffrey Snover, the PowerShell creator, uses it in his unplugged videos (recommended).
Although most often I use
Get-WmiObject Win32_computersystem | fl *
It avoids the .format.ps1xml file that defines a table or list view for the object type, if there are any. The format file may even define column headers that don't match any property names.
The most succinct way to do this is:
Get-WmiObject -Class win32_computersystem -Property *
You can list all properties of object using Four ways
Method-1: Format-Table
Get-Process | Format-Table -Property * -Wrap | Out-File abc.txt -Width 5000
OR
Get-Process | Format-Table * -Wrap | Out-File abc.txt -Width 5000
OR
Get-Process | FT * -Wrap | Out-File abc.txt -Width 5000
Method-2: Format-List
Get-Process | Format-List -Property *
OR
Get-Process | Format-List *
OR
Get-Process | FL *
Method-3: ConvertTo-Html
Get-Process | ConvertTo-Html | Out-File services1.html ; invoke-item services1.html
Method-4: Out-GridView
Get-Process | Select * | Out-GridView
Comparision of results to show parameters usage:
Format-Table/Format-List If you want to include all columns then always use -Property * parameter
Format-Table always capture output to a file using Out-File because sometime not all columns are included if you show result on screen.
FormatTable always specify reasonable width using -Width parameter otherwise column values are truncated in result.
Format-Table always use -Wrap so that column with large text is not trimmed but is shown in multiple line in long column.
CovertTo-Html properties with collections will only display Type Name of Collection insted of comma seperated values of collection items. This display is bit different from how Format-Table, Format-List & ConvertTo-Html display property with collection
I want to monitor python scripts in powershell. For that I am using Get-ProcessByName. I want to monitor individual python and JAVA scripts running and store its processId in a csv file according to individual script running. Get-ProcessByName lists all the the python or JAVA processes in the same row. How do I separate all the script names in different rows. What I am currently doing is-
$process = [System.Diagnostics.Process]
$outputTime = $process::GetProcessesByName($processName.ProcessName)[0].TotalProcessorTime.TotalMilliseconds
$name = ($process::GetProcessesByName($processName.ProcessName)[0]) | Select-Object -ExpandProperty ProcessName
$extra = Get-WmiObject -Class Win32_Process -Filter "name = '$name.exe'" | Select-Object -ExpandProperty CommandLine
Here in $extra I am getting names of all the python scripts.How do I seperate all the scripts
From my understanding Win32_Process already has all the information you need. You can use Select-Object and Calculated Properties to modify if required.
Get-WmiObject -Class Win32_Process |
Where-Object {$_.Name -eq 'python.exe'} |
Select-Object -Property Name,
#{Name = 'Script'
Expression = {$_.CommandLine -replace
'(.*)\\(?<py>.*\.py)|(.*)\ (?<py>.*\.py.*)',
'${py}'}
},
#{
Name = 'CpuTime'
Expression = {($_.KernalModeTime + $_.UserModeTime) / 10000000}
} |
Sort-Object -Property CpuTime -Descending
This would output something like
Name Script CpuTime
---- ------ -------
python.exe completion.py preview 1,65625
python.exe Untitled-1.py 0,015625
Of course this would work for java.exe or other, even multiple processes, as well. If you dont want to output the full CommandLine replace the first Calculated Property with CommandLine.
I would use this
Get-Process | where ProcessName -Match python
I'm simply trying to filter out the variables of the "PeakWorkingSetSize" process so that the output will ONLY be greater than 5000. No matter what combination I try, the numbers won't filter. Please help.
get-wmiobject -class Win32_Process | where-object {$_.PeakWorkingSetSize -gt "5000"} | format-table -auto
FIXED thanks to #Matt!
I actually still don't know what the problem was. XD
Here is the code that works:
get-wmiobject -class Win32_Process | where-object {$_.PeakWorkingSetSize -gt "5000" | format-table -property Name,PeakWorkingSetSize -auto
There is nothing wrong with this query and it should run as you have it written. Format-Table would be making for some odd output size some of those properties do not translate to string very well. Your query and selecting some specific properties yields expected results for me. 5000 is a really low number though.
PS C:\Users\Matt> get-wmiobject -class Win32_Process | where-object {$_.PeakWorkingSetSize -gt "5000"} | select name,processid,peakworkingsetsize
name processid peakworkingsetsize
---- --------- ------------------
System 4 15588
csrss.exe 580 35412
csrss.exe 732 47356
services.exe 780 11820
winlogon.exe 812 8832
.... output truncated.....
If something is still wrong I think we need to see your expected output to understand what is wrong.