Archive

Archive for the ‘Powershell’ Category

Powershell: Importing Items into a Sharepoint List

March 7, 2012 1 comment

I was teaching a Windows Server 2003 to 2008 upgrade class onsite recently for a client and it included several Powershell examples on performing such tasks as installing a role\feature or managing AD users\groups.   While on break I got to speaking with one of the tech’s and asked if he was currently utilizing Powershell to automate common day to day tasks.  His response was not what I expected as he made the statement that he couldn’t see any use for Powershell.   My initial reaction was suprise as I thought any decent tech would want to embrace such a robust and versitile automation technology, especially one that provides a standard platform for managing all things Microsoft.   Read more…

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…

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: ,

Backing Up Event Logs using Powershell

January 31, 2012 5 comments

I was recently asked to create a script that would backup certain event logs ( Application & Security ) to it’s native .evt format and then clear all events from the corresponding logs once complete.  This seemed simple enough although I didn’t recall seeing any parameters in either Get-WinEvent or any of the *-Eventlog cmdlets that provided this functionality.  Then I remembered that when something can’t be done using object specific cmdlet the next possible option is to explore the Win32_* classess.   So I used Get-WMIObject to query possible Win32_* classes that referenced Event Log.

Get-WMIObject Win32_*event* -List

The query produced the following results:

So the question now was which Win32 class to choose from.   I  narrowed it down to the Win32_NTEvent* classes and after some further examination determined that Win32_NTEventLogFile had a method called BackupEventLog.  I was able to make this determination by using Get-Member on the class.

Get-WMIObject Win32_NTEventLogFile | Get-Member

This query displayed all Properties and Methods of the Event Logs.  I’ve filtered the results to display only the first few Methods

The BackupEventLogFile method accepts one overload of System.String type which will be the name of the backup log file with an .evt extension.  The files were going to be backed up daily and then the Event Logs cleared of all events  so I needed to make sure the backup log files had unique names and decided to include the current date in the event log name.  I also needed to use a Foreach loop so as to run the code on several Event Logs in sequence.   I also included the following parameters to make the function more versitile:

 Param(
      $Computername = $ENV:COMPUTERNAME,
      [array]$EventLogs = @("application","security"),
      $BackupFolder = "C:\BackupEventLogs\"
      )

Logic was also added to create the $BackupFolder if it didn’t exist.

If(!( Test-Path $BackupFolder )) { New-Item $BackupFolder -Type Directory }

I called the function Clear-EventLogs and below is the complete script.

Function Clear-Eventlogs {            

 Param(
  $Computername = $ENV:COMPUTERNAME,
  [array]$EventLogs = @("application","security"),
  $BackupFolder = "C:\BackupEventLogs\"
  )            

 Foreach ( $i in $EventLogs ) {
 If(!( Test-Path $BackupFolder )) { New-Item $BackupFolder -Type Directory }
 $eventlog="c:\BackupEventLogs\$i" + (Get-Date).tostring("yyyyMMdd") + ".evt"
 (get-wmiobject win32_nteventlogfile -ComputerName $computername |
  Where {$_.logfilename -eq "$i"}).backupeventlog($eventlog)            

 Clear-EventLog -LogName $i            

 }# end Foreach            

}#end function            

Clear-Eventlogs

The results of running the script are the following log files:

Categories: Powershell Tags: ,

Creating Hyper-V Symbolic Links using Powershell

January 31, 2012 1 comment

As an MCT I’m required to download preconfigured VM’s and supporting VHD’s from Microsoft which are then imported into base images running Server 2008 R2 and HyperV.  Prior to importing the VM’s, symbolic links need to be created in each VM’s root Virutal Hard Disk folder.  Symbolic links are shortcuts that are associated with base or middle tier VHD’s.  Microsoft even includes a .bat file that automates their creation.  An example of one of these .bat files is below:

@ECHO OFF
@ECHO Creating Symlinks necessary to import VM’s
rem ************  to create Symlink for Base Image
rem ************substitute VHDName.vhd with the name of the base image needed
mklink “Path:\Source.vhd” “Path:\Base.vhd”
pause

So it occurred to me that if a .bat file could automate the creation of one or more symbolic links, then perhaps a Powershell script could automate the execution of one or more individual .bat files.  Creating these symbolic links is a repetitive act of having to browse to each root VM’s folder, execute the .bat file and then close the corresponding cmd prompt.  This is surely another instance where time could be better spent elsewhere and so I turn to my old friend Powershell for a script to automate this mundane task.

The first step is define the path to the root VM folders.

$path = "C:\Program Files\Microsoft Learning\6419\Drives\"

Now we run Get-ChildItem on the folder using the -Include parameter to filter for .bat files only and then -Recurse to browse sub folders and files.   These results are then placed into the $vhds array variable.

$vhds = Get-ChildItem $path -Include *.bat -Recurse

The next step is to execute the .bat files by piping the $vhds array containing the required .bat files to Start-Process.  One of the problems I encountered was that, although Start-Process was able to execute the .bat files it wasn’t passing it’s results down the pipeline.  Most cmdlets do return output but on occasion certain cmdlets needs to be encouraged to do this using the -PassThru  parameter.

$vhds | %{ start-process "$_" -PassThru |

These results are then pipelined to Foreach-Object where I found it necessary to pause the script and allow the .bat file to properly execute using Start-Sleep 1.  Without the pause there is a quick blip on the screen and then the .bat file exists.  I remember reading a script in a recent blog article by Greg Caporale regarding printing .pdf’s where he incorporated Start-Sleep ( or it’s alias sleep ) to provide enough time for the .pdf files to print before closing Adobe Reader.   The Foreach-Object also passes down the pipline each individually open cmd process to Stop-Process which exits the open cmd prompt.

$vhds | %{ Start-Process "$_" -PassThru |
        %{ Start-Sleep 1 ; $_} | Stop-Process }

I then wrapped the whole thing into a function called it Import-SymbolicLinks and defined a $Path parameter to make the script that much more flexible by accepting parameter input. Below if the final script.

Function Create-SymbolicLinks {            

 Param(
  $path = "C:\Program Files\Microsoft Learning\6419\Drives\"
  )            

 $vhds = Get-ChildItem $path -Include *.bat -Recurse
 $vhds | %{ Start-Process "$_" -PassThru |
            %{ Start-Sleep 1 ; $_} | Stop-Process }
 }            

Create-SymbolicLinks

The obvious next step is to script the import of these VM’s as well as create snapshots.

Categories: Powershell Tags: ,