Archive

Archive for February, 2012

Powershell: Create Custom MAC\IP Table

February 20, 2012 Leave a comment

Local MAC Discovery

There are times where I need to determine the MAC address of not only my PC but also the other PC’s on the local network segment.  There are a few different ways to determine the local PC”s MAC address(s) using Powershell:

    getmac           
    (ipconfig /all) -match " ([0-9A-Z]{2}[-]){5}[0-9A-Z]{2}$"           
    (ipconfig /all) | Select-String " ([0-9A-Z]{2}[-]){5}[0-9A-Z]{2}$"           
    GWMI Win32_NetworkAdapter -f "MacAddress like '%:%'" |
          Select -expand MacAddress

Although they all display the MAC address information for all network adapters the output is done so differently for each command, except for -Match and Select-String as they produce the same output.  Read more…

Advertisements
Categories: Powershell Tags:

Powershell: Retrieving AD FSMO Role Holders

February 18, 2012 2 comments

I was recently asked to create a script to display the current FSMO Role holders in an Active Directory domain.  There are 5 FSMO roles and the first domain controller in the forest root domain holds them all by default.  Of the 5 roles, 2 are per forest and 3 per domain.  These roles can be transfered or seized during the lifetime of the AD Domain and it’s important to know what DC’s hold which roles, especially when doing maintenance.

Powershell isn’t the only way to retrieve the role holders and both Netdom and NTDSUtil provide the same info, with Netdom being the easier of the two commands to use.  Here is an example of using Netdom:

Read more…

Categories: Powershell Tags:

Powershell: Adding Directories to Path Statement

February 10, 2012 1 comment

Adding directories to the Path statement is a rarity for most techs these days but on occasion, such as configuring Sharpeoint 2010 to use an Adobe IFilter or my own desire to make it easier to run powershell scripts, updating the Path statement must be done.  Either way it’s just the reason I was looking for to write another powershell script. 🙂

I always approach writing powershell code with the intention of making it resuable, mostly in the form of a function.  The function I’ve created this time is called  AddTo-SystemPath

I begin by defining parameters.  Since there may be a need to add several directories to the path statement I’ve cast the $PathToAdd variable  as an array.

  Param(
     [array]$PathToAdd
 )

A Foreach loop will then be run against the $PathToAdd variable .  It also seemed like best practice  to make sure that the Path statement didn’t already contain the directory(s) in the $PathToAdd variable so comparison is used inside an If\Else statement. The  $VerifiedPathsToAdd variable is then populated with the directories to add.

 Foreach($Path in $PathToAdd) {            

    #Verify if the Path statement already contains the folder
    if($env:Path -like "*$Path*") {
       Write-Host "$Path already exists in Path statement" }
    else { $VerifiedPathsToAdd += ";$Path"
       Write-Host "`$VerifiedPathsToAdd updated to contain: $Path"}

I now want to make sure that $VerifiedPathsToAdd contains something, and if so update the Path statement  using the [Environment] class.

The code below containing  [Environment]::SetEnvironmentVariable() is too long to display as one line so I’ve divided it into the class and method overloads.

[Environment]::SetEnvironmentVariable
("Path",$env:Path + $VerifiedPathsToAdd,"Process")

It’s possible to update the Path statement using just the $Env:Path variable, however it’s not persistent and any added values will be lost when the PS session closes. An example of using this non-persistent method is:

$ENV:Path = $ENV:Path + ";$Path"

The complete If statement containing the persistent method is:

  #Verify that there is something in $VerifiedPathsToAdd to update the Path statement
  if($VerifiedPathsToAdd -ne $null) {
    Write-Host "`$VerifiedPathsToAdd contains: $verifiedPathsToAdd"
    Write-Host "Adding $Path to Path statement now..."
  [Environment]::SetEnvironmentVariable("Path",$env:Path + $VerifiedPathsToAdd,"Process")
   }#End If

The complete Function is below:

Function AddTo-SystemPath {            

 Param(
  [array]$PathToAdd
  )
 $VerifiedPathsToAdd = $Null
 Foreach($Path in $PathToAdd) {            

  if($env:Path -like "*$Path*") {
   Write-Host "Currnet item in path is: $Path"
   Write-Host "$Path already exists in Path statement" }
   else { $VerifiedPathsToAdd += ";$Path"
    Write-Host "`$VerifiedPathsToAdd updated to contain: $Path"}            

  if($VerifiedPathsToAdd -ne $null) {
   Write-Host "`$VerifiedPathsToAdd contains: $verifiedPathsToAdd"
   Write-Host "Adding $Path to Path statement now..."
   [Environment]::SetEnvironmentVariable("Path",$env:Path + $VerifiedPathsToAdd,"Process")            

   }
  }
 }
Categories: Powershell Tags:

Powershell: Importing Hyper-V VM’s

February 2, 2012 5 comments

In my previous post Creating Hyper-V Symolic Links using Powershell I created a small but useful function called Create-SymbolicLinks which was used to execute one or more .bat files that created symbolic links to base or middle tier VHD’s as part of the initial classroom VM setup.  Once this was completed the next step was to import the VM’s and of course what better way to automate this then to use Powershell.

The first task at hand is to download and import the Hyper-V module from Codeplex.  There are 2 versions of this module available to download, with the latest version being R2 SP1.  Once downloaded I then place it into the directory where I will be running the script\function so that it can be copied to the appropriate Modules directory on the server.   Both the module path and name are defined in the Param statement as follows, along with the path to the VM’s.

 Param (
  $ModulePath = ($env:psmodulePath -split ";")[1],
  $ModuleName = "HyperV",
  $path = "C:\Program Files\Microsoft Learning\6419\Drives\"
  )

The code to copy the HyperV module and import it is:

 #Copy the HyperV module if it doesn't already exist
 if(!((Dir $ModulePath) -match $ModuleName)) {
  Copy-Item .\$ModuleName $ModulePath -Recurse
  }
 #Import the HyperV module if not already imported
 if(!(Get-Module | ?{$_.Name -like $ModuleName})) {
   Import-Module $ModuleName
  }

Now the real work begins.  I need to determine what VM’s have already imported into Hyper-V to make sure we don’t 1) do more work then is necessary and 2) don’t try overwriting any previously imported VMs.  Doing this involves using Get-VM and extracting just he name property ( or in this case the ElementName property) and putting those results into an array called $ActiveVMs.
In order to get a list of the VM’s I need to import I run a Get-ChildItem $Path and extract just the Name property and put the results into an array called $VMsToImport.

 #Create array to contain active VM's
 $ActiveVMs = Get-VM | Foreach{$_.ElementName}
 #Create array to contain VM's to be imported
 $VMsToImport = (Get-ChildItem $path) | Foreach{ $_.Name }

