Powershell – Split PFX certificates

Standard

Hi!!
It’s been awhile since I’ve posted something but last week I wrote a small script which I think will be useful to you!

Part of my many tasks where I work is to manage our PKI and in general work with and issue certificates. When issuing certificates (which include the private key) using a Windows PKI you normally export the file in PFX format. This is useful when working with Windows servers or applications. However in Linux servers or applications it’s more common that you need the certificate split into two files e.g. cert.crt/cert.key which separate the public/private keys.
In order to convert/split the PFX file into two files and separate the public/private keys you need to use openssl and manually run specific commands. This can be a bit tricky if you aren’t familiar with openssl and certificates in general.

The script I wrote does this for you automatically and can also optionally convert the private key to PEM format or decrypt the private key so it isn’t password protected (some applications need this). This can save you a lot of time and hopefully make your lives easier 🙂

Prerequisites

You need to install OpenSSL as the script uses this to perform the different actions.

I have built the script in three different sections – Parameters, Initialize and Script Main. To begin with I will quickly explain the Parameters section.

PARAMETERS

#PARAMETERS
$openssl = 'C:\OpenSSL-Win64\bin\openssl.exe'
$sourcePFX = 'c:\mycert.pfx'
$sourcePFX_Passphrase = 'somepassword'
$convertToPEM = $true
$decryptPrivateKey = $true

$openssl – Path to your openssl.exe here.
$sourcePFX – Path to the PFX you want to connvert/split.
$sourcePFX_Passphrase – password of the $sourcePFX file.
$convertToPEM – Set to $true to convert the private key to PEM format. $false to ignore/not do it.
$decryptPrivateKey – Set to $true to decrypt the private key and remove the password protection (don’t give it out to anyone who’s not supposed to have it after this…). $false to ignore/not do it.

INITIALIZE

$sourcePFX_Dir = (Get-ChildItem $sourcePFX).DirectoryName
$PrivateKeyFile = $sourcePFX.Replace('.pfx', '-encrypted.key')
$PublicKeyFile = $sourcePFX.Replace('.pfx', '.crt')
$ErrorActionPreference = 'SilentlyContinue'

In this section use the parameters given to create some variables I will using in the script main.
$sourcePFX_Dir = (Get-ChildItem $sourcePFX).DirectoryName
Here I get the path of the directory of the source PFX so we can create the new certificates in the same place.

$PrivateKeyFile = $sourcePFX.Replace(‘.pfx’, ‘-encrypted.key’)
$PublicKeyFile = $sourcePFX.Replace(‘.pfx’, ‘.crt’)
Here I create file names of the new certs based on source PFX name.

$ErrorActionPreference = ‘SilentlyContinue’
Here I tell powershell to not display errors when running the script. This is because openssl returns messages that cause powershell to error out (even when it succeeds). This is a bit confusing so I chose to remove the errors displayed. You can remove this if you want as it’s not crucial.

SCRIPT MAIN

The embedded comments in this section should be enough to tell you what I’m doing here. Basically I start with running commands that extract the public and private keys into two new files. Then I add a few if statements that convert the converts to PEM and/or decrypts the private key if you set those params to true earlier.

#SCRIPT MAIN
#Extract the private key
& $openssl 'pkcs12' -in $sourcePFX -nocerts -out $PrivateKeyFile -password pass:$sourcePFX_Passphrase -passout pass:$sourcePFX_Passphrase 
#Extract the public key
& $openssl pkcs12 -in $sourcePFX -clcerts -nokeys -out $PublicKeyFile -password pass:$sourcePFX_Passphrase
#if specified convert private key to PEM
if ($convertToPEM)
{
	$PrivateKeyPEMFile = $PrivateKeyFile.Replace('.key', '-pem.key')
	& $openssl rsa -in $PrivateKeyFile -outform PEM -out $PrivateKeyPEMFile -passin pass:$sourcePFX_Passphrase -passout pass:$sourcePFX_Passphrase
}
#If specified decrypt the private key
if ($decryptPrivateKey)
{
	if ($convertToPEM)
	{
		$PrivateKeyFile = $PrivateKeyPEMFile
	}
	$decryptedKeyFile = $PrivateKeyFile.Replace('.key', '-decrypted.key').Replace('-encrypted','')
	& $openssl rsa -in $PrivateKeyFile -out $decryptedKeyFile -passin pass:$sourcePFX_Passphrase -passout pass:$sourcePFX_Passphrase
}

That’s it!!
I hope you find the script useful!
I have copied in the full script below for you to copy if needed.

<#	
	.NOTES
	===========================================================================	 
	 Created on:   	29-Mar-2017 12:16 PM
	 Created by:   	Noam Wajnman	  
	 Filename:		Split-PFXCertificate.ps1     	
	===========================================================================
	.DESCRIPTION
		Splits a PFX certificate into a public/private key pair. See the Parameters 
		section	to optionally convert to PEM and/or decrypt the private key.
