Library of small useful functions

This is a library of functions. These can be put in a file and dot sourced PowerShell starts or they can be used in larger scripts

The libarary contains the following functions:

function set-windowsize {
<#
	.Synopsis
		Sets the powershell window size
	.Description
		Uses the $Host.UI.RawUI object to set the powershell window size
	.Parameter width
		width of window
	.Parameter height
		height of window
	.NOTES
		Author: Tom Willett
		Date: 6/20/2014
		 2014 Oink Software
#>

[CmdletBinding()] 
Param([Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)][string]$width,[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)][string]$height)
	process {
		$w =  new-object -typename System.Management.Automation.Host.Size
		$w.height = 400
		$w.width = 300
		$Host.UI.RawUI.buffersize = $w
		$w =  new-object -typename System.Management.Automation.Host.Size
		$w.height = $height
		$w.width = $width
		$Host.UI.RawUI.windowsize = $w
	}
}

function Get-LoggedOnUser {
<#
	.Synopsis
		Function gets current user using explorer process
	.Description
		gets current user by querying the process for user of explorer process
	.Parameter computername
		A computer name or ip
	.NOTES
		Author: Tom Willett
		Date: 6/14/2013
		 2013 Oink Software
	.Outputs
		an object containing the computer name, user and usersid
	.Inputs
		A computer name or ip
#>

[CmdletBinding()]             
 Param              
   (                        
    [Parameter(Mandatory=$false, 
               Position=0,                           
               ValueFromPipeline=$true,             
               ValueFromPipelineByPropertyName=$true)]             
    [String[]]$ComputerName = $env:COMPUTERNAME 
   )#End Param 
 
Begin             
{             
 Write-Host "`n Checking Users . . . " 
 $i = 0 
 $MyParams = @{ 
     Class       = "Win32_process"  
     Filter      = "Name='Explorer.exe'"  
     ErrorAction = "Stop" 
    } 
}#Begin           
Process             
{ 
    $ComputerName | Foreach-object { 
    $Computer = $_ 
     
    $MyParams["ComputerName"] = $Computer 
    try 
        { 
            $processinfo = @(Get-WmiObject @MyParams) 
            if ($Processinfo) 
                {     
                    $Processinfo | ForEach-Object {  
                        New-Object PSObject -Property @{ 
                            ComputerName=$Computer 
                            LoggedOn    =$_.GetOwner().User 
                            SID         =$_.GetOwnerSid().sid} } |  
                    Select-Object ComputerName,LoggedOn,SID 
                }#If 
        } 
    catch 
        { 
            "Cannot find any processes running on $computer" | Out-Host 
        } 
     }#Forech-object(ComputerName)        
             
}#Process 
End 
{ 
 
}#End 
 
}#Get-LoggedOnUsers 

function get-timezone([Parameter(Mandatory = $True, Position = 0)][string]$ws) {
<#
	.Synopsis
		Function gets the timezone setting for a computer using wmi
	.Description
		get-timezone returns an object containing the computer name and timezone or null if error
	.Parameter ws
		A computer name or ip
	.NOTES
		Author: Tom Willett
		Date: 6/14/2013
		 2013 Oink Software
	.Outputs
		an object containing the computer name and timezone or null if error
	.Inputs
		A computer name or ip
#>
	$objWMI = get-WMIObject Win32_TimeZone -computer $ws -erroraction silentlycontinue
	if ($?) {
		$temp = "" | Select Computer,TimeZone
		$temp.Computer = $ws
		$temp.TimeZone = $objWMI.Caption
	}
	else
	{
		$temp = $null
	}
	return $temp
}

