The post PowerTip: Use PowerShell to display a percentage that has two decimal places appeared first on Scripting Blog.
]]>How can I use Windows PowerShell to display a number as a percentage that has two decimal places?
Use the f format specifier, and specify a pattern as “{0:p2}”. On the other side of the f format specifier, perform your percentage calculation. Here is an example:
PS C:\> “{0:p2}” f (1/10)
10.00 %
The post PowerTip: Use PowerShell to display a percentage that has two decimal places appeared first on Scripting Blog.
]]>The post Calculate percentage character frequencies from a text file by using PowerShell appeared first on Scripting Blog.
]]>This is the fifth post in a multipart series of blog posts that deal with how to determine letter frequency in text files. To fully understand this post, you should read the entire series in order.
Here are the posts in the series:
Okay, I will admit that I am just playing around, but I wanted to calculate the percentages of letter frequencies in a text file. For this example, I am using A Tale of Two Cities as a text file. You should refer to earlier blog articles about this topic so that what I write will have a chance of making sense.
The first thing I want to do is create a header for my report that I will display. To do this, I create an expanding here string. The basic here string is a bit fussy, but it begins with @” that is immediately followed by a return. Then it ends a new line that has “@.
Here’s the here string I use. The thing that is pretty cool is that it is the first thing I am defining in my script, and so neither the value of the $path
nor the total number of characters are yet determined. These will be evaluated when it is time to display the header. Until then, here’s the here string:
$header = @”
****************************************************************

 Letter Frequency Analysis
 of $path
 Analyzing $($total) characters …