#>
#PARAMETERS
$openssl = 'C:\OpenSSL-Win64\bin\openssl.exe'
$sourcePFX = 'c:\mycert.pfx'
$sourcePFX_Passphrase = 'somepassword'
$convertToPEM = $true
$decryptPrivateKey = $true
#INITIALIZE
$sourcePFX_Dir = (Get-ChildItem $sourcePFX).DirectoryName
$PrivateKeyFile = $sourcePFX.Replace('.pfx', '-encrypted.key')
$PublicKeyFile = $sourcePFX.Replace('.pfx', '.crt')
$ErrorActionPreference = 'SilentlyContinue'
#SCRIPT MAIN
#Extract the private key
& $openssl 'pkcs12' -in $sourcePFX -nocerts -out $PrivateKeyFile -password pass:$sourcePFX_Passphrase -passout pass:$sourcePFX_Passphrase 
#Extract the public key
& $openssl pkcs12 -in $sourcePFX -clcerts -nokeys -out $PublicKeyFile -password pass:$sourcePFX_Passphrase
#if specified convert private key to PEM
if ($convertToPEM)
{
	$PrivateKeyPEMFile = $PrivateKeyFile.Replace('.key', '-pem.key')
	& $openssl rsa -in $PrivateKeyFile -outform PEM -out $PrivateKeyPEMFile -passin pass:$sourcePFX_Passphrase -passout pass:$sourcePFX_Passphrase
}
#If specified decrypt the private key
if ($decryptPrivateKey)
{
	if ($convertToPEM)
	{
		$PrivateKeyFile = $PrivateKeyPEMFile
	}
	$decryptedKeyFile = $PrivateKeyFile.Replace('.key', '-decrypted.key').Replace('-encrypted','')
	& $openssl rsa -in $PrivateKeyFile -out $decryptedKeyFile -passin pass:$sourcePFX_Passphrase -passout pass:$sourcePFX_Passphrase
}
Advertisement

Set advanced settings on all VMs in a cluster

Standard

Recently I was tasked with modifying the VM advanced settings (or VMX settings) on all of our VMs. Since I didn’t want to manually edit the VMX files on 500+ VMs I resolved to make a script which could do the job instead. I eventually made a good and working script which I will go over below.
First off I want to say that I have based a great deal of this script on some code that I found here: https://communities.vmware.com/docs/DOC-18653. Many thanks to Alan Renouf for posting this article!
The script posted here has been improved a bit and is also more complete since it also connects to vcenter on its own. This should hopefully make this script useful even to admins who aren’t experienced with powershell.

###############################################################################
##set-VMAdvancedSettings.ps1
##
##Description:		sets/creates advanced settings on VMs based on CSV input
##Created by:		Noam Wajnman
##Creation Date:	March 11, 2014
###############################################################################
#VARIABLES
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
$PathToCSV = "$dir\vmsettings.csv"
$vcenter = "some_vcenter_server" #script will connect to this vcenter server
$clusterName = "Some_cluster" #advanced settings will be set on all VMs on this cluster
#FUNCTIONS
function ConnectToVcenter {
	param(
		$vcenter
	)
	#Load snap-in and connect to vCenter
	if (-not (Get-PSSnapin -Name VMware.VimAutomation.Core)) {
		Add-PSSnapin VMware.VimAutomation.Core
	}
	if ($global:DefaultVIServers.Count -ne 1) {
		Connect-VIServer $vCenter
	}
}
function Set-VMAdvancedConfiguration { 
	###############################################################################
	##Function set-VMAdvancedConfiguration
	##
	##Description:		sets/creates advanced settings on VMs
	##Created by:		Noam Wajnman
	##Creation Date:	March 11, 2014
	##Credits:			Based on code written by alan renouf found here: 
	#+					https://communities.vmware.com/docs/DOC-18653
	###############################################################################
	[CmdletBinding()]
	[OutputType([System.String])]
  	param(  
    	[Parameter(Mandatory=$true,ValueFromPipeline=$true)]$vm,  
      	[string]$PathToCSV
    )
	begin {		
		$vmConfigSpec = new-object VMware.Vim.VirtualMachineConfigSpec  
		$vmsettings = Import-Csv $PathToCSV -Header Key,Value
		$vmsettings | Foreach {  
        	$Value = new-object vmware.vim.optionvalue  
        	$Value.key = $_.key  
        	$Value.value = $_.value  
        	$vmConfigSpec.ExtraConfig += $Value  
        	Write-Host "Adding $($_.Key) = $($_.Value) to configuration specifications"  
		}
	}
  	process {    	  
    	$Task = ($vm.ExtensionData).ReconfigVM_Task($vmConfigSpec)  
      	Write-Host "Setting Advanced configuration for $($VM.Name)"    	 
  	}
	end {
		Write-Host "Finished applying advanced settings to VMs."
	}
}

#SCRIPT MAIN
ConnectToVcenter -vcenter $vcenter
Get-cluster $clusterName | get-vm | Set-VMAdvancedConfiguration -PathToCSV $PathToCSV

