Powershell – Function to retrieve FSMO role holders

May 5, 2015 • Jonathan -

Small function to pull list of FSMO role holders for a domain.

function Get-FSMO {
    param(
        [Parameter(Mandatory=$True)][string]$forest,
        [Parameter(Mandatory=$True)][string]$domain
    )

    $forestInfo = Get-ADForest -Identity $forest | Select-Object SchemaMaster,DomainNamingMaster
    $domainInfo = Get-ADDomain -Identity $domain | Select-Object PDCEmulator,RIDMaster,InfrastructureMaster

    $fsmo = New-Object -TypeName PSObject -Property @{
        SchemaMaster = $forestInfo.SchemaMaster
        DomainNamingMaster = $forestInfo.DomainNamingMaster
        PDCEmulator = $domainInfo.PDCEmulator
        RIDMaster = $domainInfo.RIDMaster
        InfrastructureMaster = $domainInfo.InfrastructureMaster
    }

    return $fsmo
}

Get-FSMO -forest constoso.com -domain contoso
.



Powershell – Get LastLogon time for AD user accounts across all Domain Controllers

Feb 6, 2015 • Jonathan -

Set of scripts to query all domain controllers for the AD users LastLogon time and export the results to a CSV file. Useful for determining which accounts are active.

# import ActiveDirectory module
Import-Module ActiveDirectory

# load necessary functions
. .\Translate-ADName.ps1
. .\Get-ADUsersLastLogon.ps1

# get list of domain controllers
$domainControllers = (Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -Server $_ }

# set CSV export path
$exportPath = 'c:\tmp\userlist.csv'

# get list of enabled users
$users = Get-ADUser -Filter 'enabled -eq $true' -Properties LastLogonDate, Enabled, EmployeeID

# create empty array
$userList = @()

# loop through the users and make our custom object
foreach ($user in $users) {
    
    $i++
    Write-Progress -activity "Querying domain controllers for $($user.SamAccountName) " -status "Percent complete $([decimal]::round(($i / $users.length)  * 100))" -PercentComplete (($i / $users.length)  * 100)
        
    $object = New-Object –TypeName PSObject
    $object | Add-Member -MemberType NoteProperty –Name 'Name' –Value $user.name
    $object | Add-Member -MemberType NoteProperty –Name 'EmployeeID' –Value $user.EmployeeID
    $object | Add-Member -MemberType NoteProperty –Name 'SamAccountName' –Value $user.SamAccountName
    $object | Add-Member -MemberType NoteProperty -Name 'LastLogon' –Value $(Get-ADUserLastLogon $user.SamAccountName $domainControllers)
    $object | Add-Member -MemberType NoteProperty -Name 'OU' –Value $($user.DistinguishedName | Translate-ADName canonical)
    $userList+=$object
}

# export the results to CSV
$userList | Export-Csv -NoTypeInformation -Path $exportPath -Force
function Get-ADUserLastLogon([string]$userName, $domainControllers) {
    
    $time = 0
    foreach($dc in $domainControllers) { 
        $user = Get-ADUser $userName -Server $dc.HostName -Properties LastLogon
        if($user.LastLogon -gt $time) {
            $time = $user.LastLogon
        }
    }
    $dt = [DateTime]::FromFileTime($time)
    return $dt
}

The script below was taken from WindowsITPro.

