An Unrivaled Windows Hosting Experience
1-888-313-9421  | webteam@orcsweb.com
  1. The Power of “$()” in PowerShell

    Sometimes, and sometimes all the time, I like to cram as much as I can into a single line of PowerShell code. It’s like a challenge to me, making a command as long as absolutely possible. I haven’t quite broken the 1000 character mark, but I have made it to the 600+ character milestone. I’m sure professional programmers are cringing and mumbling something about spaghetti right now, but I think it’s fun. 

    The best tool, besides pipes, for doing this in PowerShell is $().  What is $() you may ask? Officially…I have no idea. Unofficially it means “return the value of whatever’s inside.”  It’s like a spontaneous function or script block.  It is a very handy tool that all PowerShell’ers should know. 

    Let me give you an example.  Say you want to write the output of, oh, I don’t know, the product key of your TechNet licenses using my handy keys.xml to keys.txt converter script (http://www.orcsweb.com/blog/james/using-powershell-to-convert-ugly-technet-msdn-keys-xml-to-pretty-easy-to-read-keys-txt/), but you want to add a conditional statement if there is a claim date attached to the key.  You have some options.

    Continue reading "The Power of “$()” in PowerShell" »

    Wednesday, February 24 2010 by | 0 comment(s)

  2. Using PowerShell to convert ugly TechNet/MSDN keys.xml to pretty, easy to read keys.txt

    I love long titles. I wish more stuff had long titles.

    Here’s the story. I have a TechNet account and I love pressing that “Get” link to generate as many keys as possible for every interesting product on the list.  I’ll never use them all, but that has never stopped me from pressing the “Get” link.

    The problem with being a “Get” link user is copying down all those keys.  I thought up a myriad of ways to copy them all to an easy to read and search text document but too many of them involved a lot of manual work.  Then I noticed, hidden on the top right of the Product Keys table, the “Export Key List to Xml” link, which became my new best friend.

    image

    Until I looked at the garbled, spaghetti coded XML nonsense that was generated by the “Export Key List to Xml” link.  Spaghetti code…yuck.  They didn’t even include meatballs.

    Time to bust out the PowerShell!

    Continue reading "Using PowerShell to convert ugly TechNet/MSDN keys.xml to pretty, easy to read keys.txt" »

    Tuesday, February 16 2010 by | 0 comment(s)

  3. The Apple iPad ... failure?

    Despite being a Wintel expert I really don't have any bad feeling against Apple.  I don't own any of their products, but that's a personal choice.  The iPhone plans are too outrageously priced.  Apple computers are too expensive and I can't game much on them.  As for the iPod ... I've always wanted one but could never justify the cost when I have 6GB free to store MP3s on my WinMo phone.

    But when the rumors started coming to a head about the now announced iPad I thought, "This could be really good!"  I honestly wanted it to be a great product because I've always wanted a good tablet.  Now that the official product launch has occurred it just seems...lacking.

    www.apple.com/ipad/

    First off, it doesn't have the sleek "Apple look.” The bezel is HUGE and that one tiny button seems out of place. Maybe pictures add the proverbial 10 pounds to the iPad, but it looks bigger than I thought it would be. The thing that bugs me the most about the look is the interface. It’s just a plain old, stripped down, iPhone/OS X UI. How boring.

     

    Somehow I expected something more.

     

    The most shocking part, being a hardware geek, is the processor. I guess we all kind of expected a custom chip seeing as Apple took the time and effort to buy out P.A. Semi, but that chip is a huge unknown.  It will be interesting to see how it compares to the likes of the Qualcomm Snapdragon, nvidia ION and Intel Atom platforms, all of which are known to be very powerful, energy conservative solutions.  While early reviews do show the iPad is blazing fast, we still need to hear from the dev's how the iPad handles heavy graphics at full resolution.

     

     

    Oh, and they kind of forgot to add multitasking to the iPad. Yes, you heard that right, you can’t listen to music and surf the web at the same time. Or work on say, I don’t know, a research paper and look up a reference online without closing Pages first. [EDIT: I am told that certain applications can multitask iPhone OS 3.2.  Still, I am convinced it is a showstopper if I can only multitask with certain Apple apps.]

     

    I call that a showstopper.

     

    Though I have to give Apple props on two things: price and content. For once an Apple product doesn’t give me sticker shock. Especially with that beautiful LED-backlit IPS LCD display. That should look really handsome. And we all know Apple will deliver on the content.

     

    Overall I am extremely disappointed, and not just because of all the pre-release hype. It’s just…boring, and that’s so not Apple.

     

    EDIT (more thoughts):

    I’ve been thinking about the iPad more – it’s hard not to with all the coverage it got today – and I think what disappoints me the most is the fact that it offers me nothing new but a bigger screen. It reminds me of those giant remote controls you find at the corner drug store. The iPad is nothing more than an iPhone with a bigger screen.

    While this may make other people ecstatic it is a letdown to me. I was hoping for something revolutionary and instead I got something that is barely evolutionary. In fact, I would argue that it is not even evolutionary.

    Apple didn’t release the first portable media player, they released a revolutionary media player. Apple OS X, at its core, is nothing more than a modified FreeBSD distribution, but Apple gave it a pretty, easy to use, arguably revolutionary shell and put it in a pretty package. The iPhone wasn’t the first smartphone, but it was smarter than all the others. The iPad, however, gives me little to nothing new.

    Maybe I’m wrong and someday I’ll beat off the throng at the local Apple store with a billy club and I’ll really like the iPad…but I doubt it. Maybe the iPad gen 2 or 3 will bring about the tablet revolution everyone is waiting for. Or maybe Microsoft or Google will beat them to it. Time will tell.

    Wednesday, January 27 2010 by | 0 comment(s)

  4. Importing the IIS PowerShell module in Windows Server 2008 R2

    I encountered an odd error playing with PowerShell 2.0 in Windows Server 2008 R2.  I couldn’t import the IIS module (WebAdministration) in PowerShell using the normal command.

     

    import-module -name WebAdministration

     

    The strange part is that it works on some servers, but not on others.  Very odd.  After tinkering with the help and command for a while I found an alternate command which appears to work on all servers.

     

    get-module -list webadministration | import-module

     

    Just thought I’d share.

     

    #James Kehr
    Get-Member $OW | ?{$_.title –eq System Administrator”`  –and $_.certification –match “MCITP 2008, MCSE 2000, MCDST, Network+, A+”}

    New-Variable –name company –value ‘ORCS Web, Inc.–description www.orcsweb.com | 1.888.313.9421’

    Tuesday, November 10 2009 by | 0 comment(s)

  5. How to run PowerShell 1 and 2, and Windows XP system tools, on Windows 7

    It’s no secret that I’m a huge PowerShell fan.  I’ve been very excited to start using all the handy new tools in PowerShell 2.0 RTM, but I still need PowerShell 1.0 for backwards compatibility testing.  While there are quite a few options out there to do this, I even found someone who figured out how to make PowerShell portable, I didn’t need anything fancy, complex or expensive.  Just a simple way to easily test my commands in PowerShell 2.0 and 1.0.

    With the announcement of Windows XP Mode a little dinging noise went off in the back of my head.  “Hey,” I thought, “why not just make PowerShell 1.0 into an XP Mode application?”  We have a winner!  Then, once XP Mode was released, I found out that no matter what you do Microsoft has decided to block executables in %windir% (C:\Windows) from XP Mode.  That’s okay, where there is a will there is a way, right?  In this case the answer is, yes.

    I won’t go over the PowerShell and XP Mode install parts in detail, but, in summary, you need to be running Windows 7 Ultimate, Enterprise or Professional, download and install Windows Virtual PC [RC] and XP Mode [RC] on Windows 7, and then .NET 2.0+ and PowerShell 1.0 for Windows XP 32-bit on the Windows XP Mode virtual machine for this XP Mode trickery to work.  In addition to the XP Mode and PowerShell components you need a handy little tool written by the master of all things Windows, Mark Russinovich, called Junction.

    Virtual PC [RC] and XP Mode [RC]:

    http://www.microsoft.com/windows/virtual-pc/download.aspx

    .NET 3.5 SP1 redistributable:

    http://www.microsoft.com/downloads/details.aspx?FamilyID=ab99342f-5d1a-413d-8319-81da479ab0d7&displaylang=en

    PowerShell 1.0:

    http://www.microsoft.com/.../powershell/download.mspx

    Junction:

    http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx

    Is that the sound of mental bells I hear ringing?  For those that don’t have the mental bells ringing, junction is the pre-Vista/2008 version of mklink.  Junction creates a symbolic NTFS link between two folders.  It’s like a shortcut, but Windows treats the “linked” directory like it was the real directory.  In other words, the trick to tricking XP Mode is to create a junction to the folders which contain the tools you want to use in XP Mode.

    To be on the safe side I created a link/junction from “C:\Program Files” to the PowerShell directory, C:\WINDOWS\system32\windowspowershell\v1.0.  Here is the command I used, from the command prompt, after extracting junction to C:\Windows\System32.

    junction "C:\Program Files\Shell of Power" "C:\WINDOWS\system32\windowspowershell\v1.0"

    And, no, you don’t have to use “Shell of Power” as the folder name.  It doesn’t matter what name you use, but whatever folder name you do choose it can’t exist before you run junction.exe.

    Now create a shortcut from “C:\Program Files\Shell of Power\powershell.exe” to “C:\Documents and Settings\All Users\Start Menu\Programs” and delete the silly “Shortcut to” part if you did the drag and drop method.  Log Off and hibernate the XP Mode VM (just close the window, default action is to hibernate). Pull up your “Windows XP Mode Applications” and you will see “powershell (Windows XP Mode)” in the list.  Click the link, wait for the XP Mode application to spin up, and voila!

    Let’s take this one step further, shall we? Say you also want command prompt from XP Mode.  I like to use it to do ping, telnet, and tracert tests from outside my VPN connection without actually turning off my VPN connection.  Simple.  Just make a shortcut from “C:\Windows\System32\cmd.exe” to the “Shell of Power” folder.  Then create a second shortcut from the cmd.exe shortcut in “Shell of Power” to the All Users program list.  And, once again, viola!  Rinse and repeat for any tool or program in %windir% you want to use as an XP Mode application.

    That just about covers it.  My not-so-secret way of tricking XP Mode into letting us admins and scripters use PowerShell 1.0 and the good old Windows XP system tools on your shiny new Windows 7 installation.  Oh, and thank you for XP Mode, Microsoft!

     

    #James Kehr
    Get-Member $OW | ?{$_.title -eq "System Administrator"`
    -and $_.certification -contains 'MCITP:SA 2008, MCSE 2000, MCDST, Network+, A+'}

    New-Variable -name company -value 'ORCS Web, Inc.' -description www.orcsweb.com | 1.888.313.9421’

    Friday, September 04 2009 by | 2 comment(s)

  6. PowerShell’ing on Windows Server: How to import certificates using PowerShell!

    Importing a certificate to a computer…you’d think the PowerShell method would be plastered all over the web, but oh no!  I had to figure most of this out all by my lonesome.  Okay, not *all* by my lonesome, but it felt that way.  There was one set of functions I found that worked as long as you use the x86 (aka 32-bit) version of PowerShell, but since I’m a 64-bit kind of guy I prefer my code to work in both the 32-bit and the 64-bit versions of PowerShell.

     

    For your reference, the 32-bit only method is here:

     

    http://blogs.msdn.com/daiken/archive/2007/01/12/windows-powershell-met-capicom.aspx

     

    This method does not work on Windows Server 2008 64-bit because the CAPICOM object does not have a 64-bit COM+ application.  Using this code in PowerShell 64-bit gives you lots and lots of nasty red on black text.  Which meant it was time to go back to the drawing board.

     

    In case you didn’t know, PowerShell has a drive for certificates.  Just type in “set-location cert:” (minus the “”) in PowerShell and you are now in your certificate store.  I blogged about this a bit in my MD5 certificate blog post a while back, so I won’t go into that much.  This was a good start, because it let me know what .NET class PowerShell uses for its certificates by looking at the “get-member” properties of a certificate.  Why is this important, you may be wondering?  Because PowerShell is just a scripting language built on top of the .NET framework.  Which means if you know what .NET class to manipulate you can do far more in PowerShell than just reading the cmdlet help files.   In this case I used the following command to get the .NET class.

    1. gci cert:\localmachine\root | gm   
     

    ...which translates to this using the long way...

     
    1. get-childitem cert:\LocalMachine\root | get-member   
     

    I used cert:\LocalMachine\root because I know there are always certificated there, so I will get the right class I need use.  And sure enough, at the top of the get-member output you get the .NET class of “System.Security.Cryptography.X509Certificates.X509Certificate2.”  With the .NET class in hand I did a quick MSDN search and started my research.

     

    http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.aspx

     

    I’ll spare you readers the boring trial and error stuff and skip straight to the results.  There is a way to import certificates, both X.509 (.cer) and .PFX and all other supported types.  All you need to do it use one of these two handy functions.

     
    1. function Import-PfxCertificate {    
    2.   
    3.    param([String]$certPath,[String]$certRootStore = “CurrentUser”,[String]$certStore = “My”,$pfxPass = $null)    
    4.    $pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2    
    5.   
    6.    if ($pfxPass -eq $null) {$pfxPass = read-host "Enter the pfx password" -assecurestring}    
    7.   
    8.    $pfx.import($certPath,$pfxPass,"Exportable,PersistKeySet")    
    9.   
    10.    $store = new-object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore)    
    11.    $store.open("MaxAllowed")    
    12.    $store.add($pfx)    
    13.    $store.close()    
    14. }   
     

    Import-PfxCertificate should be used when importing a certificate that requires a password.  I didn’t go all crazy on the password security, but you can add that outside the function in your code pretty easily.  If I add some later on I’ll do some updates to the blog post.  To use the function you pass one to four parameters.

     

    $certPath = the location of the certificate file.  Required.

    $certRootStore = either “LocalMachine” or “CurrentUser”.  Default is CurrentUser, which is your personal user store.  LocalMachine is well … the computer’s certificate store.  IIS site certificates go here.

    $certStore = any number of items.  If you go to the cert: drive, then change the directory to either LocalMachine or CurrentUser and run “dir” you will see a list of all the cert stores.  My = Personal, root = Trusted Root Certificate Authorities, etc.  These “directory names”, or certificate stores, is what you enter for this variable.  Again, didn’t go crazy with the error correction in this function, but as long as you pass the right store all is well.

    $pfxPass = the password of the pfx, or other passwords protected certificate files.  If none is specified you get a prompt, which stores the pass as a securestring.  You *can* pass a plain text password, but I wouldn’t recommend it unless you know the script is secure.  You can also pass a secure string to the function, using whatever securestring storage method you prefer…or can find.

     

    Example:

     

    Import-PfxCertificate "C:\temp\testCert.pfx" "LocalMachine" "My"

     

    The second function is for certificates that do not require a password.

     
    1. function Import-509Certificate {    
    2.   
    3.    param([String]$certPath,[String]$certRootStore,[String]$certStore)    
    4.   
    5.    $pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2    
    6.    $pfx.import($certPath)    
    7.   
    8.    $store = new-object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore)   
    9.    $store.open("MaxAllowed")    
    10.    $store.add($pfx)    
    11.    $store.close()    
    12. }   
     

    The variables are the same as before, the function merely lacks password support.  Usage is identical to Import-PfxCertificate, just don’t pass it a password string or securestring.  I suppose you could, the function will just ignore it.

     

    That’s all there is to it.  If you’re still with me you may be wondering why I think this is so important.  Even working for a hosting company most certificates I handle don’t need this, even though you can use this to generate and complete certificate requests.  The reason I looked for this is because of code signing.  I can script the importation of the three required certificates for PowerShell code signing to a sever in seconds now.  Whether it was worth the effort is in the eye of the beholder, but I think it was.

    #James KehrGet-Member $OW | ?{$_.title –eq System Administrator”` –and $_.certification –match “MCITP 2008, MCSE 2000, MCDST, Network+, A+”}

    New-Variable –name company –value ‘ORCS Web, Inc.–description www.orcsweb.com | 1.888.313.9421’ 

    Thursday, August 06 2009 by | 0 comment(s)
    Tagged as: , ,

  7. Breaking the blog drought!

    What a crazy summer.  No OW blogs for over 3 months.  Time to break the drought.  I was studying today for one of those certification test things and ran across an interesting problem.

    Situation: I have an offline Enterprise Root Certificate Authority (Ent CA) with my Domain Controllers as subordinates in my test environment.  Overkill I know.  I have web enrollment setup, but in order to do some of the certificate options to work—and what you should use for everything on your CertSrv site—you need https working.

     

    Easy enough…pop open the MMC and create a web server certificate request.  Easy cheesy, right?  Nope.  The certificate was created easily enough but when I tried to add the certificate to the site binding in IIS7 I got the follow evil looking and very generic error message.

     There was an error while performing this operation.  Details:    A specified logon session does not exist. It may already have been terminated. (Exception from HRESULT: 0x80070520)

    After some searching through the big series of tubes I found this wonderful article:

     

    http://blog.freakcode.com/2009/02/iis7-certificate-binding-issue.html

     

    Now we’re getting somewhere.  But here was my dilemma…I requested and installed the web server certificate on the actual server hosting the site and selected the option, when generating the certificate, to make the private key exportable.  So everything is already there, right?  Apparently not.

     

    The solution: I exported the certificate, including the private key, to a pfx file, then imported that key back in to IIS7 (IIS Manager -> <Server> -> Server Certificates -> Import).  And then guess what happened?  No more error when adding the https binding and the site came up secure.  There was no duplication in the Certificates snap-in, and, as far as I looked, nothing really changed on the server…but that “make private key exportable” flag buried somewhere in the bowels on Windows that I couldn't find.  What a weird, weird bug.

     #James Kehr

    Get-Member $OW | ?{$_.title –eq System Administrator”`

     –and $_.certification –match “MCITP:SA 2008, MCSE 2000, MCDST, Network+, A+”}

     

      New-Variable –name company –value ‘ORCS Web, Inc.–description www.orcsweb.com | 1.888.313.9421’
     

    Friday, July 31 2009 by | 0 comment(s)
    Tagged as:

  8. Fun with PowerShell: Sorting multidimensional arrays and ArrayLists

    Sometimes the best way to learn something important is to walk the long, rocky road. And sometimes you have to use poor analogies to open a blog post because nothing better is clicking at the moment. But most of the time you wish someone else had walked the long, rocky road for you so you could pilfer the code from their blog and avoid thinking all together. My most recent rocky road, and not the ice cream kind, was sorting a multidimensional array. Or more accurately an ArrayList.

    Obviously you can use sort-object to sort an array, but what if the object you want to sort by is not the first property of the array within the ArrayList? Example: say you have four fields in an array. You store 7000 of these arrays in an ArrayList. You want to sort from the last field instead of the first. List objects such as a hashtables don’t like storing and sorting more than two fields. And since you can’t name the columns in an array or ArrayList (that I have found), sorting that multidimensional nightmare appears to be exactly that. A nightmare.

    It turns out the solution is pretty easy. This will even work for a regular multidimensional array, and not just an ArrayList. Let’s say your ArrayList is named $x. $x has 7000 arrays and four fields per array. If you want to sort by the fourth field, a.k.a. field [3] in array talk, all you need to do is this:

    $x = $x | sort-object @{Expression={$_[3]}; Ascending=$false}

    “@{Expression={$_}; Ascending=$false}”, according to the sort-object help file, gives you hashtable like control of your sort. Without the hassle of working with a large hashtable. The expression value lets you do just about anything with that pipeline variable ($_). You can even do math in that expression field. Just look at example 5 in the detailed help output (help sort -detailed). The true/false in the Ascending value just determines whether the sort does big-to-small or small-to-big.

    It turns out that sorting multidimensional arrays is as easy as eating rocky road ice cream. So stop walking, pilfer my code, and get on with your multidimensional sorting already.

    Monday, April 27 2009 by | 0 comment(s)
    Tagged as:

  9. Fun PowerShell Command: Find all folders containing a file type

    Me, write a short blog?  Never! I wanted to mass import all the drivers from the UBCD4win software to a custom WIM file, but the network drivers are scattered everywhere in different subfolders.  The solution?

    $drv = get-childitem D:\UBCD4Win\drivers -recurse -filter "*.inf" | %{$_.DirectoryName} | Get-Unique

    The first part of the command gets all the locations where an INF file lives.  Then you use a for-eachobject (%) to select the directory name of where those files are.  Get-unique automatically pulls our duplicate directories in case a directory has more than one INF file.

    In the end I do the entire import in two lines of blissfully easy PowerShell code.

    1. $drv = get-childitem D:\UBCD4Win\drivers -recurse -filter "*.inf" | %{$_.DirectoryName} | Get-Unique
    2. foreach ($d in $drv){invoke-expression "D:`\WAIK`\Tools`\PETools`\peimg`.exe `/inf=$d\*`.inf D:`\PE`\winpe_x86`\mount`\Windows"}

    Please note that I have an uncommon Windows Automated Installation Kit (WAIK) location, so please adjust accordingly and add quotes (`" inside inside the invoke-express) if there is a space in the path.

    Saturday, March 14 2009 by | 0 comment(s)
    Tagged as:

  10. Fun with PowerShell: Testing whether an IPv4 address has a valid structure.

    More fun with PowerShell today! Today's script is a function, testIP, that accepts a string input and verifies whether it is a valid IPv4 address. Someday I will write one for IPv6, but I need to figure out how exactly those 128-bits worth of rules work. *shudders*


    1. function testIP {   
    2.     param ([string]$tempIP)   
    3.   
    4.     # used for validation   
    5.     $ValidIp = $True  
    6.   
    7.     # test 1: check for proper octet length.   
    8.     [array]$crushIt = $tempIP.split('.')   
    9.     if ($crushIt.length -ne 4) {   
    10.         "The IP $tempIP is invalid. Invalid character or not enough octets."  
    11.         $ValidIp = $False  
    12.         break   
    13.     }   
    14.   
    15.   
    16.     # test 2: check for invalid characters   
    17.     if ($ValidIP) {   
    18.         # this string array stored the chars 1-9 for later testing.   
    19.         $num = "0","1","2","3","4","5","6","7","8","9"  
    20.         foreach ($oct in $crushIT) {   
    21.             $mashIt = $oct.ToCharArray()   
    22.             foreach ($m in $mashIt) {   
    23.                 if ($num -notcontains $m -and $ValidIp) {   
    24.                     "The IP $tempIP contains invalid characters."  
    25.                     $ValidIp = $False  
    26.                     break   
    27.                 }   
    28.             }   
    29.                
    30.             # test for out of range octets   
    31.             if ($ValidIP) {   
    32.                 [int32]$n = $oct  
    33.                 if ($n -lt 0 -or $n -gt 254) {   
    34.                     "$oct in $tempIP is out of range."  
    35.                     $ValidIp = $False  
    36.                     break   
    37.                 }   
    38.             }   
    39.         }   
    40.     }   
    41.     # output results...change to 'return $ValidIp' to pass result to another function.   
    42.     write-output $ValidIp  
    43. }  

    Let’s break it down, shall we? And, as usual, there may be better or perhaps built-in ways to do this. I’m not an expert programmer so doing stuff like this is a good learning experience for me, and may be helpful to someone down the line.

    First let me define what $ValidIp is and what it does. This a Boolean variable used to validate and store the results of the tests. If at any point during the function a test fails, all of the following tests will simply not run. With a couple of foreach exceptions. In the end, $ValidIp, is used to return or output the result of the tests.

    Test 1 is very simple. I use the split method of System.String to divide the string into parts, with a period (.) as the separator. The values are stored in an array named $crushIt. The if-statement then checks the length of the array (i.e. how many strings are in there). If that number is not 4, the number of octets in an IPv4 address, then the test fails and $ValidIp is changed to $False.

    Test 2 is a wee bit more complex, as it checks to make sure each character entered is a number. First it runs a check to see if test 1 failed. If it hasn’t, then the script moves along. An array is built with the character values of the numbers 0-9, followed by a foreach loop which goes through every octect. I did it this way to make test 3 go smoothly.

    $mashIt is created by converting the octet to a character array, another nifty method in System.String, and then sent through yet another foreach loop. Inside this loop each character is compared to the array storing the string values of the numbers 0-9. If any character doesn’t fit the mold the fashion show ends in tears and sorrow, $ValidIp is set to false and test 3 is summarily ignored (where the tears and sorrow come into play).

    Test 3 is the easiest rule of them all. After checking whether $ValidIp is true or false, it converts the string value of the octet to an integer (if true that is). Remember, we already made sure only numbers are involved in test 2 so there will be no conversion errors here. I looked for an hour trying to figure out the convert command, only to discover you just have to save the string to an integer variable, by using [int] or [int32] before the variable name, and PowerShell does the conversion automagically. Well, technically .NET does it, but let’s not get too picky.

    Once the conversion is done a very simple if-statement is run to see whether the value of the integer is less than zero or greater than 254. If that statement is false then $ValidIp is set to false. And now we’re done.

    I know there are a lot of other tests that could be run, especially if subnet mask was added in the picture, but that’s not the purpose of this function. This is a very simple function to make sure a letter or extra number was not fat fingered into an IP range. The script I am building this for is adds IPs to a server, this function just makes sure the script doesn’t try to add IPs 192.168.1.2 through 192.168.1.2000 to the server and cause all sorts of fun and exciting errors.

    Friday, March 06 2009 by | 0 comment(s)
    Tagged as: ,