Articles from PowerShell

VS Team Edition for IT Admins

By Michael Flanakin @ 5:43 PM :: 62 Views :: 0 Comments :: .NET, Tools/Utilities, PowerShell :: Digg it!

PowerShell

Yes, I said "admins," but, unfortunately, this isn't an announcement. I'm simply thinking of a version of Visual Studio built for, well, admins. Specifically, I'm envisioning an environment to build and debug PowerShell scripts and cmdlets. Of course, this is only a hop, skip, and a jump away from PowerShell as an official .NET language. Imagine that, PoSh.NET... or, would someone force it to be P#? Either way, I like the idea. As an official language, that also opens it up to compiled scripts, which would be great for those servers without PowerShell installed. Of course, it's just a matter of time before PowerShell is default and the legacy DOS shell is eventually phased out. As a matter of fact, that's the plan for Windows 7 and Server 2008 R2. I'm not sure about Server Core, tho, since there's still the dependency on .NET.


PowerShell Tip: Creating GUIDs and Code Generation

By Michael Flanakin @ 2:30 PM :: 62 Views :: 0 Comments :: Development, PowerShell :: Digg it!

PowerShell

I should start off by saying this isn't really about hard-core code generation. It's more about simplifying some of the more repetitive tasks we tend to do during development. In this instance, I needed to get 7 GUIDs to use in some test code. Sure, I could've use the Create GUID tool in Visual Studio, but what fun is that? Besides, I hate manual tasks and this tool would have forced me down a ~24 step process. No thanks. I'll stick to the 3 steps PowerShell can give me.

First thing's first, how do we create a GUID in PowerShell? I'm going to fall back to .NET for this one.

[Guid]::NewGuid()

If you run this, you'll get a blank line. What's up with that!? Admittedly, I'm not 100% sure why this is happening, but I have a pretty good guess. GUIDs are surrounded by curly-braces ({}), which are interpreted by PowerShell to be a script block. Putting 2 and 2 together, I'm assuming PowerShell thinks this is a script to run. Easy fix.

[Guid]::NewGuid().ToString()

That's it. The only other thing I had to do was add in my other formatting to create the GUID in code and slap that in a loop.

foreach ($i in 1..7) { 'new Guid("{0}")' -f [Guid]::NewGuid() }

You'll notice I opted to use the PowerShell shortcut syntax for string formatting. If you missed it, I talked about it as well as the static-method-calling syntax last week.

This tiny exercise reminded me of a pretty advanced Excel spreadsheet I created years ago because I was sick of typing the same bit of code over and over again. Since then, other tools, like GhostDoc and Resharper, have augmented my developer experience, enabling a much higher level of productivity than I had back then. Nonetheless, there is still room for improvement. This makes me wonder how much PowerShell could do for me with respect to code generation.


Converting To/From Hex with PowerShell

By Michael Flanakin @ 12:16 PM :: 115 Views :: 1 Comments :: PowerShell :: Digg it!

PowerShell

If you're doing any web or WPF/Silverlight work, you're probably used to dealing with the RGB (red-green-blue) hex color format. I can't tell you how many times over the years I've opened the calculator to convert to/from hex values to either get a specific value or find out what percentage is being used. I'm sure graphic artists deal with this a lot, because I know I find it relatively annoying when I've used apps in the past that only accepted 3 decimal numbers instead of the RGB hex format. That's changed over the years, however. I will say that this is perhaps worsened by WPF and Silverlight, which have incorporated opacity using the RGBA (red-green-blue-alpha) spec, which is arguably a misnomer, since the alpha channel (aka opacity or transparency) is specified first. All that aside, I found myself wanting to find out what a certain opacity was when working on a WPF app, so instead of opening the calculator, I referred to my handy-dandy PowerShell, which is always open on my desktop.

Being a .NET developer, I knew the Convert class has the ability to convert to/from hex, so I started out with this simple one-liner to convert a hex number to its decimal equivalent.

[Convert]::ToInt32("a6", 16)

To go the other way, you simply switch out the method name and first parameter you pass in.

[Convert]::ToString(166, 16)

The first parameter is the value to convert and the second value is the base (i.e. 2 for binary, 8 for octal, 10 for decimal, and 16 for hexadecimal).From a PowerShell perspective, there are a two more things to note here, since we're accessing a static method. First, you have to surround the class name with brackets ([]); and, second, you have to separate the class and method names with two semicolons (::). Also note that, for some classes, you may need to use the fully-qualified class name, which includes the namespace.

After doing this, I remembered the numeric format shortcuts available in C#. For hexadecimal numbers, you can reference a value without treating it as a string by prefixing it with 0x. So, to convert my hex number to decimal, I was able to drastically shorten the code (can you even call this "code?").

0xa6

To go the other way, we'll tap into standard string formatting logic. Knowing .NET, our first guess might be to just convert it to PowerShell, like we did before.

[String]::Format("{0:x}", 166)

Here, we're specifying a string format that renders the first parameter as hex as well as the number we're converting. This isn't saving us anything, tho. Luckily, we have a bit of PowerShell magic to shorten this for us.

