Quantcast
Channel: Hey, Scripting Guy! Blog
Viewing all 3333 articles
Browse latest View live

PowerTip: Use PowerShell to Display Format for Short Date

$
0
0

Summary: Use Windows PowerShell to display the culture-specific format for a short date.

Hey, Scripting Guy! Question How can I use Windows PowerShell to display the format of a short date that is specific to the culture settings
           of my system?

Hey, Scripting Guy! Answer Use the Get-Culture cmdlet and select the DateTimeFormat and ShortDatePattern properties:

(Get-Culture).DateTimeFormat.ShortDatePattern


Formatting Date Strings with PowerShell

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about formatting date strings with Windows PowerShell.

Microsoft Scripting Guy, Ed Wilson, is here. It seems that different ways to display dates and times are in great supply. In fact, there are dozens of ways to do this. If I decide that I do not like the way a date or time displays, I can change it. In addition, the way a particular date style displays in one country is different than the way it displays in another country.

These differences are part of the culture settings. For example, the output from the Get-Date cmdlet appears differently depending on the UI culture settings. Here is an example:

PS C:\> Use-Culture de-de {get-date}

Mittwoch, 21. Januar 2015 12:23:40

PS C:\> Get-Date

Wednesday, January 21, 2015 12:23:45 PM

   Note  The Use-Culture function is not standard in Windows PowerShell or Windows. It comes from Lee Holmes’  
   PowerShell Cookbook module. I installed it from the PowerShell Gallery, but it is also available on PoshCode.

In general, I want the date to automatically change the way it displays based on culture settings because it helps avoid confusion. There may be times when I want to override this behavior. I can do this by directly formatting the date. I can use the ToStringmethod and specify the display pattern. The pattern MM – dd –yyyy specifies that I want the month, day, and year to appear in that order. The MM is case sensitive. Here is an example:

PS C:\> (Get-Date -Month 2 -Day 12 -Year 2015).tostring("MM-dd-yyyy")

02-12-2015

There can be a very real problem with this technique. In many regions, the day value comes first. So is the month February or is it December? Here is how the date displays when I use German UI culture settings:

PS C:\> Use-Culture de-DE {(Get-Date -Month 2 -Day 12 -Year 2015).tostring("MM-dd-yyyy")}

02-12-2015

According to their pattern, this is December 2, 2015. Here is the short date pattern:

PS C:\> [System.Globalization.CultureInfo]::GetCultureInfo(1031).DateTimeFormat.ShortDatePattern

dd.MM.yyyy

Now the culture settings use a hexadecimal value from the National Language Support API. Germany uses a hex value of 0x0407. If I convert it to a decimal format, it becomes 1031. This is shown here:

PS C:\> 0x0407

1031

I double check that I have the correct language settings by using the GetCulturalInfo static method:

PS C:\> [System.Globalization.CultureInfo]::GetCultureInfo(1031)

LCID             Name             DisplayName                                                    

----                 ----                  -----------                                                     

1031             de-DE            German (Germany)      

So if I really want to display a short date, I need to use a format specifier to tell Windows PowerShell to display a short date. In this way, it will be culture specific. On the MSDN page, Standard Date and Time Format Strings, I learn that the .NET short date specifier is “d”. So, I use the –format parameter of Get-Date, and the following appears:

PS C:\> get-date -Format d

1/21/2015

But what about using a different culture? Well, this is how it displays in culture de-DE:

PS C:\> Use-Culture de-DE {get-date -Format d}

21.01.2015

As a best practice, I should avoid creating my own date format strings if at all possible. If I use the built-in .NET date format specifiers, Windows PowerShell automatic displays it in the correct format. Here is a table of the .NET date format specifiers.

Format Specifier

Description

Examples

d

Short date pattern

2009-06-15T13:45:30 -> 6/15/2009 en-US

2009-06-15T13:45:30 -> 15/06/2009 fr-FR

2009-06-15T13:45:30 -> 2009/06/15 ja-JP

D

Long date pattern

2009-06-15T13:45:30 -> Monday, June 15, 2009 en-US

2009-06-15T13:45:30 -> 15 июня 2009 г. ru-RU

2009-06-15T13:45:30 -> Montag, 15. Juni 2009 de-DE

f

Full date pattern with short time pattern

2009-06-15T13:45:30 -> Monday, June 15, 2009 1:45 PM en-US

2009-06-15T13:45:30 -> den 15 juni 2009 13:45 sv-SE

2009-06-15T13:45:30 -> Δευτέρα, 15 Ιουνίου 2009 1:45 μμ el-GR

F

Full date pattern with long time pattern

2009-06-15T13:45:30 -> Monday, June 15, 2009 1:45:30 PM en-US

2009-06-15T13:45:30 -> den 15 juni 2009 13:45:30 sv-SE

2009-06-15T13:45:30 -> Δευτέρα, 15 Ιουνίου 2009 1:45:30 μμ el-GR

g

General date pattern with short time pattern

2009-06-15T13:45:30 -> 6/15/2009 1:45 PM en-US

2009-06-15T13:45:30 -> 15/06/2009 13:45 es-ES

2009-06-15T13:45:30 -> 2009/6/15 13:45 zh-CN

G

General date pattern with long time pattern

 2009-06-15T13:45:30 -> 6/15/2009 1:45:30 PM en-US

2009-06-15T13:45:30 -> 15/06/2009 13:45:30 es-ES