function get-OS([Parameter(Mandatory = $True, Position = 0)][string] $comp) {
<#
	.Synopsis
		Checks Windows OS Version
	.Description
		get-os returns an integer designating the OS version
	.Parameter comp
		A computer name or ip
	.NOTES
		Author: Tom Willett
		Date: 6/14/2013
		 2013 Oink Software
	.Outputs
		Returns
		0 if unknown
		1 Windows 2000
		2 Windows XP
		3 Windows XP 64bit
		4 Windows Server 2003 (R2)
		5 Windows Vista
		6 Windows Server 2008
		7 Windows 7
		8 Windows Server 2008 R2
		9 Windows 8
		10 Windows Server 2012
	.Inputs
		A computer name or ip
#>
	[int]$os = 0
	#first check if it is server 2003 (XP) or server 2008 (Win 7) for paths
	$Version = gwmi win32_OperatingSystem -computername $comp -ErrorAction SilentlyContinue

	# if Error return 0
	if ($Version -eq $null) {
		$os = 0
	}
	else
	{
		if ($Version.version.startswith("5.0")) {
			$os = 1
		}
		if ($Version.version.startswith("5.1")) {
			$os = 2
		}
		if ($Version.version.startswith("5.2")) {
			$os = 3
			if ($Version.Caption.Contains("Server")) {
				$os = $os + 1
			}
		}
		if ($Version.version.startswith("6.0")) {
			$os = 5
			if ($Version.Caption.Contains("Server")) {
				$os = $os + 1
			}
		}
		if ($Version.version.startswith("6.1")) {
			$os = 7
			if ($Version.Caption.Contains("Server")) {
				$os = $os + 1
			}
		}
		if ($Version.version.startswith("6.2")) {
			$os = 9
			if ($Version.Caption.Contains("Server")) {
				$os = $os + 1
			}
		}
	}
	return $os
}

function is-Server([Parameter(Mandatory = $True, Position = 0)][string] $comp) {
<#
	.Synopsis
		Checks if windows computer is a server
	.Description
		is-server returns true if a server false if workstation null if error
	.Parameter comp
		A computer name or ip
	.NOTES
		Author: Tom Willett
		Date: 6/14/2013
		 2013 Oink Software
	.Outputs
		$true if server
		$false if workstation
		$null if error
	.Inputs
		A computer name or ip
#>
	$Version = gwmi win32_OperatingSystem -computername $comp -ErrorAction SilentlyContinue
	$srv = $null
	if ($Version) {
		# Set $srv to $true if it is a server else $false
		$srv = $Version.name.contains("Server")
	}
	return $srv
}

function get-os-size([Parameter(Mandatory = $True, Position = 0)][string] $comp) {
<#
	.Synopsis
		Checks for operating system size
	.Description
		Returns either 32 or 64 as the processor size
	.Parameter comp
		A computer name or ip
	.NOTES
		Author: Tom Willett
		Date: 5/9/2014
		 2013 Oink Software
	.Outputs
		"32" or "64" reflecting processor size
		$null if error
	.Inputs
		A computer name or ip
#>
	$psize = gwmi win32_processor -computername $comp | select -first 1 | select addresswidth
	$size = $null
	if ($psize) {
		# Set $srv to $true if it is a server else $false
		$size = $psize.addresswidth
	}
	return $size
}

function is-pingable([Parameter(Mandatory = $True, Position = 0)][string]$ipAddr) {
<#
	.Synopsis
		Ping a computer
	.Description
		is-pingable uses .net to ping a computer
	.Parameter ipaddr
		A computer name or ip
	.NOTES
		Author: Tom Willett
		Date: 6/14/2013
		 2013 Oink Software
	.Outputs
		$true if pingable
		$false if not pingable
	.Inputs
		A computer name or ip
#>
	$ErrorActionPreference = "SilentlyContinue"
	$Pingable = ""
	$temp = $null
	$ping = New-Object System.Net.NetworkInformation.Ping
	$temp = $ping.send($ipAddr,3000)
	$Pingable= $temp.Status.toString()
	return ($Pingable -eq "Success")
}