"{0:x}" -f 166

I thought this was confusing the first time I saw it, but comparing it to the String.Format() method brings it home for me. Hopefully, for you, too.

I'm now converting the hex number, but that isn't telling me what the opacity is. This probably isn't even worth mentioning, because I know you're smart enough to figure this out for yourself, but we simply need to use a bit of division to get that percentage.

0xa6 / 0xff

I now know that A6 is 65%.

If you find yourself using the calculator every so often while working on something, consider keeping PowerShell in the background and just bringing it up instead. It's a great way to get used to the tool and even boost your productivity, as you get used to things you can do faster in PowerShell than via the mouse.


PowerShell Tip: Handling Errors

By Michael Flanakin @ 8:06 AM :: 267 Views :: 0 Comments :: En Español, PowerShell :: Digg it!

PowerShell

As you get into writing functions, you'll undoubtedly hit a scenario where a command may return an error. To buld the most robust scripts, you simply need to keep one standard argument in mind: -ErrorAction.

-ErrorAction tells PowerShell what to do if the command returns an error (obviously). There are four options: SilentlyContinue, Stop, Continue, and Inquire. As you most likely deduced, these continue without displaying the error, stop further processing, continue with the error displayed, and ask the user whether to continue, respectively. The default is Continue, but my favorite is SilentlyContinue because I would rather handle errors myself. If you're really lazy efficient, you can even use -EA 0. Since -ErrorAction is an enumeration, you can use this to specify any value, 0-3 (based on the previously mentioned order).

Sugrencia PowerShell: Control de Errores

En Español

Al crear funciones, usted encontrará un panorama cuando usted conseguirá un error. Para construir las escrituras robustas, recuerde un argumento: -ErrorAction.

-ErrorAction indica qué hacer si el comando devuelve un error (obviamente). Tiene cuatro opciones: SilentlyContinue, Stop, Continue, y Inquire. Como deduce lo más probable es que, estos continuar sin mostrar el error, detener el procesamiento, continuar con el error muestra, y preguntar al usuario si desea continuar, respectivamente. El estándar es Continue, pero mi favorito es SilentlyContinue porque tengo gusto de manejar mis errores. Si esta perezoso eficiente, puede utilizar -EA 0. Desde entonces -ErrorAction es un enumeración, puede utilizar este método para especificar cualquier valor, 0-3 (de acuerdo con la orden previamente mencionada).


PowerShell and Project Euler

By Michael Flanakin @ 4:40 PM :: 191 Views :: 0 Comments :: Development, PowerShell :: Digg it!

PowerShell

So, my "daily" PowerShell tips haven't gone like I imagined. I have a list of topics to post. I just haven't had the time to type them all out. Either way, I'm still stuck on PowerShell. As a matter of fact, I just heard about a geeky website, Project Euler, which is dedicated to math and programming problems. When I first heard about it, I was thinking it sounded like a great way to hone your performance tuning skills. After trying the first problem, I'm not sure that's the case, but the problem was very simple. As a matter of fact, I solved it with a one-liner. If you're actually interested in solving it yourself, you may want to ignore this post. Then again, it's pretty simple.

I'll probably check out more of these. I'm not sure if I'll post the andwers or not, tho. Then again, as you progress, they get more and more complicated. If you're a sucker for pain, you can jump to one of the more complicated problems. I don't know how hard they'll be, but I'm sure it'll take longer than the 2 minutes this one took me.

Problem 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

My Solution

All I did was loop tthrough all numbers and added the number to a running tally if it was divisible by 3 or 5. Gee, that's pretty much what the problem statement was. Like I said, this one is pretty simple.

$sum = 0; ForEach-Object ($i in 3 .. 10) { if ((($i % 3) -eq 0) -or (($i % 5) -eq 0)) { $sum += $i } }; Write-Output $sum

What really surprised me was that this script ran from 3 to 1000 in 0.0156 seconds. I don't know what typical numbers are, but I was expecting it to take longer. For learning purposes, the aliases for ForEach-Object and Write-Output are foreach and echo.


Revisiting UpdateVersion

By Michael Flanakin @ 7:51 AM :: 181 Views :: 0 Comments :: .NET, Development, Configuration Mgmt, Tools/Utilities, PowerShell :: Digg it!

UpdateVersion

It's amazing what sticks and what doesn't. Back in Aug 2004, I caught wind of UpdateVersion, a tool Matt Griffith wrote to update version numbers in AssemblyInfo files. The tool is pretty simplistic, but provides an absolute benefit. Every couple of months, I get asked for a copy of the changes I made... despite the fact that they've been available online for years. Nonetheless, it's about time I created a project on CodePlex for the utility. At this point, I don't really expect to make any changes to it, but I will if someone sees value in it. If I were to make any changes, I'd probably go ahead and convert it to .NET 3.5 and possibly even add a PowerShell cmdlet.


PowerShell Tip: Getting Started

By Michael Flanakin @ 6:28 AM :: 148 Views :: 0 Comments :: Tools/Utilities, PowerShell :: Digg it!

Windows PowerShell