2009-06-15T13:45:30 -> 2009/6/15 13:45:30 zh-CN

M, m

Month/day pattern

2009-06-15T13:45:30 -> June 15 en-US

2009-06-15T13:45:30 -> 15. juni da-DK

2009-06-15T13:45:30 -> 15 Juni id-ID

O, o

Round-trip date/time pattern

2009-06-15T13:45:30  --> 2009-06-15T13:45:30.0000000-07:00

2009-06-15T13:45:30 --> 2009-06-15T13:45:30.0000000Z

2009-06-15T13:45:30 2009-06-15T13:45:30.0000000

2009-06-15T13:45:30-07:00 --> 2009-06-15T13:45:30.0000000-07:00

R, r

RFC1123 pattern

2009-06-15T13:45:30 -> Mon, 15 Jun 2009 20:45:30 GMT

s

Sortable date/time pattern

2009-06-15T13:45:30 -> 2009-06-15T13:45:30

2009-06-15T13:45:30 -> 2009-06-15T13:45:30

t

Short time pattern

2009-06-15T13:45:30 -> 1:45 PM en-US

2009-06-15T13:45:30 -> 13:45 hr-HR

2009-06-15T13:45:30 -> 01:45 ar-EG

T

Long time pattern

2009-06-15T13:45:30 -> 1:45:30 PM en-US

2009-06-15T13:45:30 -> 13:45:30 hr-HR

2009-06-15T13:45:30 -> 01:45:30 م ar-EG

u

Universal sortable date/time pattern

2009-06-15T13:45:30 -> 2009-06-15 20:45:30Z

U

Universal full date/time pattern

2009-06-15T13:45:30 -> Monday, June 15, 2009 8:45:30 PM en-US

2009-06-15T13:45:30 -> den 15 juni 2009 20:45:30 sv-SE

2009-06-15T13:45:30 -> Δευτέρα, 15 Ιουνίου 2009 8:45:30 μμ el-GR

Y, y

Year month pattern

2009-06-15T13:45:30 -> June, 2009 en-US

2009-06-15T13:45:30 -> juni 2009 da-DK

2009-06-15T13:45:30 -> Juni 2009 id-ID

That is all there is to using .NET date format specifiers. Date Time Week will continue tomorrow when I will talk about more cool stuff.

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

PowerTip: Use PowerShell to Display date Format for Specific Culture

$
0
0

Summary: Learn how to use Windows PowerShell to display date formatting for a specific culture.

Hey, Scripting Guy! Question How can I use Windows PowerShell to see the short date pattern for a specific culture without
           changing my UI culture settings?

Hey, Scripting Guy! Answer Use the CultureInfo class from System.Globalization, call the GetCultureInfo static method
           while passing a culture number, and choose the ShortDatePattern property from the DateTime 
           format object, for example:

[System.Globalization.CultureInfo]::GetCultureInfo(1031).DateTimeFormat.ShortDatePattern

Create Custom Date Formats with PowerShell

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about creating custom date formats with Windows PowerShell.

Microsoft Scripting Guy, Ed Wilson, is here. One of the cool things about working with Windows PowerShell is that it is highly configurable. In short, if there is something that I do not like, I can change it. Most of the time, that change is relatively simple to make. So when working with dates and times, there are lots of standardized ways of displaying the information.

            Note  Also see Formatting Date Strings with PowerShell.

But if one of these standardized ways doesn’t work out, I am not stuck. I can use the UFormat parameter to change the output to my needs. Keep in mind, that any formatting of the date/time output changes it from a DateTime object to a string. This means that I want to make sure I make calculations and computations with my date as an object before I output it as a string.

The UFormat parameter uses Unix date formatting strings. I can, for example, display the date and the time by using the cstring. Keep in mind that these are case sensitive, and I proceed them with the percentage sign. So, to display an abbreviated day of the week and month name, followed by the day of the month, the time, and the year, I use %c. This is shown here:

PS C:\> get-date -UFormat %c

Thu Jan 22 15:39:36 2015

The cool thing is that for this command, I do not need to use quotation marks because Windows PowerShell expects me to supply a formatting string.

I can also display a standard date output with respect to the local culture settings, but it does not appear to work properly. So I use the .NET formatting specifiers for this. This is shown here:

PS C:\> Use-Culture de-DE {get-date -UFormat %x}

01.22.15

PS C:\> Use-Culture de-DE {get-date -Format d}

22.01.2015

By using the UFormat codes, I can also control the way time outputs. For example, as shown here, I can display the time in 12-hour format by using %r.

PS C:\> get-date -UFormat %r

04:33:09 PM

I can also display a 24-hour format. A capital R outputs the hour and minute as shown here:

PS C:\> get-date -UFormat %R

16:33

If I want to output the hour, minute, and seconds in 24-hour format, I use either capital T or capital X as shown here:

PS C:\> get-date -UFormat %T

16:35:23

PS C:\> get-date -UFormat %X

16:35:27

Most of the time when I use the UFormat strings, however, it is because I want to customize my output string. They are very flexible. I choose the parts of the date and time that I want to output. For example, suppose I need the year in four digits, month, day, hours in 24-hour format, minutes, and seconds, and I want them separated by an underscore:

PS C:\> get-date -UFormat "%Y_%m_%d_%H_%M_%S"

2015_01_22_16_44_07