All you need to do to run the script is:
1. Create a CSV file in the same directory as the script. The CSV must have two “columns”, the name of the settings and the desired value. I did it in excel and my example CSV file looks like this:
vmsettings_in_excel
2. Edit two values in the #Variables section of the script. Set $vcenter to the name of your vcenter server and $clusterName to the name of your cluster (all VMs on this cluster will have their advanced settings changed according to what you wrote in the CSV file).

You can then run the script and see all the specified settings being changed automatically on your VMs. Yay 🙂

I hope you will find the script useful!!

Set VMTools time synchronization mode on all VMs in a cluster

Standard

When changing the time synchronization settings in your environment you may have to also make modifications in your VMWare infrastructure. Among other things it can be necessary to control if the VM should synchronize its time from the host server or not. Normally it’s a manual process where you have to click into the VM settings and go to the Options tab and select VMWare Tools and there check the box or not. This script will do all that for you and set the VMTools host time synchronization to the value you choose, on all VMs in a given cluster. This will save you a lot of time especially if you, like me, manage a VMWare infrastructure with hundreds of VMs.
Although the script is quite short I have divided it into three sections variables, functions and script main to simplify its structure.

Variables

#VARIABLES
$DebugPreference = "continue" #comment out to disable debug info
#Parameters
$vcenter = "some_vcenter_server" #your vcenter server name
$clusterName = "Some_Cluster" #advanced settings will be set on all VMs on this cluster
$TimeSync = $true #script will enable/disable time sync on host on the VMs based on this value. Valid values are $true and $false

Before you run the script you will need to fill out the parameters in the variables section. $clustername is the name of the cluster on which you want to the change the settings for your VMs. All VMs running on the cluster will have their VMTools host time sync value set to what you specify in $TimeSync.

Functions

#FUNCTIONS
function ConnectToVcenter {
	param(
		$vcenter
	)
	#Load snap-in and connect to vCenter
	if (-not (Get-PSSnapin -Name VMware.VimAutomation.Core)) {
		Add-PSSnapin VMware.VimAutomation.Core
	}
	if ($global:DefaultVIServers.Count -lt 1) {
		Connect-VIServer $vCenter
	}
}
function Set-SyncValue {
	[CmdletBinding()]
	[OutputType([System.String])]
	param(
		[Parameter(ValueFromPipeline=$true)]$VM,
		[bool]$SyncValue
	)
	begin {
		Write-Debug "Creating configuration specification object"
		$ConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 
		$ConfigSpec.tools = New-Object VMware.Vim.ToolsConfigInfo 
		$ConfigSpec.tools.syncTimeWithHost = $SyncValue
	}
	process {
		#configure the VM
		Write-Debug "Setting VMTools time sync to $SyncValue on $($VM.Name)"
		$View = get-view -viewtype virtualmachine -Filter @{'name'=$VM.Name} 
		$View.ReconfigVM_task($ConfigSpec)
		sleep 3 #wait for the configuration to complete
		#Check if the VM was configured as desired.
		$AfterView = get-view -viewtype virtualmachine -Filter @{'name'=$VM.Name} 
		[bool]$result = [System.Convert]::ToBoolean($AfterView.Config.Tools.syncTimeWithHost)		
		if ($result -eq $SyncValue) {
			Write-Debug "Successfully set the Tools.syncTimeWithHost on $VM to $SyncValue"
		}
		else {
			Write-Debug "Error - $VM - Couldn't set the Tools.syncTimeWithHost to the desired value of $SyncValue"
		}
	}
	end {
		Write-Debug "Finished setting time sync values on VMs."
	}
}

The script uses two functions which I will go over now.
1. Function ConnectToVcenter
This function takes one parameter $vcenter which is the name of the vcenter server. If not already done the function adds the VMWare snap-in for powershell and then connects to vcenter to make ready for the commands we will run after.
2. Function Set-SyncValue
Set-SyncValue takes two parameters $VM and $SyncValue. $VM can be passed from the pipeline which makes it easy to use in combination with other VMWare commands. The function works by first creating a configuration specification object with the value given in $SyncValue. After this it loops though the given VMs and reconfigures them accordingly. After the command to configure a VM has been sent, the script waits 3 seconds and then checks if the setting was updated to the value you wanted.

Script Main

#SCRIPT MAIN
ConnectToVcenter -vcenter $vcenter
Get-Cluster $clusterName | Get-VM | Set-SyncValue -SyncValue $TimeSync 

The script main is very short and simple. First I connect to vcenter using the function ConnectToVcenter. The actual work is then done in a one liner where I simply pipe all the VMs from the Get-Cluster and Get-VM cmdlets to the Set-SyncValue function.

That’s it. I hope you find the script useful. I have copied the full version of the script in below.

