| |

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).

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.

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.

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...
$dir = [System.IO.DirectoryInfo]$profile
New-Item -Type Directory -Path $dir.Parent.FullName
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.

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.

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.
|
|
|
|