As you can see, there is a lot of flexibility. In fact, I can format the date and time any way that I can imagine.

Here is a table that documents the Unix format strings.

            Note  These letter codes are case sensitive.

Letter code

Meaning

Example

c

Date and time

Fri Jun 16 10:31:27 2015

D

Date in mm/dd/yy format

06/14/06

x

Date in standard format for locale

09/12/15 for English-US

C

Century

20 for 2015

Y, G

Year in 4-digit format

2015

y, g

Year in 2-digit format

15

b, h

Month name - abbreviated

Jan

B

Month name - full

January

m

Month number

06

W, U

Week of the year - zero based

00-52

V

Week of the year - one based

01-53

a

Day of the week - abbreviated name

Mon

A

Day of the week - full name

Monday

u, w

Day of the week - number

Monday = 1

d

Day of the month - 2 digits

05

e

Day of the month - digit preceded by a space

 5

j

Day of the year

1-366

p

AM or PM

 PM

r

Time in 12-hour format

09:15:36 AM

R

Time in 24-hour format - no seconds

17:45

T, X

Time in 24 hour format

17:45:52

Z

Time zone offset from Universal Time Coordinate UTC

07

H, k

Hour in 24-hour format

17

I, l

Hour in 12 hour format

05

M

Minutes

35

S

Seconds

05

s

Seconds elapsed since January 1, 1970

00:00:00 1150451174.95705

n

newline character

\n

t

Tab character

\t

That is all there is to using UFormat strings to format dates. That is also the end of Date Time Week. Join me tomorrow when I will talk about the changing nature of documentation.

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

PowerTip: Pipe String to Get-Date

$
0
0

Summary: Pipe a string to the Windows PowerShell Get-Date cmdlet to convert it to a DateTime object.

Hey, Scripting Guy! Question How can I use Windows PowerShell to convert a date that is in a string format to a DateTime object?

Hey, Scripting Guy! Answer Create a pipeline, for example:

"11/14/2015" | get-date 

Weekend Scripter: The Changing Nature of Documentation

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about the changing nature of documentation.

Microsoft Scripting Guy, Ed Wilson, is here. This week, we announced Microsoft HoloLens during the Windows 10: The Next Chapter webcast. I mean, I want one—badly.

This is going to be an incredible year. The excitement of holographic computing has me thinking about Star Trek. Of course last year, we introduced a holodeck—so the future is now, so to speak.

But then I was thinking, "Does one ship a stack of books along with the HoloLens?" It doesn’t make sense, I suppose. Back when we shipped Windows NT 3.51, there were books and books and books of documentation for the product. I mean, stacks of disks and stacks of books. Here is a picture I had our archives people dig up:

Image of books

In fact, when I bought my first computer (an Osborn 1), it came with lots of books. My most recent laptop purchase, however, did not come with anything but a stack of legal disclaimers. My toothbrush came with more documentation. (Actually, I was wondering about toothbrush documentation, and I did a quick Bing search. 7,500,000 pages returned, including YouTube videos and pages of documentation from the Centers for Disease Control and Prevention.)

Anyway, I did not bother to read all that stuff, and usability studies found that most people did not bother to read it either.

When I get ready to install and configure a new software application, I do not want to read through a bunch of marketing stuff telling me how great the software is. Dude, I already bought it. What I want is a quick start guide that tells me exactly what I need to do to quickly get the thing up and running. But that is just me. Other people prefer (in fact, they need) a features guide to tell them what features are available. Others need marketing material so they can help sell the application to their management. Still other people are visual learners, and they need a picture, a diagram, or a video that shows them exactly how to configure the application.

As far as I am concerned, images are great. I also like samples of working code. I still have nightmares about some documentation that says: To print, click the Print button from the Print menu. But when I look at the application, I cannot find the Print menu. I mean clicking the Print button would be an obvious choice, but where is the silly thing hidden? And the documentation didn’t tell me.

Many times, I want to hear real advice from people who use the product for a living. This is why I love blogs so much. In the Windows PowerShell world, most of the MVPs maintain blogs, or they contribute to blogs.

In the old days, documentation was pretty much a book that came as a big box of disks. Today, documentation is much more customized, and it comes in many forms. In fact, documentation comes in the form of wiki articles, blog posts, videos, webcasts, discussion forums, and various forms of social media. The cool thing is that I can find exactly what I need pretty much when I need it. All I need is access to a search engine and the Internet—which is pretty much all of the time.

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 

PowerTip: View PowerShell Help Online

$
0
0

Summary: View Windows PowerShell cmdlet Help online.          

Hey, Scripting Guy! Question How can I view Windows PowerShell Help in my web browser?

Hey, Scripting Guy! Answer The –Online parameter with the Get-Help cmdlet opens the latest online Windows PowerShell Help
            in your web browser, for example:

Get-Help Get-Command -Online

2014 Honorary Scripting Guys Announced

$
0
0

Summary: The Honorary Scripting Guys for 2014 are announced.

Microsoft Scripting Guy, Ed Wilson, is here. I have been pretty busy, with missing work because of my ear surgery and the holidays and all, so I enlisted the help of the Scripting Wife, Teresa, to write the latest Honorary Scripting Guys post. I gave her the names and she did the rest. So here's Teresa...

Hello everyone,

You know that I do not try to hide things about myself nor do I try to embellish my qualities—I am what I am. I have strong points and weak points. Writing is not one of my strong points and repetition is one of the most useless things all around, in my opinion. So I am going to start by snagging some of Ed’s words from two years ago and reuse them:

What does it take to become an official Honorary Scripting Guy? It takes an extreme commitment to the scripting community, a remarkable dedication helping to spread the good word about Windows PowerShell, and a relentless pursuit of excellence in producing exceptional content. To read more about the Honorary Scripting Guys, see:

Image of Scripting Guy

Which brings us up-to-date. Now without much delay, I am happy to introduce you to three new Honorary Scripting Guys:

  • Ian Farr
  • Ashley McGlone
  • Gary Siepser

Here is a little more information about the new Honorary Scripting Guys. If you click the link on their names, it will take you to their Hey, Scripting Guy! Blog posts.

Ian Farr

Ian is a Microsoft premier field engineer (PFE). He started writing UNIX shell scripts to automate simple tasks. Then as a Windows IT pro, he discovered VBScript, and it ignited a passion for automation. Over the years, he has used batch files, KiXtart, JScript, HTAs, Perl, JavaScript, and Python. Ian loves solving problems with scripts, and he has written code for several large enterprise environments. As a premier field engineer at Microsoft, he teaches Windows PowerShell and helps customers with their own scripts.

Photo of Ian Farr

Ashley McGlone

Ashley is a premier field engineer (PFE) for Microsoft. He started writing code on a Commodore VIC20 in 1982, and he has been hooked ever since. Today he specializes in Active Directory and Windows PowerShell, and he helps Microsoft Premier Customers reach their full potential through risk assessments and workshops. Ashley’s favorite workshop to teach is Windows PowerShell Essentials, and his TechNet blog focuses on real-world solutions for Active Directory by using Windows PowerShell.

Blog: Goatee PFE
Twitter: @GoateePFE

Gary Siepser:

Gary is a senior premier field engineer for Microsoft, specializing in everything PowerShell. These days, he teaches several Windows PowerShell classes to Microsoft customers. Check out Microsoft Premier Support Services to learn more.

Twitter @powerShellPFE

Ed also gave me a list of previous Honorary Scripting Guy recipients who have made a significant contribution to the Hey, Scripting Guy! Blog in 2014. If they were not already Honorary Scripting Guys, they would be!

Thanks to all the guest bloggers.

~Teresa 

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 


PowerTip: Windows PowerShell Survival Guide

$
0
0

Summary: Find the Windows PowerShell Survival Guide. 

Hey, Scripting Guy! Question Where can I find a community-based resource that links to all the essentials?

Hey, Scripting Guy! Answer Check out the Windows PowerShell Survival Guide on the TechNet Wiki. It contains links to dozens of
           Windows PowerShell resources.

Understanding Numbers in PowerShell

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about numbers in Windows PowerShell.

Hey, Scripting Guy! Question Hey, Scripting Guy! One of the things that is frustrating to me with Windows PowerShell is the way that it handles numbers. For example, I want to know the percent of processor utilization for something, and it displays a number that is like fifty million numbers long. What is up with that? Why can’t Windows PowerShell just tell me something useful?

—SP

Hey, Scripting Guy! Answer Hello SP,

Microsoft Scripting Guy, Ed Wilson, is here. Today it is cold and raining outside. I decided to make a cup of red berry tea. It does not have any caffeine, and it seems to be just thing for a cold, rainy morning. I do not mix my own red berry tea—this is one of the teas that I buy already mixed. I still had a nice bag I brought back from Hamburg. Anyway, I am sitting here sipping a nice cup of red berry tea and I came across your email to scripter@microsoft.com. It is perfect because today I am kicking off Numbers Week.

There are many cmdlets and functions built-in to Windows PowerShell that display a formatted number. But there are other interfaces that return the raw number. The reason for this is that I may want to display information to 1, 2, 3, or even 5 decimal places, depending on what I am monitoring. In many cases, I work with the entire raw number so I can get a better view of what exactly might be taking place. For this reason, it makes sense to understand a bit about the types of numbers in Windows PowerShell.

Numeric types

There are many types of numbers in Windows PowerShell. Most of the time, I do not need to know anything about the different types of numbers because Windows PowerShell performs the type conversion behind the scenes. However, a good understanding of the types of numbers can be useful, and it is certainly useful from a troubleshooting perspective. There are actually three numeric types that Windows PowerShell uses:

  • Decimal types
  • Integral types
  • Floating-point types

Decimal types

Decimals are a 128-bit data type. Decimals can be positive or negative, and they are more precise than floating point types. Decimals are commonly used in financial or monetary calculations. A decimal is an instance of the System.Decimal .NET Framework type, and therefore, it has static properties I can use to determine the range. Here is the minimum and maximum range of the decimal numeric type:

PS C:\> [decimal]::MinValue

-79228162514264337593543950335

PS C:\> [decimal]::MaxValue

79228162514264337593543950335

This range is commonly expressed as (-7.9 x 1028 to 7.9 x 1028) / (100 to 28).

Integral types

Integral types come in the signed and the unsigned variety (except for the char, which is an 16-bit Unicode character). Integers range in size from 8-bit integers to 64-bit integers.

An sbyte is a signed 8-bit integer, and it ranges from -128 to 127. A byte is an unsigned 8-bit integer that ranges from 0 to 255. The following code illustrates this:

PS C:\> [byte]::MinValue

0

PS C:\> [byte]::MaxValue