#####################################################################################################
##Script:			Set-VMTools_TimeSync.ps1
##
##Description:		enables/disables the VMTools time sync mode on all VMs in a given cluster.
##Created by:		Noam Wajnman
##Credits:			Part of this script was based on this article: 
#+					https://psvmware.wordpress.com/tag/disable-vmware-tools-time-sync-using-powercli/
##Creation Date:	April 28, 2014
#####################################################################################################
#VARIABLES
$DebugPreference = "continue" #comment out to disable debug info
#Parameters
$vcenter = "some_vcenter_server"
$clusterName = "Some_Cluster" #advanced settings will be set on all VMs on this cluster
$TimeSync = $true #script will enable/disable time sync on host on the VMs based on this value. Valid values are $true and $false
#FUNCTIONS
function ConnectToVcenter {
	param(
		$vcenter
	)
	#Load snap-in and connect to vCenter
	if (-not (Get-PSSnapin -Name VMware.VimAutomation.Core)) {
		Add-PSSnapin VMware.VimAutomation.Core
	}
	if ($global:DefaultVIServers.Count -lt 1) {
		Connect-VIServer $vCenter
	}
}
function Set-SyncValue {
	[CmdletBinding()]
	[OutputType([System.String])]
	param(
		[Parameter(ValueFromPipeline=$true)]$VM,
		[bool]$SyncValue
	)
	begin {
		Write-Debug "Creating configuration specification object"
		$ConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec 
		$ConfigSpec.tools = New-Object VMware.Vim.ToolsConfigInfo 
		$ConfigSpec.tools.syncTimeWithHost = $SyncValue
	}
	process {
		#configure the VM
		Write-Debug "Setting VMTools time sync to $SyncValue on $($VM.Name)"
		$View = get-view -viewtype virtualmachine -Filter @{'name'=$VM.Name} 
		$View.ReconfigVM_task($ConfigSpec)
		sleep 3 #wait for the configuration to complete
		#Check if the VM was configured as desired.
		$AfterView = get-view -viewtype virtualmachine -Filter @{'name'=$VM.Name} 
		[bool]$result = [System.Convert]::ToBoolean($AfterView.Config.Tools.syncTimeWithHost)		
		if ($result -eq $SyncValue) {
			Write-Debug "Successfully set the Tools.syncTimeWithHost on $VM to $SyncValue"
		}
		else {
			Write-Debug "Error - $VM - Couldn't set the Tools.syncTimeWithHost to the desired value of $SyncValue"
		}
	}
	end {
		Write-Debug "Finished setting time sync values on VMs."
	}
}
#SCRIPT MAIN
ConnectToVcenter -vcenter $vcenter
Get-Cluster $clusterName | Get-VM | Set-SyncValue -SyncValue $TimeSync

Powershell – Get inventory/slots of Dell chassis/blades

Standard

Here’s a script which will get the contents of your Dell blade chassis and export the list to a CSV file. This can be very useful to get an overview of or update your list of servers. The script uses the Dell racadm command “getslotname” and “plink.exe” to connect to the chassis and retrieve the information. You must download plink.exe (part of the putty suite) for this script to work.
I have divided the script into three sections variables, functions and script main to simplify the structure of the script. Below I will walk through the script and explain how I wrote each section.

Variables

#VARIABLES
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath #path to the directory in which the script is run.
$plink = "$dir\plink.exe" #path to plink.exe in the script directory
$CSV = "$dir\SlotNames.csv" #results will be exported to a csv file with this path
#Parameters
$username = "some_user" #username used to login to the chassis
$password = "some_password" #password used to login to the chassis
$ChassisNames = @("cmc01","cmc02","cmc03","cmc04","cmc05","cmc06") #add your chassis names or IPs in this array like shown.

The comments in the code pretty much explain all the different variables. Just remember to fill out the #parameters section according to your needs before you run the script.

Functions

1. Function Get-SlotName

function Get-SlotName {
	param (
		$ChassisName,
		$slotNumber
	)
	$EXE = $plink    
		$arg1 = "-pw"
		$arg2 = "$password"
		$arg3 = "$username@$ChassisName"
		$arg4 = "getslotname -i $slotnumber"		
		$command = "$EXE $arg1 $arg2 $arg3 $arg4"
		$output = invoke-expression -Command $command
		return $output
}

This function takes two parameters $ChassisName and $SlotNumber. It then uses plink.exe to run the command “getslotname -i slotnumber” on the chassis and return the output.

Script Main

#SCRIPT MAIN
clear
$Slots = @()
$ChassisNames | % {
	$Chassis = $_
	Write-Host "Getting information from $Chassis.."
	for ($i =1; $i -le 16; $i++) {
		$Slot = "" | select "Chassis","Slot #","Slot Name"
		$Slot.Chassis = $Chassis
		$Slot."Slot #" = $i
		$Slot."Slot Name" = Get-SlotName -ChassisName $Chassis -slotNumber $i
		$Slots += $Slot
	}
}
$Slots | Export-Csv $CSV -NoTypeInformation -Force

In the script main I start by looping through the array of chassis names $ChassisNames. As each chassis has 16 slots I then add a nested for loop to iterate over the integers 1-16. For each slot number 1-16 I create a custom object $Slot with the properties “Chassis”, “Slot #” and “Slot Name”. I use the Get-SlotName function to get the slot name value and assign it to the custom object along with the chassis and slot number values which I already have. I then add the $Slot object to the $Slots array. Finally the $Slots array is exported to CSV.
That’s it! I have copied in the full script below. I hope you find it useful. Enjoy!

