Tag Archives: powershell

Powershell: Active Directory Domain Operations

Hi,

some commands to manage Active Directory Domain Controllers by using the .NET System.DirectoryServices.ActiveDirectory.Domain Class.
Load the assembly

[reflection.assembly]::LoadWithPartialName("System.DirectoryServices.Protocols")|Out-Null

Get a Domain Object with the logon Domain of the current user
Continue reading Powershell: Active Directory Domain Operations

Advertisment to support michlstechblog.info

Powershell: How to show a message box

Sometimes while a powershell script is running you want to show a MessageBox with a information or warning to the user. In Windows Powershell no Commandlet exists to show a Message Box.

Nevertheless it is possible by using the .NET Windows.Forms.MessageBox class:-).

First of all load the assembly.

# Load assembly
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

To show the messagebox call the static function show(“Message Text”)
Continue reading Powershell: How to show a message box

Windows: Disable automatic Window arranging and resizing while dragging with the mouse (AeroSnap)

Sometimes the Windows 7 functionality to automatically arrange or resize a window while dragging is a pain. This feature is called Aero Snap. Here are good news, you can disable the behaviour :-).

Open the Control Panel, go to “Ease of Access center”. If you are there, click “Make the mouse easier to use” and enable “Prevent Windows from being automatically arranged when moved to the edge of the screen”.

Mouse Settings

Continue reading Windows: Disable automatic Window arranging and resizing while dragging with the mouse (AeroSnap)

OpenVPN: Generate a random MAC Address for TAP Interfaces on Windows

Hi,

if you use some image based technology to deploy your Windows installation, for example SCCM, MDT, Acronis and/or sysprep based, and OpenVPM is already included, the MAC Address of the TAP LAN interface isn’t changed by that way. But a unique MAC Address is requiered if the clients conntects to the same OpenVPN server. If multiple clients have the same MAC Address ping from VPN Clients sometimes fails with error “TTL expired in transit” and the VPN connection is unstable.

This powershellscript sets a MAC Address for each OpenVPN TAP adapter. In detail:

  • Creating a Eventlog TAPsetMAC
  • Get all instances for TAP Adapters by reading HKLM\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\MatchingDeviceID == “tap0901”
  • Generate a random MAC Address. Starting with Prefix defined in $sMACPrefix.
  • Writing the MAC to each Adapter
  • Log the result to the EventLog