function Translate-ADName { 
<#
.SYNOPSIS
Translates Active Directory names between various formats.

.DESCRIPTION
Translates Active Directory names between various formats using the NameTranslate COM object. Before names can be translated, the NameTranslate object must first be initialized. The default initialization type is 'GC' (see the -InitType parameter). You can use the -Credential parameter to initialize the NameTranslate object using specific credentials.

.PARAMETER OutputType
The output name type, which must be one of the following:
  1779              RFC 1779; e.g., 'CN=Phineas Flynn,OU=Engineers,DC=fabrikam,DC=com'
  DN                short for 'distinguished name'; same as 1779
  canonical         canonical name; e.g., 'fabrikam.com/Engineers/Phineas Flynn'
  NT4               domain\username; e.g., 'fabrikam\pflynn'
  display           display name
  domainSimple      simple domain name format
  enterpriseSimple  simple enterprise name format
  GUID              GUID; e.g., '{95ee9fff-3436-11d1-b2b0-d15ae3ac8436}'
  UPN               user principal name; e.g., [email protected]'
  canonicalEx       extended canonical name format
  SPN               service principal name format

.PARAMETER Name
The name to translate. This parameter does not support wildcards.

.PARAMETER InputType
The input name type. Possible values are the same as -OutputType, with the following additions:
  unknown          unknown name format; the system will estimate the format
  SIDorSIDhistory  SDDL string for the SID or one from the object's SID history
The default value for this parameter is 'unknown'.

.PARAMETER InitType
The type of initialization to be performed, which must be one of the following:
  domain  Bind to the domain specified by the -InitName parameter
  server  Bind to the server specified by the -InitName parameter
  GC      Locate and bind to a global catalog
The default value for this parameter is 'GC'. When -InitType is not 'GC', you must also specify the -InitName parameter.

.PARAMETER InitName
When -InitType is 'domain' or 'server', this parameter specifies which domain or server to bind to. This parameter is ignored if -InitType is 'GC'.

.PARAMETER ChaseReferrals
This parameter specifies whether to chase referrals. (When a server determines that other servers hold relevant data, in part or as a whole, it may refer the client to another server to obtain the result. Referral chasing is the action taken by a client to contact the referred-to server to continue the directory search.)

.PARAMETER Credential
Uses the specified credentials when initializing the NameTranslate object.

.FUNCTIONALITY
Active Directory

.EXAMPLE
PS C:\> Translate-ADName -OutputType dn -Name fabrikam\pflynn
This command outputs the specified domain\username as a distinguished name.

PS C:\> Translate-ADName canonical 'CN=Phineas Flynn,OU=Engineers,DC=fabrikam,DC=com'
This command outputs the specified DN as a canonical name.

PS C:\> Translate-ADName dn fabrikam\pflynn -InitType server -InitName dc1
This command uses the server dc1 to translate the specified name.

PS C:\> Translate-ADName display fabrikam\pflynn -InitType domain -InitName fabrikam
This command uses the fabrikam domain to translate the specified name.

PS C:\> Translate-ADName dn 'fabrikam.com/Engineers/Phineas Flynn' -Credential (Get-Credential)
Prompts for credentials, then uses those credentials to translate the specified name.

PS C:\> Get-Content DNs.txt | Translate-ADName -OutputType display -InputType dn
Outputs the display names for each of the distinguished names in the file DNs.txt.

.NOTES
    http://windowsitpro.com/active-directory/translating-active-directory-object-names-between-formats
#>

[CmdletBinding()]
param(

  [parameter(Mandatory=$TRUE,Position=0)]
  [validateset("NT4","1779","SPN","canonical","GUID","DN","UPN","display","domainSimple","enterpriseSimple","canonicalEx")]
    [String] $OutputType,

  [parameter(Mandatory=$TRUE,Position=1,ValueFromPipeline=$TRUE)]
    [String[]] $Name,

  [validateset("NT4","1779","SPN","canonical","GUID","DN","UPN","display","domainSimple","enterpriseSimple","canonicalEx","SIDorSidHistory","unknown")] 
    [String] $InputType="unknown",

  [validateset("domain","server","GC")]
    [String] $InitType="GC",

    [String] $InitName="",

    [Switch] $ChaseReferrals,

    [System.Management.Automation.PSCredential] $Credential
)

    begin {

      # Hash table to simplify output type names and values
      $OutputNameTypes = @{
        "1779"             = 1;
        "DN"               = 1;
        "canonical"        = 2;
        "NT4"              = 3;
        "display"          = 4;
        "domainSimple"     = 5;
        "enterpriseSimple" = 6;
        "GUID"             = 7;
        "UPN"              = 9;
        "canonicalEx"      = 10;
        "SPN"              = 11;
      }

      # Copy output type hash table and add two additional types
      $InputNameTypes = $OutputNameTypes.Clone()
      $InputNameTypes.Add("unknown", 8)
      $InputNameTypes.Add("SIDorSidHistory", 12)

      # Same as with previous hash tables...
      $InitNameTypes = @{
        "domain" = 1;
        "server" = 2;
        "GC"     = 3;
      }

      # Accessor functions to simplify calls to NameTranslate
      function invoke-method([__ComObject] $object, [String] $method, $parameters) {
        $output = $object.GetType().InvokeMember($method, "InvokeMethod", $NULL, $object, $parameters)
        if ( $output ) { $output }
      }
      function get-property([__ComObject] $object, [String] $property) {
        $object.GetType().InvokeMember($property, "GetProperty", $NULL, $object, $NULL)
      }
      function set-property([__ComObject] $object, [String] $property, $parameters) {
        [Void] $object.GetType().InvokeMember($property, "SetProperty", $NULL, $object, $parameters)
      }

      # Create the NameTranslate COM object
      $NameTranslate = new-object -comobject NameTranslate

      # If -Credential, use InitEx to initialize it; otherwise, use Init
      if ( $Credential ) {
        $networkCredential = $Credential.GetNetworkCredential()
        try {
          invoke-method $NameTranslate "InitEx" (
            $InitNameTypes[$InitType],
            $InitName,
            $networkCredential.UserName,
            $networkCredential.Domain,
            $networkCredential.Password
          )
        }
        catch [System.Management.Automation.MethodInvocationException] {
          write-error $_
          exit
        }
        finally {
          remove-variable networkCredential
        }
      }
      else {
        try {
          invoke-method $NameTranslate "Init" (
            $InitNameTypes[$InitType],
            $InitName
          )
        }
        catch [System.Management.Automation.MethodInvocationException] {
          write-error $_
          exit
        }
      }

      # If -ChaseReferrals, set the object's ChaseReferral property to 0x60
      if ( $ChaseReferrals ) {
        set-property $NameTranslate "ChaseReferral" (0x60)
      }

      # The NameTranslate object's Set method specifies the name to translate and
      # its input format, and the Get method returns the name in the output format
      function translate-adname2([String] $name, [Int] $inputType, [Int] $outputType) {
        try {
          invoke-method $NameTranslate "Set" ($inputType, $name)
          invoke-method $NameTranslate "Get" ($outputType)
        }
        catch [System.Management.Automation.MethodInvocationException] {
          write-error "'$name' - $($_.Exception.InnerException.Message)"
        }
      }
    }

    process {
      Foreach($item in $name){
        translate-adname2 $name $InputNameTypes[$InputType] $OutputNameTypes[$OutputType]
      }
    }
 }