################################################################################################
##Script:			Get-DellChassisSlots.ps1
##
##Description:		Gets an inventory of the slots in the given Dell blade chassis' and exports
#+					the information to a csv file. Needs plink.exe in order to run (download and
#+					place in the script directory). 
##Created by:		Noam Wajnman
##Creation Date:	April 09, 2014
################################################################################################
#FUNCTIONS
function Get-SlotName {
	param (
		$ChassisName,
		$slotNumber
	)
	$EXE = $plink    
		$arg1 = "-pw"
		$arg2 = "$password"
		$arg3 = "$username@$ChassisName"
		$arg4 = "getslotname -i $slotnumber"		
		$command = "$EXE $arg1 $arg2 $arg3 $arg4"
		$output = invoke-expression -Command $command
		return $output
}
#VARIABLES
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath #path to the directory in which the script is run.
$plink = "$dir\plink.exe" #path to plink.exe in the script directory
$CSV = "$dir\SlotNames.csv" #results will be exported to a csv file with this path
#Parameters
$username = "some_user" #username used to login to the chassis
$password = "some_password" #password used to login to the chassis
$ChassisNames = @("cmc01","cmc02","cmc03","cmc04","cmc05","cmc06") #add your chassis names or IPs in this array like shown.
#SCRIPT MAIN
clear
$Slots = @()
$ChassisNames | % {
	$Chassis = $_
	Write-Host "Getting information from $Chassis.."
	for ($i =1; $i -le 16; $i++) {
		$Slot = "" | select "Chassis","Slot #","Slot Name"
		$Slot.Chassis = $Chassis
		$Slot."Slot #" = $i
		$Slot."Slot Name" = Get-SlotName -ChassisName $Chassis -slotNumber $i
		$Slots += $Slot
	}
}
$Slots | Export-Csv $CSV -NoTypeInformation -Force

Get HBA device info from remote servers and export to CSV

Standard

If you work with SAN storage and fibre channel adapters it can be very useful to get an overview of all your HBAs (host bus adapters) on your servers. This script uses WMI to get HBA info like WWN, driver, version, model etc. from remote servers and then export it to a CSV file. You will then have a consolidated view of all your HBA devices with detailed information about them.
You will need to create the file servers.txt in the script directory and enter the names (one per line) of the servers you want to get the info from.
I have divided this script into three sections variables, functions and script main. I will now briefly explain how I created each section.

Variables

#VARIABLES
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath #path to the directory in which the script is run.
$servers = @(gc "$dir\servers.txt") #create servers.txt in the script directory and enter the names of servers you wish to query for HBA info.
$CSV = "$dir\HBAs.csv" #results will be exported to a csv file with this path

$servers is an array of server names populated by running Get-Content on the file servers.txt. $CSV is the path of the CSV file which will be created at the end of the script run. Both objects $servers and $CSV are defined using the object $dir which always points to the directory which the script was started in. This is practical as it allows me to copy and move the script around without having to change any paths.

Functions

1. Function Get-HBAInfo

#FUNCTIONS
function Get-HBAInfo {
	[CmdletBinding()]
	[OutputType([System.String])]
	param(  
		[parameter(ValueFromPipeline = $true)]$server  
	)	
	process {
		$WMI = Get-WmiObject -class MSFC_FCAdapterHBAAttributes -namespace "root\WMI" -computername $server		
		$WMI | % {
			$HBA = "" | select "server","WWN","DriverName","DriverVersion","FirmwareVersion","Model","ModelDescription"
			$HBA.server = $server
			$HBA.WWN = (($_.NodeWWN) | % {"{0:x}" -f $_}) -join ":"				
			$HBA.DriverName       = $_.DriverName  
			$HBA.DriverVersion    = $_.DriverVersion  
			$HBA.FirmwareVersion  = $_.FirmwareVersion  
			$HBA.Model            = $_.Model  
			$HBA.ModelDescription = $_.ModelDescription
			$HBA
		}			
	}	
}

This function takes a single parameter $server and runs a WMI query on it to get the HBA information. For each HBA device found on the server A custom object called $HBA is created and returned. The function can take input from the pipeline which is practical as you can simply pass the server name to the function using another script or cmdlet if you want.

Script Main

#SCRIPT MAIN
clear
$HBAs = @($servers | Get-HBAInfo)
$HBAs | Export-Csv $CSV -NoTypeInformation -Force

The script main is very simple consisting of only two lines. First I use the Get-HBAInfo function to get the HBA information from the given servers. Then, in the second line, the results are exported to CSV.

I have copied in the full script below. I hope you find it useful. Enjoy!!