255

PS C:\> [sbyte]::MinValue

-128

PS C:\> [sbyte]::MaxValue

127

A short is a signed 16-bit integer, and a ushort is an unsigned 16-bit integer. To obtain a short, I use the System.Int16 .NET Framework class, and to obtain a ushort, I use System.uInt16. I can use the [int16] and the [uint16] type accelerators for this purpose. The following code illustrates their ranges:

PS C:\> [int16]::MinValue

-32768

PS C:\> [int16]::MaxValue

32767

PS C:\> [uint16]::MinValue

0

PS C:\> [uint16]::MaxValue

65535

Int is the default numeric data type in Windows PowerShell. It is a 32-bit signed integer. The .NET Framework class is System.Int32. Because it is the default numeric data type, I can use [int32] or [int]. There is also an unsigned 32-bit integer. It is the System.uint32 .NET Framework type. I can use [uint32] to create an unsigned 32-bit integer. The ranges of these numbers are shown here:

PS C:\> [int32]::MinValue

-2147483648

PS C:\> [int32]::MaxValue

2147483647

PS C:\> [int]::MaxValue

2147483647

PS C:\> [uint32]::MinValue

0

PS C:\> [uint32]::MaxValue

4294967295

A long is a signed 64-bit integer and a ulong is an unsigned 64-bit integer. The .NET Framework classes are System.Int64 and System.uInt64. I can therefore use [int64] or [uint64] to create the long or the ulong data types. The following code illustrates the ranges of the long and ulong:

PS C:\> [int64]::MinValue

-9223372036854775808

PS C:\> [int64]::MaxValue

9223372036854775807

PS C:\> [uint64]::MinValue

0

PS C:\> [uint64]::MaxValue

18446744073709551615

Floating-point types

There are two floating-point types that Windows PowerShell uses: the float and the double. The float uses seven digits of precision and the double uses 15–16 digits of precision. The float type is an instance of the System.Single .NET Framework value type, and the double is an instance of the System.Double type. I can therefore use [single] and [double] to constrain numbers to these types. The following code illustrates their minimum and maximum values:

PS C:\> [single]::MinValue

-3.402823E+38

PS C:\> [single]::MaxValue

3.402823E+38

PS C:\> [double]::MinValue

-1.79769313486232E+308

PS C:\> [double]::MaxValue

1.79769313486232E+308

The following table summarizes the numeric value types, their ranges, sizes, and .NET Framework types.

Type

Range

Size or Precision

.NET Framework type

Decimal

(-7.9 x 1028 to 7.9 x 1028) / (100 to 28)

28 – 29 significant digits

System.Decimal

Sbyte

-128 to 127

Signed 8-bit

System.Sbyte

Byte

0 to 255

Unsigned 8-bit

System.Byte

Char

U+0000 to U+ffff

Unicode 16-bit

System.Char

Short

-32,768 to 32,767

Signed 16-bit

System.Int16

Ushort

0 to 65,535

Unsigned 16-bit

System.Uint16

Int

-2,147,483,648 to 2,147,483,647

Signed 32 bit

System.Int32

Uint

0 to 4,294,967,295

Unsigned 32-bit

System.Uint32

Long

9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Singed 64-bit

System.Int64

Ulong

0 to 18,446,744,073,709,551,615

Unsigned 64-bit

System.Uint64

Float

±1.5e−45 to ±3.4e38

7 digits

System.Single

Double

±5.0e−324 to ±1.7e308

15 – 16 digits

System.Double

That is all there is to using Windows PowerShell to format numbers, SP. Numbers Week will continue tomorrow when I will talk about more cool stuff.

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 

PowerTip: Round Number Up or Down with PowerShell

$
0
0

Summary: Easily use Windows PowerShell to round a number up or down.  

Hey, Scripting Guy! Question I want only a whole number returned, so I want the number rounded up or down as appropriate.
           How can I do this with Windows PowerShell?

Hey, Scripting Guy! Answer Cast the number as an integer, and Windows PowerShell will round the number up or down
           as appropriate, for example:

PS C:\> [int]22.4

22

PS C:\> [int]22.5

22

PS C:\> [int]22.6

23

Working with Fixed Number Sizes in PowerShell

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about working with fixed number sizes in Windows PowerShell.

Hey, Scripting Guy! Question Hey, Scripting Guy! I have a script that returns a specific type of number, so I added a type constraint on the variable that holds the number. The problem is that sometimes when I run the script, I get errors. I cannot figure this out. Can you help me?

—BG

Hey, Scripting Guy! Answer Hello BG,

Microsoft Scripting Guy, Ed Wilson, is here. We have not had any snow this year here in Charlotte, North Carolina. This is good news, and of course, bad news. The good news is that because the city is rarely prepared for snow storms, any snow at all causes major problems. The bad news is that we do not get to see snow very often—maybe once every three or four years, if we are lucky. Personally, I enjoy looking at snow from the windows, but I really do not like it when I have to get outside in it. Snow causes lots of problems if you are not expecting it, and if you are not prepared for it.

We run into much the same issue when it comes to constraining number types in Windows PowerShell. Because Windows PowerShell has a greatly enhanced adaptive-type system, and it can change the types of the objects that lay under the covers, one rarely needs to deal with things (such as a type mismatch) that plague other object-oriented languages.

