Tag: multiple

  • Get Inactive Users Report for the past 60 days in a multi domain environment

    Get Inactive Users Report for the past 60 days in a multi domain environment

    I had a request recently to provide an inactive user report for the past 60 days. Basically, find out which accounts have not logged in for the past 60 days so action can be taken against them.

    The request was for a multi domain forest which queries every domain controller and gets the latest lastlogon value by comparing value from each. I wrote a script and wanted to share as other might find it handy too.

  • Get Primary, Secondary, Tertiary DNS values and more from Multiple Servers

    Get Primary, Secondary, Tertiary DNS values and more from Multiple Servers

    Came across a unique request to get primary, secondary, and tertiary DNS values for multiple computers/servers across the domain. I started writing the script and got what I wanted.

    Now this started off as just to query for DNS Server information, but then I thought to add other pieces to get myself a good Network Inventory of all the servers in the environment.

    I am utilizing the Win32_NetworkAdapterConfiguration WMI Class to get the required information.

    You can modify the script below to suit your needs. The complete list of settings that can be captured:

      string   Caption;
      string   Description;
      string   SettingID;
      boolean  ArpAlwaysSourceRoute;
      boolean  ArpUseEtherSNAP;
      string   DatabasePath;
      boolean  DeadGWDetectEnabled;
      string   DefaultIPGateway[];
      uint8    DefaultTOS;
      uint8    DefaultTTL;
      boolean  DHCPEnabled;
      datetime DHCPLeaseExpires;
      datetime DHCPLeaseObtained;
      string   DHCPServer;
      string   DNSDomain;
      string   DNSDomainSuffixSearchOrder[];
      boolean  DNSEnabledForWINSResolution;
      string   DNSHostName;
      string   DNSServerSearchOrder[];
      boolean  DomainDNSRegistrationEnabled;
      uint32   ForwardBufferMemory;
      boolean  FullDNSRegistrationEnabled;
      uint16   GatewayCostMetric[];
      uint8    IGMPLevel;
      uint32   Index;
      uint32   InterfaceIndex;
      string   IPAddress[];
      uint32   IPConnectionMetric;
      boolean  IPEnabled;
      boolean  IPFilterSecurityEnabled;
      boolean  IPPortSecurityEnabled;
      string   IPSecPermitIPProtocols[];
      string   IPSecPermitTCPPorts[];
      string   IPSecPermitUDPPorts[];
      string   IPSubnet[];
      boolean  IPUseZeroBroadcast;
      string   IPXAddress;
      boolean  IPXEnabled;
      uint32   IPXFrameType[];
      uint32   IPXMediaType;
      string   IPXNetworkNumber[];
      string   IPXVirtualNetNumber;
      uint32   KeepAliveInterval;
      uint32   KeepAliveTime;
      string   MACAddress;
      uint32   MTU;
      uint32   NumForwardPackets;
      boolean  PMTUBHDetectEnabled;
      boolean  PMTUDiscoveryEnabled;
      string   ServiceName;
      uint32   TcpipNetbiosOptions;
      uint32   TcpMaxConnectRetransmissions;
      uint32   TcpMaxDataRetransmissions;
      uint32   TcpNumConnections;
      boolean  TcpUseRFC1122UrgentPointer;
      uint16   TcpWindowSize;
      boolean  WINSEnableLMHostsLookup;
      string   WINSHostLookupFile;
      string   WINSPrimaryServer;
      string   WINSScopeID;
      string   WINSSecondaryServer;

    Since the scripts are querying for information it is best if it runs from a DC or a privileged server with an account that has privileged access.

    To get the results you need the following two scripts:

    I needed to get all the network information for all the domain controllers in the domain. So the following code retrieves it for me. This came really handy in viewing all the DNS settings setup on all the DCs and correcting them if needed.

    This will get the information and export to an excel file that you can have handy for reference or auditing. Hope this helps!

  • Resolve IP Addresses from List of Host Names

    Resolve IP Addresses from List of Host Names

    If you have a list of hostnames/servers that you need IP addresses for its cumbersome to ping each server and get the ip address.

    PowerShell to the rescue!

    To do this we need a file called Server.txt with each server’s hostname on each line. I am storing the file in D:\Data\Servers.txt.

    Once we run the script below it resolves the ip via DNS and stores to another file called D:\Data\Addresses.txt.

    [su_note note_color=”#fafae8″]All the IP addresses are getting pulled from their DNS value. [/su_note]

    function Get-HostToIP($hostname) {     
        $result = [system.Net.Dns]::GetHostByName($hostname)     
        $result.AddressList | ForEach-Object {$_.IPAddressToString } 
    } 
     
    Get-Content "D:\Data\Servers.txt" | ForEach-Object {(Get-HostToIP($_)) >> d:\data\Addresses.txt}
  • Get PasswordAge for users in a particular domain

    Get PasswordAge for users in a particular domain

    In Office365 if you have more than one domain in a subscription, there are times where you may want to get the password age for users of that domain.

    In my case to check which users are covered and meeting policy and get the users addressed.

    Get-MsolUser -All -DomainName "yourdomainname.com" | select DisplayName, LastPasswordChangeTimeStamp,@{Name=”PasswordAge”;Expression={(Get-Date)-$_.LastPasswordChangeTimeStamp}}

    The output will be similar to:

  • Configure SNMP on an ESXi Host or multiple Hosts

    Recently I needed to configure all of our 40 or so ESXi hosts to forward SNMP traps to our corporate monitoring solution. This meant enabling and configuring SNMP on each of the hosts. Naturally, I wrote a script for this as 40 hosts is way too many to do manually.

    This article shows you how configure SNMP on an ESXi host manually, via PowerCLI and via host profiles.

    Option 1: Manually via Command Line

    This is the most boring approach and should really only be used if you only have a few ESXi hosts to do, or if you really like doing things manually 🙂

    1. Start the SSH service on the ESXi host (Configuration >> Software >> Security Profile >> Services)
    2. SSH into host (using putty or something similar)
    3. Run the following to configure SNMP settings, enable SNMP in the firewall and start the SNMP agent:
      esxcli system snmp set --communities 
      esxcli system snmp set --targets 
      esxcli system snmp set --enable true
      
      esxcli network firewall ruleset set --ruleset-id snmp --allowed-all true
      esxcli network firewall ruleset set --ruleset-id snmp --enabled true
      
      /etc/init.d/snmpd restart

      Note 1: Replace <COMMUNITY_STRING> with the community string for your monitoring solution.

      Note 2: Replace <TARGET_STRING> with the target string that maps to your environment, in the format of target_address@port/community_string.

      Option 2: Manually via PowerCLI

      Option number 2 is to use PowerCLI to configure SNMP on an ESXi host. The following script is how to do this on a single host. To configure SNMP on an whole bunch of ESXi hosts, see option 3 below.

      #Script Variables
      $sESXiHost = ''
      $sCommunity = ''
      $sTarget = ''
      $sPort = ''
      
      #Connect to ESXi host
      Connect-VIServer -Server $sESXiHost
      
      #Clear SNMP Settings
      Get-VMHostSnmp | Set-VMHostSnmp -ReadonlyCommunity @()
      
      #Add SNMP Settings
      Get-VMHostSnmp | Set-VMHostSnmp -Enabled:$true -AddTarget -TargetCommunity $sCommunity -TargetHost $sTarget -TargetPort $sPort -ReadOnlyCommunity $sCommunity
      
      #Get SNMP Settings
      $Cmd= Get-EsxCli -VMHost $sESXiHost
      $Cmd.System.Snmp.Get()

      Note: Prior to being able to use the script above, ensure you configure the following variable values:

      • <ESXI_HOST> – The FQDN or the IP address of the ESXi host you want to enable SNMP on.
      • <COMMUNITY> – This is the community string you require for your environment (same as in option 1 above).
      • <TARGET> – This is the FQDN or IP address of the target you want to send the SNMP traps to. Note: THIS IS NOT A TARGET STRING as in option 1. In this instance you ONLY need the FQDN or IP address. The @port and the community_string will be added automatically by the Set-VMHostSnmp cmdlet.
      • <PORT> – The port you require SNMP traps to be sent on.

    Option 3: Automatically via PowerCLI

    If you have to configure SNMP for more than just a handful of ESXi hosts, then it is worth automating the entire process through a PowerCLI script. The logic around enabling SNMP on the ESXi host is the same as in option 2 above, with some additional logic around this to enumerate and complete the process on all ESXi Hosts.

    Here is a script that will connect to a vCenter Server, get a list of all ESXi Hosts and then configure SNMP on each ESXi host:

    #requires -version 4
    <#
    .SYNOPSIS
      Configure SNMP Settings on ESXi Hosts
    
    .DESCRIPTION
      Connect to vCenter Server and configure all ESXi hosts with SNMP settings
    
    .PARAMETER None
    
    .INPUTS Server
      Mandatory. The vCenter Server or ESXi Host the script will connect to, in the format of IP address or FQDN.
    
    .INPUTS Credentials
      Mandatory. The user account credendials used to connect to the vCenter Server of ESXi Host.
    
    .OUTPUTS Log File
      The script log file stored in C:\Windows\Temp\Set-HostSNMP.log.
    
    .EXAMPLE
      .\Set-HostSNMP.ps1
    #>
    
    #---------------------------------------------------------[Initialisations]--------------------------------------------------------
    
    #Set Error Action to Silently Continue
    $ErrorActionPreference = 'SilentlyContinue'
    
    #Dot Source required Function Libraries
    . 'C:\Scripts\Logging_Functions.ps1'
    
    #Add VMware PowerCLI Snap-Ins
    Add-PSSnapin VMware.VimAutomation.Core
    
    #----------------------------------------------------------[Declarations]----------------------------------------------------------
    
    #Script Version
    $sScriptVersion = '1.0'
    
    #Log File Info
    $sLogPath = 'C:\Windows\Temp'
    $sLogName = 'Set-HostSNMP.log'
    $sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
    
    #SNMP Settings
    $global:sCommunity = '<COMMUNITY>'
    $global:sTarget = '<TARGET>'
    $global:sPort = '<PORT>'
    
    #-----------------------------------------------------------[Functions]------------------------------------------------------------
    
    Function Connect-VMwareServer{
      Param([Parameter(Mandatory=$true)][string]$VMServer)
    
      Begin{
        Log-Write -LogPath $sLogFile -LineValue "Connecting to VMware environment [$VMServer]..."
      }
    
      Process{
        Try{
          $oCred = Get-Credential -Message 'Enter credentials to connect to vSphere Server or Host'
          Connect-VIServer -Server $VMServer -Credential $oCred
        }
    
        Catch{
          Log-Error -LogPath $sLogFile -ErrorDesc $_.Exception -ExitGracefully $True
          Break
        }
      }
    
      End{
        If($?){
          Log-Write -LogPath $sLogFile -LineValue 'Completed Successfully.'
          Log-Write -LogPath $sLogFile -LineValue ' '
        }
      }
    }
    
    Function Start-ScriptExecution{
      Param()
    
      Begin{
        Log-Write -LogPath $sLogFile -LineValue 'Enumerating ESXi Hosts and setting SNMP configuration...'
      }
    
      Process{
        Try{
          #Get list of all ESXi hosts in connected environment
          $ESXHosts = Get-VMHost
    
          ForEach($ESXHost in $ESXHosts){
            Set-SNMPSettings -ESXHost $ESXHost
          }
        }
    
        Catch{
          Log-Error -LogPath $sLogFile -ErrorDesc $_.Exception -ExitGracefully $True
          Break
        }
      }
    
      End{
        If($?){
          Log-Write -LogPath $sLogFile -LineValue ' '
          Log-Write -LogPath $sLogFile -LineValue 'Completed Successfully.'
          Log-Write -LogPath $sLogFile -LineValue ' '
        }
      }
    }
    
    Function Set-SNMPSettings {
      Param([Parameter(Mandatory=$true)][string]$ESXHost)
    
      Begin{
        Log-Write -LogPath $sLogFile -LineValue ' '
        Log-Write -LogPath $sLogFile -LineValue "  $ESXHost - Configuring SNMP Settings"
      }
    
      Process{
        Try{       
          #Clear existing SNMP Configuration
          Get-VMHostSnmp -Server $ESXHost | Set-VMHostSnmp -ReadonlyCommunity @()
    
          #Add new SNMP Configuration
          Get-VMHostSnmp -Server $ESXHost | Set-VMHostSnmp -Enabled:$true -AddTarget -TargetCommunity $global:sCommunity -TargetHost $global:sTarget -TargetPort $global:sPort -ReadOnlyCommunity $global:sCommunity
        }
    
        Catch{
          Log-Error -LogPath $sLogFile -ErrorDesc "  $ESXHost - An error has occurred" -ExitGracefully $False
        }
      }
    
      End{
        If($?){
          Log-Write -LogPath $sLogFile -LineValue "  $ESXHost - Completed Successfully"
        }
      }
    }
    
    
    #-----------------------------------------------------------[Execution]------------------------------------------------------------
    
    Log-Start -LogPath $sLogPath -LogName $sLogName -ScriptVersion $sScriptVersion
    $Server = Read-Host 'Specify the vCenter Server or ESXi Host to connect to (IP or FQDN)?'
    Connect-VMwareServer -VMServer $Server
    Start-ScriptExecution
    Log-Finish -LogPath $sLogFile

    Note: Similar to option 2 above, you will need to configure the following variables first:

    • <COMMUNITY> – This is the community string you require for your environment (same as in option 1 above).
    • <TARGET> – This is the FQDN or IP address of the target you want to send the SNMP traps to.[su_note note_color=”#fafae8″]Note: THIS IS NOT A TARGET STRING as in option 1. In this instance you ONLY need the FQDN or IP address. The @port and the community_string will be added automatically by the Set-VMHostSnmp cmdlet. [/su_note]
    • <PORT> – The port you require SNMP traps to be sent on.

    Option 4: Automatically via Host Profiles

    Finally, if you are lucky enough to be running Enterprise Plus licensing, then you will have the ability to use Host Profiles. This allows you to configure SNMP within the host profile and then just apply that profile to all of your ESXi hosts.

    Follow these steps to add the SNMP configuration into an existing Host Profile:

    1. From the VI Client, navigate to Management >> Host Profiles
    2. Select the profile you want to add the SNMP settings and click Edit Profile
    3. Expand the SNMP Agent Configuration policy and select SNMP Agent Configuration
    4. In the Configuration Details pane, complete the followng:
      • Enable or Disable agent: Ticked
      • IP/UDP Port: The port you require SNMP traps to be sent on
      • SNMP Community String: The community string for your environment
      • Notification Receiver: The target string that maps to your environment, in the format of target_address@port/community_string
    5. Click OK to save changes
    6. For each ESXi host attach and apply the profile (Note: An ESXi host needs to be in maintenance mode to be able to apply the host profile)

    And that concludes how to configure SNMP on a ESXi host.

    Source