################################################################################################
##Script:			Get-HBAInfo.ps1
##
##Description:		Gets information about HBAs on the given servers using WMI and exports it to 
#+					CSV. Remember to create the file servers.txt in the script directory and
#+					enter the names (one per line) of the servers you want to get the info from.
##Created by:		Noam Wajnman
##Creation Date:	February 28, 2013
##Updated:			April 08, 2014
################################################################################################
#FUNCTIONS
function Get-HBAInfo {
	[CmdletBinding()]
	[OutputType([System.String])]
	param(  
		[parameter(ValueFromPipeline = $true)]$server  
	)	
	process {
		$WMI = Get-WmiObject -class MSFC_FCAdapterHBAAttributes -namespace "root\WMI" -computername $server		
		$WMI | % {
			$HBA = "" | select "server","WWN","DriverName","DriverVersion","FirmwareVersion","Model","ModelDescription"
			$HBA.server = $server
			$HBA.WWN = (($_.NodeWWN) | % {"{0:x}" -f $_}) -join ":"				
			$HBA.DriverName       = $_.DriverName  
			$HBA.DriverVersion    = $_.DriverVersion  
			$HBA.FirmwareVersion  = $_.FirmwareVersion  
			$HBA.Model            = $_.Model  
			$HBA.ModelDescription = $_.ModelDescription
			$HBA
		}			
	}	
}
#VARIABLES
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath #path to the directory in which the script is run.
$servers = @(gc "$dir\servers.txt") #create servers.txt in the script directory and enter the names of servers you wish to query for HBA info.
$CSV = "$dir\HBAs.csv" #results will be exported to a csv file with this path
#SCRIPT MAIN
clear
$HBAs = @($servers | Get-HBAInfo)
$HBAs | Export-Csv $CSV -NoTypeInformation -Force

Powershell – Get DNS A records and export to CSV

Standard

When managing and cleaning up your IP addresses/ranges it can be very useful to get some lists of the records you have in your DNS zones. Here’s a simple script which gets the IP addresses/hostnames of the given DNS zones and exports the results to CSV.
The script is split into two parts Variables and script main. I will walk through and explain both parts below.

Variables

#VARIABLES
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
$CSV = "$dir\DNS_A_records.csv"
#parameters
$DNSServer = "Some_DNS_server"
$Zone1 = "myzone.local"
$Zone2 = "me.myzone.local"

I use the $dir object in the paths of my scripts as this object always points to the directory which the script has been run from. This is practical as it allows you to move/copy the script around without having to change any paths. $CSV is the path to the CSV file which will be created at the end of the script run.
Remember to fill out the parameters section before you run the script! $DNSServer is the name of your DNS server. $Zone1, $Zone2… etc are the names of the DNS zones which you want to get A records from. If you have more than 2 zones to get A records from then just add more objects to match the number of zones you need and add the zone names.

Script Main

#SCRIPT MAIN
clear
$DNS_Zones = @()
$DNS_Zones += $Zone1
$DNS_Zones += $Zone2
$hosts = @()
$DNS_Zones | % {
	$zone = $_
	Write-Host "Getting DNS A records from $zone"	
	$DNS_A_records = @(Get-WmiObject -Class MicrosoftDNS_AType -NameSpace Root\MicrosoftDNS -ComputerName $DNSServer -Filter "ContainerName = `'$zone`'")
	$DNS_A_records | % {
		$hostA = "" | select "hostname","IPAddress"
		$hostA.hostname = $_.OwnerName
		$hostA.IPAddress = $_.IPAddress
		$hosts += $hostA
	}
}
$hosts = $hosts | Sort-Object @{Expression={[Version]$_.IPAddress}}
$hosts | Export-Csv $CSV -NoTypeInformation -Force

In the script main I first create the array $DNS_Zones which will hold the different zone names. Then the zone names ($Zone1, $Zone2… etc.) are added to the array. If you created more than two zone objects in the variables section you must add them here too.
I now create the $hosts array which will hold the records we will wish export later. The next thing that happens is that we loop through the $DNS_Zones array. For each DNS Zone we get all A records using WMI and for each of these, a custom object with the properties hostname and IPAddress is created and added to the $hosts array.
I then sort the $hosts array by IP Address using the following code:
$hosts | Sort-Object @{Expression={[Version]$_.IPAddress}}
The @{Expression} argument allows you to add the [version] type declaration on the IPAddress property on the array elements/objects which in turn enables you to easily sort the IPs.
Finally the $hosts array is exported to CSV using the great Export-CSV powershell cmdlet.
I have copied in the full script below.I hope you find it useful. Enjoy!

################################################################################################
##Script:			Get-DNS_A_Records.ps1
##
##Description:		Gets all DNS A records from a given DNS server and exports the information 
#+					to a CSV file.
##Created by:		Noam Wajnman
##Creation Date:	April 07, 2014
################################################################################################
#VARIABLES
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
$CSV = "$dir\DNS_A_records.csv"
#parameters
$DNSServer = "Some_DNS_server"
$Zone1 = "myzone.local"
$Zone2 = "me.myzone.local"
#SCRIPT MAIN
clear
$DNS_Zones = @()
$DNS_Zones += $Zone1
$DNS_Zones += $Zone2
$hosts = @()
$DNS_Zones | % {
	$zone = $_
	Write-Host "Getting DNS A records from $zone"	
	$DNS_A_records = @(Get-WmiObject -Class MicrosoftDNS_AType -NameSpace Root\MicrosoftDNS -ComputerName $DNSServer -Filter "ContainerName = `'$zone`'")
	$DNS_A_records | % {
		$hostA = "" | select "hostname","IPAddress"
		$hostA.hostname = $_.OwnerName
		$hostA.IPAddress = $_.IPAddress
		$hosts += $hostA
	}
}
$hosts = $hosts | Sort-Object @{Expression={[Version]$_.IPAddress}}
$hosts | Export-Csv $CSV -NoTypeInformation -Force