.



Script – Set Adobe Flash Player Update Options

Jan 30, 2015 • Jonathan -

Batch script to set Adobe Flash Player automatic update options. Checks whether the machine is 32 or 64 bit and writes Flash configuration file mms.cfg to the appropriate folder.

@echo off
:: How To Check If Computer Is Running A 32 Bit or 64 Bit Operating System. - http://support.microsoft.com/kb/556009
reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" | find /i "x86" > NUL && set OS=32BIT || set OS=64BIT

:: write the mms.cfg file to the appropriate location
if %OS%==32BIT echo AutoUpdateDisable=0 > %windir%\System32\Macromed\Flash\mms.cfg
if %OS%==32BIT echo SilentAutoUpdateEnable=1 >> %windir%\System32\Macromed\Flash\mms.cfg

if %OS%==64BIT echo AutoUpdateDisable=0 > %windir%\SysWow64\Macromed\Flash\mms.cfg
if %OS%==64BIT echo SilentAutoUpdateEnable=1 >> %windir%\SysWow64\Macromed\Flash\mms.cfg
.



Powershell – Instapush.im push notifications

May 15, 2014 • Jonathan -

Powershell function to send push notifications to iPhone, iPad, or Android devices using the Instapush notification service. Utilizes the Invoke-RestMethod and ConvertTo-Json cmdlets.