#
# This function deletes the files and directories in a given path with given filter with a given age and possibly hidden
# By default the filter is all files, the age is all files (uses Convert_String_to_date()), hidden files are ignored, it does not recurse subdirectories.
#
Function Delete_Files([Parameter(Mandatory = $True)][string] $Path, [Parameter(Mandatory = $True)][string] $filter, [Parameter(Mandatory = $True)][string] $age, [boolean] $hidden = $true, [boolean] $recurse = $true, [boolean]$myDebug = $false){
<#
	.Synopsis
		This function deletes the files and directories in a given path with given filter with a given age
	.Description
		This function deletes the files and directories in a given path with given filter with a given age and possibly hidden
		By default the filter is all files, the age is all files (uses Convert_String_to_date()), hidden files are ignored, it does not recurse subdirectories.
	.Parameter Path
		The path to the files and/or directories to delete (Understands unc paths)
	.Parameter Filter
		The file/direcory filter uses standard wildcards
	.Parameter age
		How old files/directories to delete (understands days weeks months etc.  See convert_string_to_date())
	.Parameter hidden
		if set to $false do not delete hidden files -- default $true
	.Parameter recurse
		if set to $false do not recurse -- default $true
	.Parameter myDebug
		if set to $true only show what would be deleted -- default $false
	.NOTES
		Author: Tom Willett
		Date: 6/14/2013
		 2013 Oink Software
	.Outputs
		none
	.Link
		convert_string_to_date()
#>

	$dt = Convert_String_to_date($age)

	if ($recurse) {
		if ($hidden) {
			if ($myDebug) {
				Get-ChildItem $path $filter -force -recurse -ErrorAction SilentlyContinue | where {$_.LastWriteTime -le $dt} | remove-item -force -recurse -whatif -ErrorAction SilentlyContinue
			}
			else
			{
				Get-ChildItem $path $filter -force -recurse -ErrorAction SilentlyContinue | where {$_.LastWriteTime -le $dt} | remove-item -force -recurse -ErrorAction SilentlyContinue
			}
		}
		else
		{
			if ($myDebug) {
				Get-ChildItem $path $filter -recurse -ErrorAction SilentlyContinue | where {$_.LastWriteTime -le $dt} | remove-item -force -recurse -whatif -ErrorAction SilentlyContinue
			}
			else
			{
				Get-ChildItem $path $filter -recurse -ErrorAction SilentlyContinue | where {$_.LastWriteTime -le $dt} | remove-item -force -recurse -ErrorAction SilentlyContinue
			}
		}
	}
	else
	{
		if ($hidden) {
			if ($myDebug) {
				Get-ChildItem $path $filter -force -ErrorAction SilentlyContinue | where {$_.LastWriteTime -le $dt} | remove-item -force -whatif -ErrorAction SilentlyContinue
			}
			else
			{
				Get-ChildItem $path $filter -force -recurse -ErrorAction SilentlyContinue | where {$_.LastWriteTime -le $dt} | remove-item -force -ErrorAction SilentlyContinue
			}
		}
		else
		{
			if ($myDebug) {
				Get-ChildItem $path $filter -ErrorAction SilentlyContinue | where {$_.LastWriteTime -le $dt} | remove-item -force -whatif -ErrorAction SilentlyContinue
			}
			else
			{
				Get-ChildItem $path $filter -ErrorAction SilentlyContinue | where {$_.LastWriteTime -le $dt} | remove-item -force -ErrorAction SilentlyContinue
			}
		}
	}
}

function Convert_String_to_date([Parameter(Mandatory = $True)][string] $myage) {
<#
	.Synopsis
		This function converts a string to a date relative to current date
	.Description
		This function converts a string to a date relative to current date.  The string needs to be in the format 2d for 2 days before now.  
		It understands m for month y for year and h for hour.  It returns a datetime object.
	.Parameter myage
		The aging string
	.NOTES
		Author: Tom Willett
		Date: 6/14/2013
		 2013 Oink Software
	.Outputs
		none
	.example
		convert_string_to_date("3w")  Return the date 3 weeks before now
	.example
		convert_string_to_date("2y")  Return date 2 years before now
#>

	[string]$interval = $myage.get_chars($myage.get_length()-1)
	[int]$n = $myage.substring(0,$myage.get_length()-1)

	$dte=(Get-Date)
	switch ($interval.ToLower())
	{
		"d"		{ $dte=(Get-Date).AddDays(-$n)}
		"m"		{ $dte=(Get-Date).AddMonths(-$n)}
		"y"		{ $dte=(Get-Date).AddYears(-$n)}
        "h"     { $dte=(Get-Date).AddHours(-$n)}
		"default" 	{ $dte=(Get-Date) }
	}
	$dte
}