Powershell – Get last boot time on remote servers and export results to CSV

Standard

Here’s a script to help you get the last boot time from remote windows servers. If you need to check the uptime of servers or troubleshoot unexpected restarts etc. then this script can be very useful.
The script uses WMI to get the information from the remote servers and then exports the results to a CSV file in the directory where the script was run. I have structured the script in three sections variables, functions and script main. I will go over these sections one by one now.

Variables

#VARIABLES

#$DebugPreference = "continue" #uncomment to get debug info
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath #path to the directory in which the script is run.
$servers = "$dir\Servers.txt" #last boot time will be retrieved on all the servers given in this file.
$CSVPath = "$dir\LastBootTimes.csv" #results will be exported to csv to a file with this path

The object $dir always points to the directory in which the script is run and is used in the paths to files I work with in the script. This makes the script more robust because I can copy the script wherever I want without having to change any paths at all or edit the script.
$servers is the path to “servers.txt” file. You must create this file before you run the script and enter the names (one per line) of the servers you want to get the last boot time from.
$CSVPath is the path to CSV file which will be created when the script is run.

Functions

1. Get-LastBootTime

#FUNCTIONS
function Get-LastBootTime {
	[CmdletBinding()]
	[OutputType([System.String])]
	param(
		[Parameter(ValueFromPipeline=$true)][System.String[]]$server = $env:COMPUTERNAME
	)
	begin {
		function Test-PortAlive {
			#############################################################################################
			##Function:			Test-PortAlive
			##
			##Description:		Tests connection on a given server on a given port.
			##
			##Created by:		Noam Wajnman
			##Creation Date:	April 02, 2014	
			##############################################################################################
			[CmdletBinding()]
			[OutputType([System.boolean])]
			param(
				[Parameter(ValueFromPipeline=$true)][System.String[]]$server
			)
			$socket = new-object Net.Sockets.TcpClient
			$connect = $socket.BeginConnect($server, 135, $null, $null) #port set to 135 (RPC)
			$NoTimeOut = $connect.AsyncWaitHandle.WaitOne(500, $false) #timeout value set to 500 ms
			if ($NoTimeOut) {
				$socket.EndConnect($connect) | Out-Null
				return $true				
			}
			else {
				return $false
			}
		}
	}
	process {		
		$BootTime = $null
		$server = $($server).toUpper()	
		$alive = Test-PortAlive -server $server
		if ($alive) {
			Write-Debug "connection to $server is open on port $port"			
			$OSInfo = Get-WmiObject win32_operatingsystem -ComputerName $server #get the info with WMI
			$BootTime = $OSInfo.ConvertToDateTime($OSInfo.LastBootUpTime) #convert to datetime
			$BootTime = '{0:yyyy-MM-dd HH:mm:ss}' -f $BootTime #parse time to sortable format
			if ($BootTime) {
				Write-Debug "$server was rebooted last time at:`t$BootTime"					
				$result = "" | select "Server","LastBootTime" #creating a custom object
				$result.Server = $server
				$result.LastBootTime = $BootTime
				$result #return the $result object
			}
			else {
				Write-Debug "couldn't get boot time from server $server"
			}
		}			
		else {
			Write-Debug "Error - connection to $server is not open on port $port"			
		}
	}	
}

the function Get-LastBootTime takes one parameter $server which can also be passed to it via the pipeline.
Pipeline functions usually have three parts “begin”, “process” and “end” (this function only uses “begin” and “process”). In the begin section I have included another function “Test-PortAlive” but I won’t go into details about it as I have covered this in a previous post dedicated to that function. In this script I use it to test if the server is alive and the RPC port 135 is open as this is needed to run the WMI query.
The “process” part of the function is where last boot time information is retrieved using WMI. Basically the function attempts to get the info. If successful then a custom object with the properties “server” and “LastBootTime” is created and returned.

Script Main

#SCRIPT MAIN

clear
$BootTimes = @(gc $servers | Get-LastBootTime) #create and populate array with the last boot times of the given servers.
$BootTimes = $BootTimes | Sort-Object -Property "LastBootTime" #Sort array by last boot time
$BootTimes #Prints the $bootTimes array to the console 
$BootTimes | Export-Csv $CSVPath -NoTypeInformation -Force #Export the results to CSV

In the script main the first thing which happens is to create the array $BootTimes and fill it with the data from Get-LastBootTime function. This is done by running Get-Content on the servers.txt file and then piping the server names to the Get-LastBootTime function.
After this I sort the $BootTimes array by last boot time.
Finally the $BootTimes array is exported to CSV in the script directory.
I have copied in the full script below. I hope you will find it useful.
Enjoy!!