****************************************************************
“@
The next thing I need to do is to read the contents of the text file and count the characters in the file. I assign the path of my file to a variable that I name $path. I then use GetContent to read the contents of the file, and I store the results in the $a variable. I now want to count how many characters are in the file. Because I have the entire contents of the text file in the $a variable, I can use that. Although, the count property contains the number of lines in the file, it does not contain the number of characters. The easy way to obtain this information is to use the MeasureObject cmdlet and call the Character switch to cause it to count characters. I then directly access the Characters property from the object returned from the MeasureObject cmdlet and store the number of characters in the $total variable. I then display the header here string that I previously stored in the $header variable. This code is shown here:
$path = ‘C:\fso\ATaleOfTwoCities.txt’
$a = GetContent $path
$total = ($a  measure Character).characters
$header
The code that I use to count the frequency of the characters was explained in an earlier article, so the code is shown here without additional comment:
$ajoined = $a join “`r”
$ajoinedUC = $ajoined.ToUpper()
$ajoinedUC.GetEnumerator() 
group NoElement  sort count Descending
So, now I use the SelectObject cmdlet, and I compute some custom properties to display. This is a great technique that works well with the pipeline. It takes the form of the following:
@{ LABEL = STRING ; EXPRESSION = SCRIPTBLOCK}
The first custom property simply displays the Name of the character. I add a column heading called “Character”, and under that column heading, I will display each character.
For the second property, I use the Count property that comes from my GroupObject cmdlet that groups all of the characters together. My SortObject command sorts these from largest number to smallest number. I place the Count property below a column heading that I call “Frequency”.
The last property is the most complex. I add a column heading called “Percent”. I calculate the percentage of representation by dividing the letter frequency by the total number of characters. I then use the builtin Percentage format specifier, p, in conjunction with the f format operator. I tell it to calculate percentage from my number and to display it to two decimal places of accuracy. The total Select statement is shown here:
Select @{L = ‘Character’; E = {$_.Name} },
@{L = ‘Frequency’ ; E = {$_.count} },
@{L = ‘Percent’ ; E = {“{0:p2}” f ($_.count / $total)}}
The complete code is shown here:
$header = @”
****************************************************************

 Letter Frequency Analysis
 of $path
 Analyzing $($total) characters …

****************************************************************
“@
$path = ‘C:\fso\ATaleOfTwoCities.txt’
$a = GetContent $path
$total = ($a  measure Character).characters
$header
$ajoined = $a join “`r”
$ajoinedUC = $ajoined.ToUpper()
$ajoinedUC.GetEnumerator() 
group NoElement  sort count Descending 
Select @{L = ‘Character’; E = {$_.Name} },
@{L = ‘Frequency’ ; E = {$_.count} },
@{L = ‘Percent’ ; E = {“{0:p2}” f ($_.count / $total)}}
The script is in the figure here:
When I run the script, the following output is shown:
I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. Also check out my Microsoft Operations Management Suite Blog. See you tomorrow. Until then, peace.
Ed Wilson
Microsoft Scripting Guy
The post Calculate percentage character frequencies from a text file by using PowerShell appeared first on Scripting Blog.
]]>The post PowerTip: Return remainder after dividing two numbers appeared first on Scripting Blog.
]]>How can use Windows PowerShell to divide two numbers and only return the remainder (called a modulo operation)?
In Windows PowerShell, the modulo operator is the % sign. Here are a few examples of how to use it:
PS C:\> 3 % 2
1
PS C:\> 5 % 2
1
PS C:\> 11 % 2
1
The post PowerTip: Return remainder after dividing two numbers appeared first on Scripting Blog.
]]>The post Weekend Scripter: Approximate the Value of Pi from a Polygon appeared first on Scripting Blog.
]]>Microsoft Scripting Guy, Ed Wilson, is here. Today we have a guest blog post from Firaz Samet in honor of Pi (π) Day. I will turn the blog over…
The Scripting Guy ran across my PowerShell Math Module on CodePlex, and he asked me if I would be interested in writing a blog post for Pi Day. I was also incidentally thinking about Pi Day, so this came at the right time. I hope you enjoy reading it.
First a little bit about me…
I am a senior software engineer at Microsoft where I work on Azure Stream Analytics. I have been playing around with Windows PowerShell since version 1.0 where I worked on SharePoint search management cmdlets. I love the power it provides by accessing the full .NET Framework and its rich set of builtin cmdlets and filtering capabilities. I concede that its syntax needed some time to get used to, but after I went past that, it became a natural way to solve my most common scripting and programming needs. One thing that has always frustrated me is that mathematical notation is a bit cumbersome. One reason I wrote a wrapper around Math.NET is to help ease interactive matrix manipulation.
Pi Day is celebrated around the world on March 3 (3.14). It aims to raise interest in math and especially π. This year’s will be even more significant (3.1415…). For more information, see Pi Day on Wikipedia.
In this post, I will talk about using Windows PowerShell to approximate π with polygons. I will also introduce matrix calculus with Math.NET Numerics, using a thin Windows PowerShell wrapper called Math.NET PowerShell.
The approximation of π that I introduce here starts with a square with sides that measure 2 units. It then approximates the area of the inscribed unit circle (radius is 1 unit, of which the area equals π) by constructing a regular polygon with double the number of sides with each iteration. This is done by chopping off triangles from each corner area, while keeping the apothem to 1.
By using the triangle properties and the trigonometric halfangle formulae for the tangent, we can deduce the following formula:
We now want to express the previous formula with Windows PowerShell. We will mainly use the [math] library’s power method, Pow(x, y). But to make the notation simpler, we will introduce a Windows PowerShell filter to make calling the Pow method closer to the mathematical notation:
filter ^([double] $y){[math]::Pow($_,$y)}
This means that expressing 2³ would look like (2 ^ 3) instead of [math]::Pow(2, 3). Parentheses are still required to prevent the pipeline syntax from affecting the remainder of the code. Similarly, will become (2 ^ .5).
We now use Windows PowerShell to develop the formula:
function halfTan($t){$t / (((($t ^ 2) + 1) ^ .5) + 1)}
function triangleArea($t){2 * ($t ^ 3) / (($t ^ 2) + 1)}
$t = 1
$t = halfTan $t
$a = ((2 ^ .5) – 1) ^ 2
$p = 4
0..25  %{
$i = $_;
$p= $a * 4 * (2 ^ $i);
"{0} t: {1} a: {2} ~pi:{3}" f $i,$t,$a,$p;
$t = halfTan $t;
$a = triangleArea $t;
}
On iteration 25, we reach the value of [math]::Pi.
24 t: 2.34066892682746E08 a: 2.56477909373991E23 ~pi:3.14159265358979
The iterative nature ofmakes using matrices an interesting proposition. For this reason, we will express it in the following matrix formula:
We will then use a thin Windows PowerShell wrapper around Math.NET Numerics called Math.NET PowerShell to calculate it in Windows PowerShell. The Windows PowerShell module offers a familiar way to initialize matrices (such as m "1 0;0 1" to initialize the identity matrix of order 2) and an easy approach to using the adequate Math.NET Numerics matrix type.
By default, Math.NET PowerShell uses the most memory conservative matrix type (sparse matrix with single precision). But the precision of this type is too low for our needs. Therefore, we will select the double precision type. This is achieved by using the following command:
SetMathNetMatrixType Double
When this is done, we express the formula using the previous matrix notation as follows:
function halfTan($t){$t / (((($t ^ 2) + 1) ^ .5) + 1)}
function triangleArea($t){2 * ($t ^ 3) / (($t ^ 2) + 1)}
$t = 1
$t = halfTan $t;
$p = m "4 4;0 0"
$area = m "1 0;0 2"
$area[1,0]=((2 ^ .5) – 1) ^ 2
$p=$p*$area
0..25  %{
"{0} t: {1} a: {2} ~pi:{3}" f $_,$t,$area[1,0],$p[0,0];
$t = halfTan $t;
$area[1,0] = triangleArea $t
$p=$p*$area
}
Running this script yields the same approximation for π.
~ Firaz
Thank you for writing a most interesting article, Firaz.
I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
The post Weekend Scripter: Approximate the Value of Pi from a Polygon appeared first on Scripting Blog.
]]>The post Weekend Scripter: PowerShell Does Scientific Notation appeared first on Scripting Blog.
]]>Microsoft Scripting Guy, Ed Wilson, is here. Today we have another guest blogger from the past—Clint Huffman. The keyboard is yours Clint…
In Performance Monitor, if a number in a field is too large to display, scientific notation is used to represent the number. A value such as 30,064,771,072 (28 GB) is too large for a field to display, so it is represented as 3.0064e+010. This is not an error—it is scientific notation. It indicates that the decimal point must be moved to the right the number of times indicated after the plus (+) symbol. There are 9 digits behind a gigabyte, so the number 2.8637e+010 in the following image appears as a “ball park” figure of 28 GB. But after dividing each thousands group by 1024, the true answer is 26.7 GB.
Math is hard for me, and I avoid it when I can, so I use Windows PowerShell to help me with it. Windows PowerShell can convert values in gigabytes and return the number in bytes or viceversa. For example, Windows PowerShell can convert 35GB into the full numeric value of 37580963840 in bytes.
It can convert scientific notation into a full numeric value. For example, in the previous image, I typed the value 3.7580e+010 from Perfmon into Windows PowerShell and it returned 37580000000. Knowing what this number is in gigabytes would be nice, so I divided it by 1GB (Windows PowerShell understands KB as kilobytes, MB as megabytes, and so on) to give me the number in gigabytes. In this case, it didn’t quite return an even 35 GB because the actual number was truncated by Perfmon, but it is close enough.
The editor in me has to add this…
Proper technical documentation is to use a space between the number and the unit, such as 10 GB. The reason I specified 35GB earlier is because in order for Windows PowerShell to interpret the number as 35 gigabytes, the space must be removed between number and the unit—35<space>GB will throw an error.
Enjoy!
~Clint
Cool. Thank you, Clint. I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
The post Weekend Scripter: PowerShell Does Scientific Notation appeared first on Scripting Blog.
]]>The post Using Windows PowerShell to Work with Numbers appeared first on Scripting Blog.
]]>Normally, I like to use the Weekend Scripter articles to do things that are more fun and interesting (I mean, after all it is the weekend for a large portion of the world). However, because the script I had intended to write did not work on my Windows 7 laptop, I felt like I needed to get something done before we head out to the horse show. I can only push my luck so far by taking my laptop to the show…
What did not work, you may ask? Well I had an idea about using another undocumented WMI class to get wireless signal strength. The WMI class MSNdis_80211_ReceivedSignalStrength is seen in the following image.
To use this WMI class in a Windows PowerShell script, use the GetWmiObject cmdlet as shown here:
PS C:\> GetWmiObject Class MSNdis_80211_ReceivedSignalStrength Namespace root/wmi
PS C:\>
The problem, as you can plainly see is that no information is returned…at least not on my 64 bit Windows 7 laptop. That is one of the problems with using undocumented WMI classes, one never knows if they will work or not.
Well, because my ideas for a really cool Weekend Scripter article were blown out of the water, I decided to open up Scripter and I came across a rather interesting email … admittedly it is not as cool as picking up your wireless signal strength via a script, but it may be a bit more useful. Here is the question … oh wait, the question is in Portuguese, and while that would be fine for my friends in Portugal, Brazil and Macau, it won’t work too well for my friends in the USA. So basically, what NG is asking is how he can use Windows PowerShell to perform mathematical calculations.
Here is my answer to him.
Windows PowerShell is designed for use by network administrators, and others who wish to work with computers. At its heart, it is an automation language that enables one to perform easy tasks such as shutting down computers, pinging computers, and starting and stopping services. Many of our network applications are using Windows PowerShell for their automation solution. This includes applications such as SharePoint server, Exchange Server, SQL Server, Internet Information Server, Active Directory Domain Services, and others.
This having been said, Windows PowerShell is a .NET Framework based application, and as a result has full support for the .NET Framework. From a mathematical perspective, you would do well to review the members of the system.math .NET Framework class. Here is a link to documentation on that class: http://msdn.microsoft.com/enus/library/system.math.aspx All of these members are static, which means they can be used directly from within Windows PowerShell. Here is an example of using the TAN static method to return the tangent of a 45degree angle:
PS C:\> [system.math]::tan(45)
1.61977519054386
PS C:\>
Note that I place system.math inside square brackets, and then use the double colon after that. The square brackets allow me to refer to the .NET Framework class directly without having to create an instance of it. The double colon is used to call the static method. Because Windows PowerShell assumes the system namespace, you do not need to type it if you do not wish. The decision as to whether to include it or not, will remain with you – do you remember that the math class is found in the system namespace? In general I have a tendency to forget these types of things, and therefore I tend to use the full name. You can use the static TAN method from the system.math .NET Framework class by leaving out the word system. This is shown here:
PS C:\> [math]::tan(45)
1.61977519054386
PS C:\>
Using the other static methods is just as easy. For example, if you need to know the cosign of a 90 degree angle, use the COS method. This is shown here:
PS C:\> [math]::COS(90)
0.44807361612917
PS C:\>
As a “computer” person, I like the ability to use the Pow method. This will give me a number raised to a certain power. For example, if I need to work with binary numbers … powers of two, I can do so like this:
PS C:\> [math]::pow(2,2)
4
PS C:\> [math]::pow(2,3)
8
PS C:\> [math]::pow(2,4)
16
PS C:\> [math]::pow(2,0)
1
PS C:\>
I can even write a script to display binary numbers. If I need to work with subnet masks, the script shown here can be used:
PS C:\> 0..7  ForeachObject {writehost $_ ([math]::pow(2,$_)) }
0 1
1 2
2 4
3 8
4 16
5 32
6 64
7 128
PS C:\>
I could do the same thing with base 8 and base 16 if I needed to do so. NG, that is all there is to working with methods from the system.math .NET Framework class. You do not have to use MSDN to look up the class. If you have an idea about what a method might do, you can use the GetMember cmdlet to retrieve the static methods, as shown here:
PS C:\> [math]  GetMember Static MemberType method
TypeName: System.Math
Name MemberType Definition
— ——— ———
Abs Method static System.SByte Abs(System.SByte value), static System.Int16 Abs(…
Acos Method static double Acos(double d)
Asin Method static double Asin(double d)
Atan Method static double Atan(double d)
Atan2 Method static double Atan2(double y, double x)
BigMul Method static long BigMul(int a, int b)
Ceiling Method static decimal Ceiling(decimal d), static double Ceiling(double a)
Cos Method static double Cos(double d)
Cosh Method static double Cosh(double value)
DivRem Method static int DivRem(int a, int b, System.Int32&, mscorlib, Version=2.0….
Equals Method static bool Equals(System.Object objA, System.Object objB)
Exp Method static double Exp(double d)
Floor Method static decimal Floor(decimal d), static double Floor(double d)
IEEERemainder Method static double IEEERemainder(double x, double y)
Log Method static double Log(double d), static double Log(double a, double newBase)
Log10 Method static double Log10(double d)
Max Method static System.SByte Max(System.SByte val1, System.SByte val2), static…
Min Method static System.SByte Min(System.SByte val1, System.SByte val2), static…
Pow Method static double Pow(double x, double y)
ReferenceEquals Method static bool ReferenceEquals(System.Object objA, System.Object objB)
Round Method static double Round(double a), static double Round(double value, int …
Sign Method static int Sign(System.SByte value), static int Sign(System.Int16 val…
Sin Method static double Sin(double a)
Sinh Method static double Sinh(double value)
Sqrt Method static double Sqrt(double d)
Tan Method static double Tan(double a)
Tanh Method static double Tanh(double value)
Truncate Method static decimal Truncate(decimal d), static double Truncate(double d)
PS C:\>
There are also two static properties that can be used. The two static properties are shown here:
PS C:\> [math]  GetMember Static MemberType property
TypeName: System.Math
Name MemberType Definition
— ——— ———
E Property static System.Double E {get;}
PI Property static System.Double PI {get;}
PS C:\>
You use the same methodology to access static properties:
PS C:\> [math]::pi
3.14159265358979
PS C:\>
If you want to find the circumference of a circle, you may remember the formula 2 x pi x radius. You can do exactly the same thing using Windows PowerShell. This is shown here where I get the circumference of a circle that has a radius of 2:
PS C:\> $pi = [math]::pi
PS C:\> $r = 2
PS C:\> 2*$pi*$r
12.5663706143592
PS C:\>
You can even create a function to give you the circumference of a circle if you wish. This is shown here:
PS C:\> function getcircumference {Param($r);Return (2*[math]::pi)*$r}
PS C:\> getcircumference r 2
12.5663706143592
NG, that is all there is to working with static properties from the system.math class. I also see my significant other standing by the door swinging the camera around like a whirligig so I should put my laptop to sleep and get ready to boogie. The cool thing is she has not given me time to put my laptop up; therefore, I will have to take it with me to the horse show—yes!
We invite you to join us tomorrow when we will begin talking about date manipulation. We would love for you to follow us on Twitter or Facebook. If you have any questions, send email to us at scripter@microsoft.com, or post them on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Ed Wilson and Craig Liebendorfer, Scripting Guys
The post Using Windows PowerShell to Work with Numbers appeared first on Scripting Blog.
]]>