function Pause ([string]$Message = "Press any key to continue...") {
<#
	.Synopsis
		Pauses script execution until a key is pressed
	.Description
		Pauses script execution until a key is pressed
	.Parameter message
		A prompt string  Default value is "Press any key to continue ..."
	.NOTES
		Author: Tom Willett
		Date: 6/14/2013
		 2013 Oink Software
#>

 	Write-Host -NoNewLine $Message
 	$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
 	Write-Host ""
}

function Format-HumanReadable([Parameter(Mandatory = $True)][int]$size) {
<#
	.Synopsis
		Formats a number to a human readable string kb mb tb etc
	.Description
		Formats a number to a human readable string kb mb gb tb etc
	.Parameter size
		A numeric string to convert
	.NOTES
		Author: Tom Willett
		Date: 6/14/2013
		 2013 Oink Software
#>
	if ($size -ge 1PB) {
		$hsize = [string][math]::round(($size/1PB),0) + "P"
	} elseif ($size -ge 1TB) {
		$isize=[math]::round(($size/1TB),0)
		$hsize=[string]$isize + "T"
	} elseif ($size -ge 1GB) {
		$isize=[math]::round(($size/1GB),0)
		$hsize=[string]$isize + "G"
	} elseif ($size -ge 1MB) {
		$isize=[math]::round(($size/1MB),0)
		$hsize=[string]$isize + "M"
	} elseif ($size -ge 1KB) {
		$isize=[math]::round(($size/1KB),0)
		$hsize=[string]$isize + "K"
	}
	$hsize += "B"
	return $hsize
}