This, of course, has good and bad effects. At times, if I am not really paying attention, I can get tripped up if I am not expecting the object transformation. To be honest, this has only happened to me a couple of times, and it was usually because I was trying to do something pretty tricky in the first place. One way around this, is to place a type constraint on the object, and then force it to raise an error message when the change takes place. This can be helpful for spotting these sorts of changes.

Note  To be clear, most of the time (in fact, I would say over 90 percent of the time), it is best to allow Windows PowerShell to manage the types.

Changing number types

The default number type in Windows PowerShell is an Int, and that is also an Int32. If the number becomes too big, Windows PowerShell will change the number from an Int to a Double. I wrote the following script to illustrate the point:

function get-double

{

 Param($a)

  $b = $b + $a

  "now $($b.gettype())"

  if ($b -eq 'Infinity') {Return}

  get-double $b

}

I load the function and call it by passing the number 2. This is shown here:

Get-Double 2

When I run the script, it runs for a few seconds and then stops when it reaches Infinity. Part of the output is shown here:

Image of command output

It is clear from the output that when Windows PowerShell reaches the maximum value of Int32, it changes the type of number that is contained inside the variable $b to a Double. Most of the time, this is the behavior I want.

Constraining the type of the number in a variable

But suppose that the value of $b should never become greater than a certain value, and that number is an Int. The script appears to work, but it takes a long time to complete. As I troubleshoot the script, I decide to constrain the value of $b to a number type that makes sense for my script. I'm going to try an Int16.

In the following script, I use the type constraint [int16] to ensure that the variable $b only holds an Int16.

function get-int

{

 Param($a)

 $erroractionpreference = "stop"

  [int16]$b = $b + $a

  "now $b"

  get-int $b

}

If the value in $b becomes greater than 32768, an error arises. Because the error that arises is not a terminating error, the script would run and run and run, but continue to display errors. That is not the behavior I want, so I changed the value of $errorActionPreference from "continue" to "stop". The output is shown here:

Image of command output

By constraining the type of number that I store in the $b variable, it becomes obvious that the problem with my script is that I am, somehow, getting a number that is too big. In reality, a problem such as that is usually traceable to one of the following:

  • A loop that runs too long (an upper limit is not properly controlling the loop execution)
  • Variables that are not being properly initialized prior to reuse

Because Windows PowerShell has an adaptive-type system, such problems are often difficult to see. They show themselves as weird and inconsistent output, or you may have a script that appears to work, but it takes a really long time to complete. Constraining my types can make troubleshooting easier and enable me to more readily spot such problems.

BG, that is all there is to using numeric type constraints. Numbers Week will continue tomorrow when I will talk about more cool stuff.

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 

PowerTip: Use Parentheses to Override Operator Precedence

$
0
0

Summary: Use parentheses to override operator precedence in Windows PowerShell.

Hey, Scripting Guy! Question How can I ensure that a math expression that keeps returning incorrect information will work properly in
           Windows PowerShell?                                               

Hey, Scripting Guy! Answer In Windows PowerShell (as in other languages), math operators have a precedence. Therefore, division
           comes before addition. If you want to override this behavior, group with parentheses, for example:

PS C:\> 2 + 9 / 3

(2 + 9)/3

5

3.66666666666667

Formatting PowerShell Decimal Places

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using strings to format the display of decimal places in Windows PowerShell.

Hey, Scripting Guy! Question Hey, Scripting Guy! One of the things I have a problem with is when I get numbers that have a lot of decimal places. I mean, how do I really get rid of them—at least properly? I have done things like convert them to integers, but that loses me all of the decimal places. I have also tried using Trimor other string techniques with mixed success. I would love to see how a real pro does it. Can you help me?

—PA

Hey, Scripting Guy! Answer Hello PA,

Microsoft Scripting Guy, Ed Wilson, is here. Like a lot of people, I like to work with a plan. I need to know what I am going to be doing a week from now, a month from now, and even a year from now. But when I have a plan in place, I do not give it a lot of extra thought. I mean, that is what the planning stage is for, right? To plan?

Well, PA, a similar thing happens when I am working with Windows PowerShell. I like to know where I am going, but then I hold off until just when I need to do something before I actually do it. What am I talking about?

Well numbers, for one thing.

Using a custom format string to control decimal places

When I use a custom format string to control the number of decimal places, I change the underlying type from a number type to a string. In the following example, I convert from a Double to a String:

PS C:\> $d = 1.11

PS C:\> $d.GetType()

IsPublic IsSerial Name                         BaseType                

-------- -------- ----                               --------                

True     True     Double                         System.ValueType        

PS C:\> $s = (1.11).tostring("#.#")

PS C:\> $s.GetType()

IsPublic IsSerial Name                          BaseType                

-------- -------- ----                               --------                

True     True     String                           System.Object

This change might be OK if I am sending the output to its final destination—for example, displaying it to the Windows PowerShell console or printing it on a printer. But if I am storing the data, perhaps in a database, it is probably best to store the actual number. This is because I can easily create a report from the database that displays only one decimal place, but I have no idea what the second decimal place might be.

Additionally, I could run into other problems trying to perform math operations on strings instead of numbers. So as a best practice, put it off and make these types of conversions the last thing you do to your data.

However, when I am trying to read data, I have a problem keeping track of more than two or three decimal places. The numbers begin to run together. So if I am trying to gain a quick impression, I like to easily change to one or two decimal places. To do this, I use a custom number format string.