Now comes the interesting part.  How to do a comparision of the two arrays and determine if any VM names overlap.  This seemed like a perfect opportunity to use a regular expression.  I remember reading an article on the Scripting Guys called “Speed Up Array Comparisions in Powershell with a Runtime Regex” where the author discussed the benefits of using the -Match operator with a regular expression  instead of the -Contains comparison operator.  Needless to say using a regular expression was way faster…10x faster and since Powershell is all about automation and efficiency , creating a regex seems like the way to go.

 [regex]$ActiveVMs_Regex = '(?i)^('+(($ActiveVMs |
        Foreach {[regex]::Escape($_)})-join "|" )+')$'

The only thing left now was to run the -Match comparison and import the VM’s  using Import-VM.   I also needed to use Start-Sleep 5 because during my initial tests ( and there were many of them ) some VM’s weren’t imported.  It was random and not consistent but after having the script pause before each import provided just the rate of success I was looking for.   Powershell you rock!!!

            
 #Import the VMs            
 $VMsToImport -notmatch $ActiveVMs_Regex |             
        Foreach{ Import-VM (Join-Path $path $_ )             
        Start-Sleep 5            
  }

Here is the complete function..

Function Import-VMs {            

 Param (
  $ModulePath = ($env:psmodulePath -split ";")[1],
  $ModuleName = "HyperV",
  $path = "C:\Program Files\Microsoft Learning\6419\Drives\"
     )            
 #Copy the HyperV module if it doesn't already exist
 if(!((Dir $ModulePath) -match $ModuleName)) {
  Copy-Item .\$ModuleName $ModulePath -Recurse
     }             

 #Import the HyperV module if not already imported
 if(!(Get-Module | Where{$_.Name -like $ModuleName})) {
   Import-Module $ModuleName
     }            

 #Create array to contain active VM's
 $ActiveVMs = Get-VM | Foreach{$_.ElementName}            

 #Create array to contain VM's to be imported
 $VMsToImport = ( Get-ChildItem $path ) | Foreach{$_.Name}
 [regex]$ActiveVMs_Regex = '(?i)^('+(($ActiveVMs |
        Foreach {[regex]::Escape($_)})-join "|" )+')$'            

 #Import the VMs            
 $VMsToImport -notmatch $ActiveVMs_Regex |             
        Foreach{ Import-VM ( Join-Path $path $_ )             
        Start-Sleep 5            
     }
}#End Function
Categories: Powershell Tags: ,