function Send-InstapushNotification() {
    <#
    .SYNOPSIS
    Instapush makes it easy to get real-time notifications on your Android device, iPhone, and iPad
 
    .DESCRIPTION
    Instapush allows you to issue an http request, and have a notification delivered to your device.
     
    .PARAMETER applicationID
    (required) - your apps application ID
     
    .PARAMETER applicationSecret
    (required) - your application secret
     
    .PARAMETER pushArray
    (required) - An array containing your event and tracker information

    .EXAMPLE
    $trackers = @{email='rabble'}
    $push = @{event='test'; trackers=$trackers}
    Send-InstapushNotification -applicationID xxxxxxxxxxxx -applicationSecret xxxxxxxxxxxx -pushArray $push
     
    .LINK
    InstaPush API Documentation: https://instapush.im/developer/rest
 
    .LINK
    Invoke-RestMethod Technet Article: http://technet.microsoft.com/en-us/library/hh849971.aspx

    .LINK
    ConvertTo-Json Technet Article: http://technet.microsoft.com/en-us/library/hh849922.aspx

    #>
 
    param(
        [Parameter(Mandatory=$True)][string]$applicationID,
        [Parameter(Mandatory=$True)][string]$applicationSecret,
        [Parameter(Mandatory=$True)][array]$pushArray
    )

    # build the notification    
    $httpHeaders = @{}
    $httpHeaders.Add('x-instapush-appid',$applicationID)
    $httpHeaders.Add('x-instapush-appsecret',$applicationSecret)
    $httpHeaders.Add('Content-Type','application/json')
           
    # send the notification
    $result = Invoke-RestMethod -Uri 'https://api.instapush.im/v1/post' -Headers $httpHeaders -Body ($pushArray | ConvertTo-Json -Compress) -Method Post -ErrorAction SilentlyContinue
     
    return $result
}
.



Powershell – Send-PushoverNotification – Sending Pushover Notifications via Powershell

May 7, 2014 • Jonathan -

Pushover makes it easy to get real-time notifications on your Android device, iPhone, iPad, and Desktop. Below is a Powershell function utilizing the Invoke-RestMethod Powershell cmdlet to make it easier to send notifications from Powershell scripts.

function Send-PushoverNotification() {
    <#
    .SYNOPSIS
    Pushover makes it easy to get real-time notifications on your Android device, iPhone, iPad, and Desktop. 

    .DESCRIPTION
    Pushover uses a simple REST API to receive messages from your application and send them to devices running our device clients.
    
    .PARAMETER Token
    (required) - your application's API token
    
    .PARAMETER User
    (required) - the user/group key (not e-mail address) of your user (or you), viewable when logged into the pushover dashboard
    
    .PARAMETER message
    (required) - Your message
    
    .PARAMETER priority
    Send as -1 to always send as a quiet notification, 1 to display as high-priority and bypass the user's quiet hours, or 2 to also require confirmation from the user
    
    .PARAMETER device
    Your user's device name to send the message directly to that device, rather than all of the user's devices
    
    .PARAMETER title
    Your message's title, otherwise your app's name is used
    
    .PARAMETER url
    A supplementary URL to show with your message
    
    .PARAMETER url_title
    A title for your supplementary URL, otherwise just the URL is shown
    
    .PARAMETER timestamp
    A Unix timestamp of your message's date and time to display to the user, rather than the time your message is received by our API
    
    .PARAMETER sound
    The name of one of the sounds supported by device clients to override the user's default sound choice
    
    .EXAMPLE
    Send-PushoverNotification -token 'xxxxxxxxxxxxxx' -user 'xxxxxxxxxxxxxxxx' -message 'regular message goes here'

    .EXAMPLE
    Send-PushoverNotification -token 'xxxxxxxxxxxxxx' -user 'xxxxxxxxxxxxxxxx' -message 'important message' -priority 1 

    .EXAMPLE
    Send-PushoverNotification -token 'xxxxxxxxxxxxxx' -user 'xxxxxxxxxxxxxxxx' -message 'emergency message' -priority 2 -url 'http://site.contoso.com'  
    
    .LINK
    Pushover API Documentation: https://pushover.net/api

    .LINK
    Invoke-RestMethod Technet Article: http://technet.microsoft.com/en-us/library/hh849971.aspx
    #>

    param(
        [Parameter(Mandatory=$True)][string]$token,
        [Parameter(Mandatory=$True)][string]$user,
        [Parameter(Mandatory=$True)][string]$message,
        [Parameter(Mandatory=$False)][int]$priority = '0',
        [Parameter(Mandatory=$False)][string]$device,
        [Parameter(Mandatory=$False)][string]$title,
        [Parameter(Mandatory=$False)][string]$url,
        [Parameter(Mandatory=$False)][string]$url_title,
        [Parameter(Mandatory=$False)][string]$timestamp,
        [Parameter(Mandatory=$False)][string]$sound
    )
  
    # build the notification    
    $notification = @{}
    $psboundparameters.GetEnumerator() | % { 
        $notification.Add($($_.key), $($_.value))
    }
    
    # send the notification
    $result = Invoke-RestMethod -Uri 'https://api.pushover.net/1/messages.json' -Body $notification -Method Post -ErrorAction SilentlyContinue
    
    return $result
}
.