I just wanted to share a small script that creates a new profile and registers the ps1 file extension. For those that don't know, ps1 is the default extension for PowerShell scripts. Of course, there's a difference between ps1 and bat or cmd. If you double-click a ps1 file in Windows Explorer, it'll open in Notepad. What's up with that!? Apparently, this was done for security reasons. The idea is that, since you can't simply double-click on the file to execute it, hopefully you'll actually look at it to make sure it's not going to kill your system. PowerShell is much more dangerous than traditional batch files are, so this is probably a good thing. With that in mind, PowerShell, by default, doesn't allow you to even execute these ps1 files. To do that, you have to set the execution policy. Anyway, here's the script...

# create profile script
$dir = [System.IO.DirectoryInfo]$profile
New-Item -Type Directory -Path $dir.Parent.FullName

# enable the ability to execute ps1 files
Set-ExecutionPolicy RemoteSigned

I found this online a while ago, but I don't remember where. The only other thing I want to mention, since I imagine some people might freak out by it is the New-Item cmdlet, is that there's a function that simplifies this call and gives us a familiar DOS experience: md. I always thought md was an alias, but never bothered to consider why/how the New-Item cmdlet was determining that you wanted a directory.


Best Command Line Environment

By Michael Flanakin @ 7:45 AM :: 199 Views :: 0 Comments :: .NET, Tools/Utilities, En Español, PowerShell :: Digg it!

Windows PowerShell

Is PowerShell the best command line environment out there? Looking at a comparison of computer shells, I'm thinking it is. I'm sure others would disagree, but the facts are there. There are about 3-5 runners up, but the one feature which puts PowerShell over the top, in my mind, is the use of .NET objects in the pipeline.

La Mejor Línea de Comando

En Español

¿Es PowerShell la mejor línea de comando? Después de mirar una comparación sobre cáscaras de las computadoras, pienso que es. La otra gente discrepará probablemente, pero los hechos están allí. Hay 3 a 5 cáscaras segundarias, pero la característica que PowerShell el mejor es el uso de objetos de .NET en la tubería.


2-Minute Intro to PowerShell

By Michael Flanakin @ 7:22 AM :: 143 Views :: 0 Comments :: Tools/Utilities, PowerShell :: Digg it!

Windows PowerShell

As I've been working with PowerShell more and more, I keep picking up small tidbits I'd like to share. Arguably, I'd have learned a lot of them much sooner if would've picked up a book or something, but I look at this as a language I'll just pick up over time and don't really want to dedicate the time to a book... at least not at this point. So, I've decided to start throwing out a few PowerShell tips. I'd like to do a tip of the day, but I don't know if I'll come up with that many. We'll see. For this first post, I guess I should give a very brief overview of what PowerShell is and a few of the basic concepts behind it.

PowerShell is Microsoft's command line replacement. If you've ever done any time on the command line -- yes, I phrase it that way on purpose -- then you know it can be a pain. Not only is it painful, like any "good" prison, it's very limiting... another prison-like attribute. Another aspect I believe PowerShell is trying to attack is Windows shell scripting with VBScript or a similar language. I've used VBScript a few times for UI automation and I have to say, it's not much better than the traditional command line. The bottom line is that PowerShell is a powerful scripting environment for Windows.

So here are the basics: cmdlets, aliases, functions, and the pipeline. Cmdlets are commands. Go figure. If you want to do something, it all comes down to the commands you have available to you. To get a list of commands, type Get-Command. From there, you can figure out what's possible. If you have any questions about how to use them, type Get-Help [cmdlet]. Aliases are exactly what they sound like, aliases for cmdlets. This is one of the great things about PowerShell because it allows people to adopt PowerShell much easier. For instance, dir and ls are both aliases for the Get-ChildItem cmdlet, which is great for DOS and Linux/Unix users, respectively. Notably, the parameters are still PowerShell parameters and not the same as what's in DOS or the *nix systems. Functions are like a gateway drug to true PowerShell productivity. Think of functions as small scripts -- once again, go figure. Lastly, the pipeline is a concept that one command, whether that be a cmdlet or function, can send its output to another command via the pipeline. This is done by using the pipe ("|") character. For instance, to sort a list of folder contents by size, you pipe the contents to one that will sort the items it receives: Get-ChildItem | Sort-Object Length. Pretty simple. The key here, and true power of PowerShell, is the fact that PowerShell acts on .NET objects. This is a first. All other command line environments are pure text and piping content from one command to another is simply sending text down the pipe. Being built on .NET, PowerShell gives us an unprecedented amount of control and flexibility in our scripting.

To give you an idea of Microsoft's dedication to PowerShell, there's an internal mandate that all system administration tools must be built on PowerShell by 2009. The latest Exchange, Active Directory, and System Center releases have already made the switch and SQL Server 2008 is well its way, too.

I'll leave the intro here. In coming posts, I'll dig a little deeper into new features that I find. I'd like this to ultimately turn out to be a developers' guide to PowerShell, but that's more lofty a goal than I'm ready to sign up for. We'll see how things progress.






Archives Archives

Categories Categories

Related Links Related Links