########################################################
# Generate a random MAC for all OpenVPN tap LAN interfaces
#  Michael Albert
#  05.04.2013
# License: GPLv2
########################################################
# HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}
# MatchingDeviceID tap0901
# REG_SZ MAC=00-FF-8F-E3-A1-AE
$oRandom=New-Object System.random
function fGetRandomMAC([string]$sMACStart){
     if($sMACStart.length -ge 0 -and $sMACStart.length -le 11){
          for($iLoop=$sMACStart.length; $iLoop -le 11; $iLoop++){
               $iChar=$oRandom.Next(16)
               $sMACStart+=[String]::Format("{0:x}", $iChar).ToUpper()
          }
          return($sMACStart)
     }
     else{
          return $false
     }
}
function fConvert2MAC16([string]$sMAC12){
     [string]$sMAC16=""
     if($sMAC12.length -eq 12){
          for($iLoop=0;$iLoop -le 11;$iLoop++){
               $sMAC16+=$sMAC12.SubString($iLoop,1)
               if((($iLoop+1) % 2) -eq 0 -and ($iLoop+1) -lt 12){
                    $sMAC16+="-"
               }
          }
          return $sMAC16
     }
     else{
          return $false
     }
}
###############################################################################
# Currently not used but defined :-)
function fValidMAC([system.string]$sMAC){
          $RegExIP=new-object System.Text.RegularExpressions.Regex("^([0-9a-fA-F]{2}\-){5}([0-9a-fA-F]{2})$")
          return($RegExIP.IsMatch($sMAC))
}
###############################################################################
## MAIN
###############################################################################
$sMACPrefix="00FF8F"
if(! [System.Diagnostics.EventLog]::SourceExists("TAPsetMAC")){
     New-EventLog -Source TAPsetMAC -Log Application
}
$aTAPAdapter=Get-ChildItem "registry::HKLM\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}" -ErrorAction SilentlyContinue |where-object{$_.GetValue("MatchingDeviceID") -eq "tap0901"}
foreach($rTAPAdapter in $aTAPAdapter){
     # Get-ItemProperty -Path "registry::HKLM\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}"
     if(! ($rTAPAdapter.GetValue("MAC"))){
          #$rTAPAdapter
          #$rTAPAdapter.Name
          # Get-ItemProperty -Path ("registry::"+$rTAPAdapter.Name)
          $sMAC=fGetRandomMAC $sMACPrefix
          if($sMAC16=fConvert2MAC16 $sMAC){
               Write-Host -NoNewline  "Set MAC of TAP Adaper to" $sMAC16 "..."
               $Error.Clear()
               New-ItemProperty -Path ("registry::"+$rTAPAdapter.Name) -Force -Name MAC -PropertyType String -Value $sMAC16|Out-Null
               if(! $Error){
                    Write-Host "ok"
                    Write-EventLog -LogName Application -Source TAPsetMAC -EntryType Information -EventID 666 -Message ("TAP LAN Adapter: Altered MAC Address to "+$sMAC16)
               }
               else{
                    Write-EventLog -LogName Application -Source TAPsetMAC -EntryType Warning -EventID 666 -Message ("TAP LAN Adapter: Failed to altered MAC Address to "+$sMAC16)
               }
          }
     }
}

Michael

Powershell: Some basic XML handling with Powershell and .NET

Hi everybody,

here are some fundamentals to handle XML Files with powershell.

The following commands uses these XML File


<config description="Config file for testing">
    <system description="Document Management">
        <document authorFirstName="Kirk" authorSurname="Author1" date="20130503 01:15:43" description="Document Hammet" index="3">C:\temp\doc0001.txt</document>
        <document authorFirstName="Lars" authorSurname="Author5" date="20130503 10:05:42" description="Document Ulrich" index="4">C:\temp\doc0002.txt</document>
        <document authorFirstName="Cliff" authorSurname="Author5" date="20130612 11:54:33" description="Document Burton"  index="6">C:\temp\doc0051.txt</document>
        <document authorFirstName="Jason" authorSurname="Author2" date="20130806 04:02:41" description="Document Newsted"  index="1">C:\temp\doc0041.txt</document>
        <document authorFirstName="Robert" authorSurname="Smith" date="20131202 07:12:03" description="Document Trujillo"  index="2">C:\temp\doc0012.txt</document>
        <document authorFirstName="James" authorSurname="Smith" date="20130211 09:05:59" description="Document Hetfield"  index="5">C:\temp\doc0003.txt</document>
    </system>
</config>

Creating  a XML File, create a document root, create subelements, add and set attributes, save the file

# Create a new XML File with config root node
[System.XML.XMLDocument]$oXMLDocument=New-Object System.XML.XMLDocument
# New Node
[System.XML.XMLElement]$oXMLRoot=$oXMLDocument.CreateElement("config")
# Append as child to an existing node
$oXMLDocument.appendChild($oXMLRoot)
# Add a Attribute
$oXMLRoot.SetAttribute("description","Config file for testing")
[System.XML.XMLElement]$oXMLSystem=$oXMLRoot.appendChild($oXMLDocument.CreateElement("system"))
$oXMLSystem.SetAttribute("description","Document Management")
# Save File
$oXMLDocument.Save("c:\temp\config.xml")

Loading an existing XML File, read an element, do some XPATH queries

Continue reading Powershell: Some basic XML handling with Powershell and .NET