The ToStringmethod is everywhere in Windows PowerShell—even number types contain a ToStringmethod. The great thing is that I can easily override the method with my own custom format string. Here is an example of changing a number that has two decimal places to a number that contains a single decimal place:

PS C:\> (1.11).tostring("#.#")

1.1

All I need to do is use the pound sing ( # ) where I want a digit to appear. So in the example, I had two decimal places, but I only wanted one.

If I have numbers on the right side of the decimal, I need only a single pound sign. On the left side of the decimal, everything becomes rounded up if there are additional numbers, or nothing happens if there are no numbers. The following example illustrates how I limit my output to two decimal places:

PS C:\> $a = 1.1, 2.22, 3.333, 4.4444, 5.55555

PS C:\> $a | % {$_.ToString("#.##")}

1.1

2.22

3.33

4.44

5.56

In the previous output, 5.55555 rounds up to 5.56, but 4.4444 rounds down to 4.44. The number 1.1 displays as 1.1, even though my format string of “#.##” contains two pound signs.

If I am working with output from a Windows PowerShell cmdlet, I can use the same technique by using a customized property. I can do this with Select-Object, Format-Table, or Format-List (and even with Out-GridView).

In the following image, I see the CPU time of several process reports as 0.03, and 0.02.

Image of command output

As shown here, if I format the output so that it only displays a single decimal place, I lose much of the CPU output:

Get-Process |

Where CPU |

Sort CPU -Descending |

Select-Object ProcessName,

@{l='cpu';e={($_.cpu).tostring("#.#")}}

The script and its associated output are shown here:

Image of command output

PA, that is all there is to using custom format strings to control the display of decimal places in Windows PowerShell. Numbers Week will continue tomorrow when I will talk about more cool stuff.

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 

PowerTip: Format Decimal Numbers in PowerShell

$
0
0

Summary: Learn how to display a specific number of decimal points in Windows PowerShell.

Hey, Scripting Guy! Question How can I use Windows PowerShell to display only one decimal place on a number that currently has two?

Hey, Scripting Guy! Answer Use a custom number format string with the ToString method from the number, for example:

PS C:\> (1.11).tostring("#.#")

1.1


PowerTip: Round a Number with PowerShell

$
0
0

Summary: Use Windows PowerShell to round numbers to a specific decimal place.

Hey, Scripting Guy! Question How can I use Windows PowerShell to round a number to a specific number of decimal places, and continue to
           have a number instead of converting it to a string.

Hey, Scripting Guy! Answer Use the Round static method from the System.Math class. By default, it does not display decimal places, but
           you can easily change that behavior. The following code illustrates this procedure:

PS C:\> $a = 111.2226

PS C:\> [math]::Round($a)

111

PS C:\> [math]::Round($a,2)

111.22

PS C:\> [math]::Round($a,3)

111.223

Using PowerShell and Standard Number Formats

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using standard number formats.

Hey, Scripting Guy! Question Hey, Scripting Guy! I love using Windows PowerShell. I use it for everything. My problem is that it does not do everything automatically. For example, I use the Get-Volume cmdlet a lot to check on disk space, but I need to do a manual calculation to see the percentage of free space. This involves basically writing a script and dividing the numbers, multiplying by a hundred, and then trimming all the excess decimal places. Is there anything you can do to help me?

—AV

Hey, Scripting Guy! Answer Hello AV,

Microsoft Scripting Guy, Ed Wilson, is here. This morning I am sitting here sipping a beautiful cup of Darjeeling tea. I added a cinnamon stick to it, and that is it. It is robust, complex, and deeply relaxing. I am also munching on a freshly made bagel, with just a bit of cream cheese on it. I am checking my email on my Surface Pro 3, and looking outside wondering where the snow is. No snow here in Charlotte. Nope, not a flake.

Anyway, on cool, crisp mornings such as this, it is nice to open the Windows PowerShell ISE and curl up with a nice script. However, AV, your problem doesn’t need a scripted solution. You may want to write a quick script, but it is not totally necessary. As someone once said, I can solve that problem in one line.

Display formatted percentages

I can use the Windows PowerShell command Get-Volume (it is technically a function and not a cmdlet) to display a nice output that contains information about my drives. This command and its output are shown here:

Image of command output

One of the properties that appears to be missing is percentage of free space. I like to create a custom property for an object by using the Select-Object cmdlet. To do this, I use a hash table. I specify a label (a name for the property) and an expression (a script block that creates a value for that property). I can use the aliases l for label and e for expression. The hash table looks like this:

@{l='percent free';e={($_.sizeremaining/$_.size)}}

When I do this, I can use the special number format code, “P”, to create my percentage. Basically, it multiplies my value by 100 and returns the first two places after the decimal point. It also rounds up or down as necessary. The number format code becomes an override for the ToStringmethod. In the following example, I show how to call the ToStringmethod. Note that the “P” goes inside the parentheses that are required for all method calls.

PS C:\> (5/10).ToString("P")

50.00 %

To compute the percent free for each of my volumes, I pipe the Get-Volume function to the Select-Object cmdlet, and I specify the volume letter and my hash table as properties. Here is the command I use:

Get-Volume | Select driveletter, @{l='percentfree';e={($_.sizeremaining/$_.size).tostring("P")}}

The command and the output from the command are shown here:

Image of command output

AV, that is all there is to using Windows PowerShell to display a formatted percentage. Numbers  Week will continue tomorrow when I will talk about more cool Windows PowerShell stuff.

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

PowerTip: Express Percentage in PowerShell

$
0
0

Summary: Learn an easy method to express a percentage in Windows PowerShell.

Hey, Scripting Guy! Question How can I use Windows PowerShell to express a two-decimal place percentage? For example, I have multiple
           calculations in a Windows PowerShell script, and I am tired of always dividing two numbers, multiplying
           by a hundred, and trimming the results to two decimal places.

Hey, Scripting Guy! Answer Use the special “P” format specifier as an overload to the ToString method, for example:

PS C:\> (5/21).tostring("P")

23.81 %

Rounding Numbers—PowerShell Style

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to round numbers.

Hey, Scripting Guy! Question Hey, Scripting Guy! I think your series about formatting numbers has been pretty interesting. However, everything you have shown has a major problem—and that is that you convert numbers into strings. I would love to be able to display a Windows PowerShell number with a specific number of decimal places, but not have it be a string. Instead, I want it to be a number type. Can you do this? Or am I stuck with storing numbers and then converting them into strings before I display the results?

—GS

Hey, Scripting Guy! Answer Hello GS,

Microsoft Scripting Guy, Ed Wilson, is here. This morning, I decided to make a cup of Gunpowder green tea. I put a bit of lemon in it, and that is it. Gunpowder green tea seems to go well with kiwis—the flavors complement each other nicely. It is very refreshing. Normally, I drink a black tea in the morning, and then maybe have a cup of some sort of green tea in the afternoon. But I decided I wanted to start drinking more green tea.

I am sitting at my table, checking email sent to scripter@microsoft.com, and I ran across your email. GS, you are right. I have been focusing on methods that in the end convert the number to a string. So lets correct that right now.

Rounding a number with Windows PowerShell

To round a number in Windows PowerShell, all I need to do is to call the Roundstatic method from the System.Math class. A static method just means that it is directly available from the class, and that I do not need to create an instance of it first. Because the Math class is in the System .NET Framework namespace, I can drop the initial System when I call the static method. I can therefore call the method like this:

PS C:\> [math]::Round(2.25)

2

Notice that by default, the Roundmethod does not include any decimal places. The second parameter for the Roundmethod permits me to specify how many places I wanted to include. This technique is shown here:

PS C:\> [math]::Round(2.25, 1)

2.2

Notice that here the decimal, .25, rounded down to .2. This is because the number (2) is even. In the following example, the .35 rounds up because the number (3) is odd.

PS C:\> [math]::Round(2.35, 1)

2.4

A practical example of rounding

File sizes in Windows PowerShell appear as bytes. This can make the numbers a bit difficult to read. Luckily, Windows PowerShell includes a number of admin constants to make the conversion from bytes to kilobytes or megabytes easier to accomplish. The problem is nearly as bad when it comes to file sizes because the conversion usually produces a long string of decimal places. The answer is to use the Roundmethod and to select a number that is more easily digested.

In the following example, I use the Get-Item cmdlet to return information about a file that happens to reside on my hard drive. I then choose the Lengthproperty. That tells me the size of the file in bytes. I then convert the file size to megabytes and display the results. Following that, I use the Roundmethod choose the default, and choose two decimal places. This is shown in the following output:

PS C:\> Get-Item C:\fso\epcisar.txt

    Directory: C:\fso

Mode             LastWriteTime     Length        Name                                                          

----                 -------------              ------           ----                                                          

-a---         7/17/2014   3:33 PM    6531842 epcisar.txt                                                    

PS C:\> $a = Get-Item C:\fso\epcisar.txt

PS C:\> $a.Length / 1MB

6.22924995422363

PS C:\> [math]::round($a.Length / 1MB)

6

PS C:\> [math]::round($a.Length / 1MB, 2)

6.23

Now that I know what I want to do, I am going to display the name of the file and the size of the file in megabytes—but I am going to do it in a single line. To do this, I will use the Select-Object cmdlet and create a new property. I use a hash table to create the new property. For the label (l is my property alias), I use ‘size in MB’. The expression picks the length property from the pipeline.

In the following example, I first divide the length by 1 MB, and then I call the [math]::Round static method and tell it that I want two decimal places:

Get-Item C:\fso\epcisar.txt | select name, @{l='size in MB'; e={[math]::Round(($_.length /1MB),2)}}

The command and the output from the command are shown in the following image:

Image of command output

GS, that is all there is to using Windows PowerShell to round numbers. This also concludes Numbers Week. Join me tomorrow for PowerShell Spotlight when I will have guest post by Windows PowerShell MVP, Teresa Wilson (The Scripting Wife).

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 

PowerTip: Use PowerShell to Round to Specific Decimal Place

$
0
0

Summary: Use Windows PowerShell to round numbers to a specific decimal place.

Hey, Scripting Guy! Question How can I use Windows PowerShell to round a number to a specific number of decimal places, and
            continue to have a number instead of converting it to a string.

Hey, Scripting Guy! Answer Use the Roundstatic method from the System.Math class. By default, it does not display decimal places,
           but you can easily change that behavior. The following code illustrates this procedure:

PS C:\> $a = 111.2226

PS C:\> [math]::Round($a)

111

PS C:\> [math]::Round($a,2)

111.22

PS C:\> [math]::Round($a,3)

111.223

Viewing all 3333 articles
Browse latest View live




Latest Images