################################################################################################
##Script:			Get-LastBootTime.ps1
##
##Description:		Gets the time of the last boot on the servers given in "servers.txt" and
#+					exports the results to a csv file in the script dir.
##Created by:		Noam Wajnman
##Creation Date:	May 21, 2013
##Updated:			April 02, 2014
################################################################################################
#FUNCTIONS
function Get-LastBootTime {
	[CmdletBinding()]
	[OutputType([System.String])]
	param(
		[Parameter(ValueFromPipeline=$true)][System.String[]]$server = $env:COMPUTERNAME
	)
	begin {
		function Test-PortAlive {
			#############################################################################################
			##Function:			Test-PortAlive
			##
			##Description:		Tests connection on a given server on a given port.
			##
			##Created by:		Noam Wajnman
			##Creation Date:	April 02, 2014	
			##############################################################################################
			[CmdletBinding()]
			[OutputType([System.boolean])]
			param(
				[Parameter(ValueFromPipeline=$true)][System.String[]]$server
			)
			$socket = new-object Net.Sockets.TcpClient
			$connect = $socket.BeginConnect($server, 135, $null, $null) #port set to 135 (RPC)
			$NoTimeOut = $connect.AsyncWaitHandle.WaitOne(500, $false) #timeout value set to 500 ms
			if ($NoTimeOut) {
				$socket.EndConnect($connect) | Out-Null
				return $true				
			}
			else {
				return $false
			}
		}
	}
	process {		
		$BootTime = $null
		$server = $($server).toUpper()	
		$alive = Test-PortAlive -server $server
		if ($alive) {
			Write-Debug "connection to $server is open on port $port"			
			$OSInfo = Get-WmiObject win32_operatingsystem -ComputerName $server #get the info with WMI
			$BootTime = $OSInfo.ConvertToDateTime($OSInfo.LastBootUpTime) #convert to datetime
			$BootTime = '{0:yyyy-MM-dd HH:mm:ss}' -f $BootTime #parse time to sortable format
			if ($BootTime) {
				Write-Debug "$server was rebooted last time at:`t$BootTime"					
				$result = "" | select "Server","LastBootTime" #creating a custom object
				$result.Server = $server
				$result.LastBootTime = $BootTime
				$result #return the $result object
			}
			else {
				Write-Debug "couldn't get boot time from server $server"
			}
		}			
		else {
			Write-Debug "Error - connection to $server is not open on port $port"			
		}
	}	
}
#VARIABLES
#$DebugPreference = "continue" #uncomment to get debug info
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath #path to the directory in which the script is run.
$servers = "$dir\Servers.txt" #last boot time will be retrieved on all the servers given in this file.
$CSVPath = "$dir\LastBootTimes.csv" #results will be exported to csv to a file with this path
#SCRIPT MAIN
clear
$BootTimes = @(gc $servers | Get-LastBootTime) #create and populate array with the last boot times of the given servers.
$BootTimes = $BootTimes | Sort-Object -Property "LastBootTime" #Sort array by last boot time
$BootTimes #Prints the $bootTimes array to the console 
$BootTimes | Export-Csv $CSVPath -NoTypeInformation -Force #Export the results to CSV

Powershell – Test TCP ports on remote servers

Standard

From time to time it is necessary to check if specific TCP ports are open on remote servers. If you have many servers to check it can be a hassle to use telnet or other tools and check each server one by one. It is also often useful in other scripts to test if a remote server/port is alive before running code on them. To accomplish this I have written this little function.

function Test-PortAlive {
	#############################################################################################
	##Function:			Test-PortAlive
	##
	##Description:		Tests connection on a given server on a given port.
	##
	##Created by:		Noam Wajnman
	##Creation Date:	April 02, 2014	
	##############################################################################################
	[CmdletBinding()]
	[OutputType([System.boolean])]
	param(
		[Parameter(ValueFromPipeline=$true)][System.String[]]$server,
		[int]$port
	)
	$socket = new-object Net.Sockets.TcpClient
	$connect = $socket.BeginConnect($server, $port, $null, $null)
	$NoTimeOut = $connect.AsyncWaitHandle.WaitOne(500, $false)
	if ($NoTimeOut) {
		$socket.EndConnect($connect) | Out-Null
		return $true				
	}
	else {
		return $false
	}
}

The function takes two parameters $server and $port. $server is the name of the remote server to test and $port is the number of the TCP port to check the status of. The $server parameter can even be passed via the pipeline making it very easy to run. The function returns either $true or $false depending on whether the port is open or not. To avoid long wait times due to closed ports I have included a relatively short timeout value of 500 ms before the result is determined.
I have included a few examples below of how to call the function.
1. Normal

 
Test-PortAlive -port 135 "some_server" 

Here I just run the function as normal and pass both params. I chose port 135 in this example but it could be any port.
2. Pipeline

 
$Array_of_Server_Names | Test-PortAlive -port 135

In this example I am using an array to pass the server names to the function via the pipeline. I again chose port 135 in this example.

That’s it. I hope you find this function useful. Enjoy!!