Function convert-CIDR2Mask {
	<#
		.Synopsis
			Returns a dotted decimal subnet mask from a mask length.
		.Description
			convert-CIDR2Mask returns a subnet mask in dotted decimal format from an integer value ranging
			between 0 and 32. convert-CIDR2Mask first creates a binary string from the length, converts
			that to an unsigned 32-bit integer then calls convert-Long2IP to complete the operation.
		.Parameter MaskLength
			The number of bits which must be masked.
	#>
	[CmdLetBinding()]
	Param(
		[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
		[Alias("Length")]
		[ValidateRange(0, 32)]
		$MaskLength
	)
	Process {
		Return convert-Long2IP ([Convert]::ToUInt32($(("1" * $MaskLength).PadRight(32, "0")), 2))
	}
}

Function convert-IP2Long {
	<#
		.Synopsis
			Converts a Decimal IP address into a 32-bit unsigned integer.
		.Description
			convert-IP2Long takes a decimal IP, uses a shift-like operation on each octet and returns a single UInt32 value.
		.Parameter IPAddress
			An IP Address to convert.
	#>

	[CmdLetBinding()]
	Param(
		[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
		[Net.IPAddress]$IPAddress
	)
	Process {
		$i = 3; $DecimalIP = 0;
		$IPAddress.GetAddressBytes() | ForEach-Object { $DecimalIP += $_ * [Math]::Pow(256, $i); $i-- }
		Return [UInt32]$DecimalIP
	}
}

Function convert-Long2IP {
	<#
		.Synopsis
			Returns a dotted decimal IP address from either an unsigned 32-bit integer or a dotted binary string.
		.Description
			convert-Long2IP uses a regular expression match on the input string to convert to an IP address.
		.Parameter IPAddress
			A string representation of an IP address from either UInt32 or dotted binary.
	#>
	[CmdLetBinding()]
	Param(
		[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
		[String]$IPAddress
	)
	Process {
		Switch -RegEx ($IPAddress) {
			"([01]{8}\.){3}[01]{8}" {
			Return [String]::Join('.', $( $IPAddress.Split('.') | ForEach-Object { [Convert]::ToUInt32($_, 2) } ))
		}
		"\d" {
			$IPAddress = [UInt32]$IPAddress
			$DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
				$Remainder = $IPAddress % [Math]::Pow(256, $i)
				($IPAddress - $Remainder) / [Math]::Pow(256, $i)
				$IPAddress = $Remainder
			} )
			Return [String]::Join('.', $DottedIP)
		}
		default {
			Write-Error "Cannot convert this format"
		}
		}
	}
}

function do-nslookup ($ipAddr) {
<#
	.Synopsis
		Uses .net to do a nslookup
	.Description
		Uses .net to do a nslookup
	.Parameter ipaddr
		An ip or dns name
	.NOTES
		Author: Tom Willett
		Date: 6/14/2013
		 2013 Oink Software
#>
	return [System.Net.Dns]::GetHostEntry($ipAddr)
}

Function get-Network {
	<#
		.Synopsis
			Takes an IP address and subnet mask then calculates the network address for the range.
		.Description
			get-Network returns the network address for a subnet by performing a bitwise AND
			operation against the decimal forms of the IP address and subnet mask. get-Network
			expects both the IP address and subnet mask in dotted decimal format.
		.Parameter IPAddress
			Any IP address within the network range.
		.Parameter SubnetMask
			The subnet mask for the network.
	#>
	[CmdLetBinding()]
	Param(
		[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
		[String]$IPAddr,

		[Parameter(Mandatory = $False, Position = 1)]
		[Alias("Mask")]
		[Net.IPAddress]$SubnetMask
	)
	Process {
		if ($IPAddr.Contains("/")) {
			$temp = $IPAddr.Split("/")
			[Net.IPAddress]$IPAddr=$temp[0]
			[Net.IPAddress]$SubnetMask=convert-CIDR2Mask $temp[1]
		}
  		Return convert-Long2IP ((convert-IP2Long $IPAddr) -BAnd (convert-IP2Long $SubnetMask))
	}
}

Function get-Broadcast {
  <#
    .Synopsis
      Takes an IP address and subnet mask then calculates the broadcast address for the range.
    .Description
      get-Broadcast returns the broadcast address for a subnet by performing a bitwise AND
      operation against the decimal forms of the IP address and inverted subnet mask.
      get-Broadcast expects both the IP address and subnet mask in dotted decimal format.
    .Parameter IPAddress
      Any IP address within the network range. Will also take cidr notation.
    .Parameter SubnetMask
      The subnet mask for the network.
  #>

  [CmdLetBinding()]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
    [String]$IPAddress,

    [Parameter(Mandatory = $False, Position = 1)]
    [Alias("Mask")]
    [Net.IPAddress]$SubnetMask
  )

  Process {
	if ($IPAddress.Contains("/")) {
		$temp = $IPAddress.Split("/")
		[Net.IPAddress]$IPAddress=$temp[0]
		[Net.IPAddress]$SubnetMask=convert-CIDR2Mask $temp[1]
	}
    Return convert-Long2IP $((convert-IP2Long $IPAddress) -BOr `
      ((-BNot (convert-IP2Long $SubnetMask)) -BAnd [UInt32]::MaxValue))
  }
}

Function Get-NetworkRange([Parameter(Mandatory = $True)][String]$IP, [Parameter(Mandatory = $True)][String]$Mask ) {
<#
	.Synopsis
		Given an ip and mask or cidr returns all the addresses in a range
	.Description
		Given an ip and mask or cidr returns all the addresses in a range
	.Parameter ip
		An ip or cidr range
	.Parameter mask
		A network mask
	.NOTES
		Author: Tom Willett
		Date: 6/14/2013
		 2013 Oink Software
#>
	If ($IP.Contains("/"))  {
		$Temp = $IP.Split("/")
		$IP = $Temp[0]
		$Mask = $Temp[1]
	}
	If (!$Mask.Contains("."))  {
		$Mask = convert-CIDR2Mask $Mask
	}
	$DecimalIP = convert-IP2Long $IP
	$DecimalMask = convert-IP2Long $Mask
	$Network = $DecimalIP -BAnd $DecimalMask
	$Broadcast = $DecimalIP -BOr ((-BNot $DecimalMask) -BAnd [UInt32]::MaxValue)
	For ($i = $($Network + 1); $i -lt $Broadcast; $i++) {
		convert-Long2IP $i
	}
}

Function Get-NumIPS ([Parameter(Mandatory = $True)][string]$strNetwork){
<#
	.Synopsis
		Given a network range in cidr format return the number of addresses
	.Description
		Given a network range in cidr format return the number of addresses
	.Parameter strNetwork
		A cidr range
	.NOTES
		Author: Tom Willett
		Date: 6/14/2013
		 2013 Oink Software
#>
	$StrNetworkAddress = ($strNetwork.split("/"))[0]
	[int]$NetworkLength = ($strNetwork.split("/"))[1]
	$IPLength = 32-$NetworkLength
	$NumberOfIPs = ([System.Math]::Pow(2, $IPLength))
	Return $NumberofIPs
}

function get-input([Parameter(Mandatory = $True)][string]$Prompt,[string]$title = "Get Input") {
<#
	.Synopsis
		Visual Basic input box
	.Description
		Visual Basic input box
	.Parameter prompt
		Input prompt
	.Parameter title
		Title of box  default = "Get Input"
	.Outputs
		Returns value of input box
	.NOTES
		Author: Tom Willett
		 2013 Oink Software
#>
	[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic") | Out-Null
	[string][Microsoft.VisualBasic.Interaction]::InputBox($Prompt, $title)
}

<#
	Show windows forms message boxes
	MessageBoxButtons enum
		OK
		OKCancel
		AbortRetryIgnore
		YesNoCancel
		YesNo
		RetryCancel
	MessageBoxIcon enum
		None
		Hand
		Question
		Excalmation
		Asterisk
		Stop
		Error
		Warning
		Information
#>

function show-QuestionBox([Parameter(Mandatory = $True)][string]$message, [Parameter(Mandatory = $True)][string]$title) {
<#
	.Synopsis
		Windows forms question box
	.Description
		Windows forms question box
	.Parameter message
		Input prompt
	.Parameter title
		Title of box
	.Outputs
		Returns Yes or No
	.NOTES
		Author: Tom Willett
		 2013 Oink Software
#>
	[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
	[Windows.Forms.MessageBox]::Show($Message, $Title, [Windows.Forms.MessageBoxButtons]::YesNo, 
		[System.Windows.Forms.MessageBoxIcon]::Question, [System.Windows.Forms.MessageBoxDefaultButton]::Button1, 
		[System.Windows.Forms.MessageBoxOptions]::DefaultDesktopOnly)
}

function show-InformationBox ([Parameter(Mandatory = $True)][string]$message, [Parameter(Mandatory = $True)][string]$title) {
<#
	.Synopsis
		Windows forms Information box
	.Description
		Windows forms Information box
	.Parameter message
		Input prompt
	.Parameter title
		Title of box
	.Outputs
		Returns OK
	.NOTES
		Author: Tom Willett
		 2013 Oink Software
#>
	[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
	[Windows.Forms.MessageBox]::Show($Message, $Title, [Windows.Forms.MessageBoxButtons]::OK, 
		[System.Windows.Forms.MessageBoxIcon]::Information, [System.Windows.Forms.MessageBoxDefaultButton]::Button1, 
		[System.Windows.Forms.MessageBoxOptions]::DefaultDesktopOnly)
}

function ld-module([Parameter(Mandatory = $true)][string]$module) {
<#
	.Synopsis
		Load a powershell module if it is available
	.Description
		This checks if a powershell module is available and loaded.  If it is available and not loaded it loads it.
	.Parameter module
		Module name
	.Parameter Password
		New Password
	.NOTES
		Author: Tom Willett
		 2013 Oink Software
#>
	if(-not(Get-Module -name $module))
	{
		if(Get-Module -ListAvailable | Where-Object {$_.name -eq $module}) {
			Import-Module -Name $module
			$true
		} else {
			$false
		}
	} else {
		$true
	}
}

function reset-adaccountpassword([Parameter(Mandatory = $true)][string]$user, [Parameter(Mandatory =  $true)][string]$password) {
<#
	.Synopsis
		Reset AD Password
	.Description
		Uses ActiveDirectory Module to reset password
	.Parameter User
		SAM Account
	.Parameter Password
		New Password
	.Link
		ld-module
	.NOTES
		Author: Tom Willett
		 2013 Oink Software
#>
	ld-module ActiveDirectory
	set-adaccountpassword $user -newpassword (convertto-securestring -asplaintext $password -force) -reset
}

function get-serviceinfo([Parameter(Mandatory=$true)][string]$serviceName, [string]$computer=".") {
<#
	.Synopsis
		Gets information about a service using wmi
	.Description
		Reads win32_service for a particular service(s)
	.Parameter serviceName
		Service display name
	.Parameter computer
		computer where service resides
	.NOTES
		Author: Tom Willett
		 2013 Oink Software
#>
	get-wmiobject -query "select * from win32_service where name like '$serviceName%'" -computername $computer | format-list -property *
}

function get-processinfo([Parameter(Mandatory=$true)][string]$processName, [string]$computer=".") {
<#
	.Synopsis
		Gets information about a process using wmi
	.Description
		Reads win32_process for a particular process(s)
	.Parameter processName
		Process display name
	.Parameter computer
		computer where process resides
	.NOTES
		Author: Tom Willett
		 2013 Oink Software
#>
	get-wmiobject -query "select * from win32_process where name like '$processName%'" -computername $computer | format-list -property *
}

function get-processes([string]$computer=".") {
<#
	.Synopsis
		Gets information about all process using wmi
	.Description
		Reads win32_process for all processes
	.Parameter computer
		computer where processes resides
	.NOTES
		Author: Tom Willett
		 2013 Oink Software
#>
	get-wmiobject -query "select * from win32_process" -computername $computer | format-list -property *
}

function get-aduserbylastname([Parameter(Mandatory=$true)][string]$lastName){
<#
	.Synopsis
		Gets AD Users by last name
	.Description
		Uses RSAT powershell module to get all users by last name
	.Parameter lastName
		Lastname or partial (beginning)
	.NOTES
		Author: Tom Willett
		 2013 Oink Software
#>
	$flt = $lastname + "*"
	get-aduser -filter {surname -like $flt} -properties mail, description | format-table SamAccountName, name, description, mail 
}

function get-adcomputerpartial([Parameter(Mandatory=$true)][string]$computerName){
<#
	.Synopsis
		Gets AD computers with partial name
	.Description
		Uses RSAT powershell module to get all computers by partial name
	.Parameter lastName
		computername or partial (beginning)
	.NOTES
		Author: Tom Willett
		 2014 Oink Software
#>
	$flt = $computerName + "*"
	get-adcomputer -filter {name -like $flt} -properties operatingsystem, CanonicalName | format-table name, CanonicalName, operatingsystem
}

function get-adgroups([Parameter(Mandatory=$true)][string]$Name){
<#
	.Synopsis
		Gets AD Groups by name
	.Description
		Uses RSAT powershell module to get all groups by name
	.Parameter Name
		Name or partial (beginning)
	.NOTES
		Author: Tom Willett
		 2013 Oink Software
#>
	$flt = $Name + "*"
	get-adgroup -filter {Name -like $flt} | format-table Name
}

function get-bho([Parameter(Mandatory=$true)][string]$computer) {
	reg query "\\$computer\hklm\software\microsoft\windows\currentversion\explorer\browser helper objects" /s
}

function Get-Shares
{
<#
	.Synopsis
		Gets shares on a remote server
	.Description
		Uses wmi to get shares and path
	.Parameter server
		Server name
	.NOTES
		Author: Tom Willett
		 2013 Oink Software
#>

	param([string]$Server, [string]$drive = "*")
	$Shares = Get-WmiObject -Class Win32_Share -ComputerName $Server
	$output = @()
	ForEach ($Share in $Shares)
	{
		$fullpath = \\{0}\{1} -f $server, $share.name
		Add-Member -MemberType NoteProperty -InputObject $Share -Name FullPath -Value $fullpath
		$output += $Share
	}
	if ($drive -eq "*") {
		Return $output | sort-object path
	} else {
		Return $output | where {$_.path -match "^$drive" } | sort-object path
	}
}

function open-disk
{
	<#

	.SYNOPSIS
	Open Disk Management
	.DESCRIPTION
	Open Disk Management
	.EXAMPLE
	ps> .\open-disk.ps1
	Open Disk Management

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

diskmgmt.msc
}

function open-display
{
	<#

	.SYNOPSIS
	Open Display Properties
	.DESCRIPTION
	Open Display Properties
	.EXAMPLE
	ps> .\open-display.ps1
	Open Display Properties

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	control desk.cpl
}

function open-events
{
	<#
	.SYNOPSIS
	Open Event Viewer
	.DESCRIPTION
	Open Event Viewer
	.EXAMPLE
	ps> .\open-events.ps1
	Open Event Viewer

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	eventvwr.msc
}

function open-grouppolicy
{
	<#
	.SYNOPSIS
	Open Local Group Policy
	.DESCRIPTION
	Open Local Group Policy
	.EXAMPLE
	ps> .\open-grouppolicy.ps1
	Open Local Group Policy

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	gpedit.msc
}

function open-localusers
{
	<#
	.SYNOPSIS
	Open Local Users
	.DESCRIPTION
	Open Local Users
	.EXAMPLE
	ps> .\open-localusers.ps1
	Open Local Users

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	lusrmgr.msc
}

function open-manage
{
	<#
	.SYNOPSIS
	Open Computer Management
	.DESCRIPTION
	Open Computer Management
	.EXAMPLE
	ps> .\open-manage.ps1
	Open Computer Management

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	compmgmt.msc
}

function open-network
{
	<#
	.SYNOPSIS
	Open Network Properties
	.DESCRIPTION
	Open Network Properties
	.EXAMPLE
	ps> .\open-Network.ps1
	Open Network Properties

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	control ncpa.cpl
}

function open-programs
{
	<#
	.SYNOPSIS
	Open Add/Remove Programs
	.DESCRIPTION
	Open Add/Remove Programs
	.EXAMPLE
	ps> .\open-programs.ps1
	Open Add/Remove Programs

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	control appwiz.cpl
}

function open-securitypolicy
{
	<#
	.SYNOPSIS
	Open Local Security Policy
	.DESCRIPTION
	Open Local Security Policy
	.EXAMPLE
	ps> .\open-Securitypolicy.ps1
	Open Local Security Policy

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	secpol.msc
}

function open-shares
{
	<#
	.SYNOPSIS
	Open Share Management
	.DESCRIPTION
	Open Share Management
	.EXAMPLE
	ps> .\open-shares.ps1
	Open Share Management

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	fsmgmt.msc
}

function open-system
{
	<#
	.SYNOPSIS
	Open System Page
	.DESCRIPTION
	Open System Page
	.EXAMPLE
	ps> .\open-system.ps1
	Open System Page

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	control sysdm.cpl
}

function open-timedate
{
	<#
	.SYNOPSIS
	Open Time Date Properties
	.DESCRIPTION
	Open Time Date Properties
	.EXAMPLE
	ps> .\open-timedate.ps1
	Open Time Date Properties

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	control timedate.cpl
}

function open-windowsupdate
{
	<#
	.SYNOPSIS
	Open Windows Update
	.DESCRIPTION
	Open Windows Update
	.EXAMPLE
	ps> .\open-windowsupdate.ps1
	Open Windows Update

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	wuapp
}

function open-backup

	<#
	.SYNOPSIS
	Open Backup and Restore
	.DESCRIPTION
	Open Backup and Restore
	.EXAMPLE
	ps> .\open-backup.ps1
	Open Backup and Restore

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	sdclt
}

function open-devicemanager
{
	<#
	.SYNOPSIS
	Open Device Manager
	.DESCRIPTION
	Open Device Manager
	.EXAMPLE
	ps> .\open-DeviceManager.ps1
	Open Device Manager

	.NOTES

	Author: Tom Willett 
	Date: 9/24/2014
	 2014 Oink Software

	#>

	mmc devmgmt.msc
}