Powershell – Send PushBullet Notifications from PRTG

May 6, 2014 • Jonathan -

Powershell v3+ script to send notifications using the Pushbullet notification service. The script will determine all available devices based on the provided API keys and send the notification to all of them. Adding multiple API keys will result in the notification being sent to those users as well.

# specify the pushbullet api key(s)
$pushbulletApiKeys = @('xxxxxxxxxxxxxxxxxxxxxxxxx')

# build the message from the arguments passed by PRTG
for ($i=0; $i -lt $args.count; $i++) {
	$message+="$($args[$i]) "
}

# function to pushbullet notifications
function sendPushBulletNotification($apiKey, $message) {

    # convert api key into PSCredential object
    $credentials = New-Object System.Management.Automation.PSCredential ($apiKey, (ConvertTo-SecureString $apiKey -AsPlainText -Force))

    # get list of registered devices
    $pushDevices = Invoke-RestMethod -Uri 'https://api.pushbullet.com/api/devices' -Method Get -Credential $cred

    # loop through devices and send notification
    foreach ($device in $pushDevices.devices) {

        # build the notification
        $notification = @{
            device_iden = $device.iden
            type = 'note'
            title = 'PRTG Alert'
            body = $message
        }

        # push the notification
        Invoke-RestMethod -Uri 'https://api.pushbullet.com/api/pushes' -Body $notification -Method Post -Credential $credentials
    }
}

# send the notification(s)
foreach ($apiKey in $pushbulletApiKeys) {
    sendPushBulletNotification $apiKey $message
}
.



Powershell – Install SNMP Services Remotely on Windows Server 2008R2

Sep 27, 2013 • Jonathan -

The script below assumes you have an active directory group with all the servers as members.

# import the powershell active direcory module
Import-Module ActiveDirectory

# get the group members
$servers = Get-ADGroupMember -Identity GroupWithServersInIt

# install SNMP on the servers
foreach ($server in $servers) {
	invoke-command -computername $server.name -ScriptBlock {import-module ServerManager; Add-WindowsFeature SNMP-Services}
}
.



HyperV – Starting VM From Command Line

Aug 13, 2013 • Jonathan -

Starting a Virtual Machine from Powershell on a 2008R2 Core server with the Hyper-V role install.

# name of the vm we want to start
$vmName = "my-vm"
 
# find the vm
$query = "SELECT * FROM Msvm_ComputerSystem WHERE ElementName='" + $VMName + "'"

# get the vm
$vm = get-wmiobject -query $query -namespace "root\virtualization" -computername "."
 
# turn the vm on 
$res = $vm.RequestStateChange(2)
.



Powershell – Bulk Update Active Directory Department Field

Jul 24, 2013 • Jonathan -

Bulk update the Department field in active directory using Powershell Get-ADUser and Set-ADUser cmdlets.

# define the OU you want to set
$ou = "OU=Oregon,OU=Sales,OU=Users,DC=contoso,DC=com"
 
# define the server you want to make the changes on
$domainController = "dc1.constoso.com"
 
# set department text
$departmentText = 'Oregon - Sales'
 
# get the list of users
$users = Get-ADUser -Server $domainController -SearchBase $ou -Filter {(ObjectClass -eq "user")} -Properties Department
 
# apply the new department to the users we found
ForEach ($u in $users) {
    $u | Set-ADUser -Department $departmentText -Server $domainController
}
.



Powershell – Change Exchange Alias to Match SamAccountName

Jun 7, 2013 • Jonathan -

Quick Powershell snippet to modify a users Exchange Alias to match the the Active Directory SamAccountName. This came in handy when deploying Airwatch using the {EmailUserName} variables to configure Exchange properties in profiles.

$mboxes = Get-Mailbox -OrganizationalUnit contoso.com/users/sales

foreach ($m in $mboxes) {
	$m | Set-Mailbox -Alias $m.SamAccountName
}
.



subscribe via RSS