Note 2: The key is adding @{Label = ; Expression
=}, then using -as to control the decimals. To see what I mean
substitute '-as [decimal]' for '-as[int]'.
Note 3: I chose to employ the variable $CPU to
highlight how Format-Table displays the value in the shortened form.
Note 4: Remember that -as accesses the .Net
Framework types.
Scenario: You want to measure the response time to a website, you
want the result as a whole number rather than with a string of confusing
decimals.
# PowerShell -As simple example Write-Host `n "Waiting for test
..." $Avg = 0 $Site = "www.google.com" $PingSite =
Test-Connection -count 5 $Site $Avg = ($PingSite | Measure-Object
ResponseTime -average) $Calc = ($Avg.average) -as [int]
Clear-host
Write-Host "Average response time to $Site is $Calc ms"
Note 5: To see the contrast try substituting -as
[Decimal] for -as [int].
Note 6: One area where -as is useful is with WMI
classes.
Guy
Recommends: WMI Monitor and It's Free!
Windows Management Instrumentation (WMI) is one of the hidden
treasures of Microsoft operating systems. Fortunately, Solarwinds
have created a
Free WMI Monitor so that you can discover these gems of performance
information, and thus improve your PowerShell scripts. Take the guess work out of which WMI counters to use when scripting the
operating system, Active Directory or Exchange Server.
As an alternative to -as you could employ System.Math. Here is
System.Math calculating a square root. The problem is we don't
need that number of decimals.
One benefit of using System.Math's Round is that you could
control the number of decimal places. However, my overall
point is that with PowerShell, as with the whole of Microsoft, there
are always multiple ways of achieving the same result.
»
Researching -As Type Properties
The secret of finding more information is to call for Get-Help About ...
Operators
Clear-Host Get-Help about_*_operators
Name ---- -------- -------- about_Arithmetic_Operators
about_Assignment_Operators about_Comparison_Operators
about_logical_operators about_type_operators
Clear-Host Get-Help about_type_operators
Summary of PowerShell -As
PowerShell uses an old C# trick and employs the -as type operator to
modify the underlying .Net Framework Type. The best example defining
the operator type is '-as [Int]' which reduce values with zillions of
decimal places to integers.
If you like this page then please share it with your friends
Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.
Windows Management Instrumentation (WMI) is one of the hidden
treasures of Microsoft operating systems.
Fortunately, Solarwinds
have created the
Free WMI Monitor so that you can actually see and understand these gems of
performance information. Take the guess work out of which
WMI counters to use for applications like Microsoft Active Directory,
SQL or Exchange Server.