Powershell script to check out gateway configuration of remote computers

Hey guys,
I had a small task today to check out the configured gateway for some servers part of my Active Directory Domain Services. The servers have two network interfaces (frontend/backend). I wanted to see if a specific IP is configured on one of the interfaces from any of the servers included within an OU, so I came out with the following script:

$computers = Get-ADComputer -SearchBase ‘OU=Servers,DC=ppscu,DC=com’ -Filter ‘*’ | Select -Exp Name

foreach ($comp in $computers)

     $result = Invoke-Command -ComputerName $comp -ScriptBlock {
        $interfaces = Get-WmiObject Win32_NetworkAdapterConfiguration | ? { $_.IPEnabled }
        foreach ($int in $interfaces)
            $cmp = ($env:computername)
            $gateway = $int.DefaultIPGateway
            $ipaddress = $int.IPAddress        
            if ($gateway -like “”)
                Write-Host “$cmp has gateway on $ipaddress” -BackgroundColor Red
                Write-Host “$cmp does not have the specified gateway on $ipaddress, gateway is: $gateway ” -BackgroundColor white -ForegroundColor Black


Deploying Windows Server 2012 DC using Powershell

Hey guys,
In this short article I want to show you how to install Windows Server 2012 Domain Controllers and Forests by using the new Powershell cmdlets provided with this Edition. Server 2012 introduced a lot of new features and it has introduced a new way to install and configure Domain Controllers. Installing a new machine using the interface it’s still pretty intuitive so instead, I’ll insist in showing you how to achieve this by using Powershell. Before we can use the new cmdlets to configure our DC, execute the following command to install AD Domain Services:
Install-windowsfeature -name AD-Domain-Services –IncludeManagementTools

To explore newly introduced cmdlets, type in the following:
Get-Command -Module ADDSDeployment

Powershell Domain Controller deployment

There are two situations that can occur when deploying a new Domain Controller:

  • Deploying a DC in a new Forest
Before we can go at the installation part, we’ll need to make sure our new forest will pass the needed requirements. Use the Test-ADDSForestInstallation cmdlet to test the forest installation:

Test-ADDSForestInstallation -DomainName “ppscu.com” -NoRebootOnCompletion

Powershell create new Active Directory Forest

If the operation is completed successfully you can proceed further with the forest installation.
When adding the first Domain Controller to a new Forest, you will need to execute the following:

 -CreateDnsDelegation:$false `
 -DatabasePath “C:\Windows\NTDS” `
 -DomainMode “Win2012R2” `
 -DomainName “ppscu.com” `
 -DomainNetbiosName “ppscu.com” `
 -ForestMode “Win2012R2” `
 -InstallDns:$true `
 -LogPath “C:\Windows\NTDS” `
 -NoRebootOnCompletion:$false `
 -SysvolPath “C:\Windows\SYSVOL” `

You will be prompted to set a DSRM password for the specified forest. Note that the operation will take some time so be patience. The first Domain Controller within a Forest will also be a Global Catalog server.
  • Deploying a DC in an existing Domain
To test weather your forest supports adding the machine as a Domain Controller for your existing Farm, use the following cmdlet:

Test-ADDSDomainControllerInstallation -InstallDns -Credential (Get-Credential
PPSCU\Administrator) -DomainName “ppscu.com”

Once all tests have been completed successfully, execute the following command to add your new DC. Note that you’ll have to change the parameters values according to your needs:

Import-Module ADDSDeployment
Install-ADDSDomainController ‘
-NoGlobalCatalog:$false ‘
-CreateDnsDelegation:$false ‘
-Credential (Get-Credential) ‘
-CriticalReplicationOnly:$false ‘
-DatabasePath “C:\Windows\NTDS” ‘
-DomainName “ppscu.com” ‘
-InstallDns:$true ‘
-LogPath “C:\Windows\NTDS” ‘
-NoRebootOnCompletion:$false ‘
-SiteName “ppscu.com” ‘
-SysvolPath “C:\Windows\SYSVOL” ‘

To uninstall a DC from a domain, use the Test-ADDSDomainControllerUninstallation and Uninstall-ADDSDomainController cmdlets.
That’s about it for this article folks, hope you will enjoy it. Have a great day!

Configuring NXlog with python

Hello folks,
I’ve finally started working with python for one of our new automatization systems, saltstack. I’ve been experimenting with saltstack recently so I don’t have much experience in this technology. Anyway, I’ve created a script that allows you to configure a log aggregation server (such as Graylog or Flume) on your NXlog client. The script verifies if a hostname or IP address is already configured using a regex formula and if a configuration is not found, allows you to configure the server:

import re
import logging
import subprocess

logger = logging.getLogger(__name__)

def checkconf():
    k = 0
    file = ‘C:\\Program Files (x86)\\nxlog\\conf\\nxlog.conf’
    for line in f:
        if re.match(“^\s*Host\s*([a-z]|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})”, line):
            k = 1
    if k == 1:
        return True
        return False

def set(flumeip=”″):
    configfile = ‘C:\\Program Files (x86)\\nxlog\\conf\\nxlog.conf’
    oldpattern = “Host “
    newpattern = “Host ” + flumeip

    if checkconf() == True:
        logger.info(“Nxlog configuration already found, skipping”)
        f = open(configfile,’r’)
        filedata = f.read()
        newdata = filedata.replace(oldpattern,newpattern)
        f = open(configfile,’w’)
        subprocess.call(‘net stop “nxlog”‘)
        logger.info(“NXlog service Stopped”)
        subprocess.call(‘net start “nxlog”‘)
        logger.info(“NXlog service Started”)
        logger.info(“IP configured for the NXlog client”)
        return True

checkconf() function verifies if the server is already configured and returns either True or False if a match is found or not.
set() function checks the returned value of checkconf() and then either skips the configuration if a match is found or adds the IP/hostname and then restarts the NXlog service.
That’s about all for this article, if you have any misunderstandings don’t hesitate to post a comment in my dedicated section.

Use Powershell to get specific events

Although event viewer offers an easy way to visualize server events, there are situations in which there are too many events to extract the needed information. Powershell can be used to get specific event logs from any machine. If you need to retrieve event logs from System that contain a particular pattern, you can use the following command:

Get-EventLog System -Message “*Driver Management*” | Format-List
Powershell scripting
You can also retrieve events after a certain date from a specific event log location:
$date= get-date 5/02/2014
get-eventlog -LogName System -Source “Microsoft-Windows-Kernel-General” -entrytype Information -after $date
Retrieve event logs using Powershell
The following command retrieves logs from System that have the Microsoft-Windows-Kernel-General source and 11 eventID:
get-eventlog -log System -source “Microsoft-Windows-Kernel-General” | where {$_.eventID -eq 11} | Format-List
Get event longs with Powershell

Display last boot time with Powershell

To remotely find out the last boot time from multiple machines at the same time use the following script:

1..8 | % {$i=”{0:0}” -f $_;$server=”server$i”; invoke-command -computername $server -scriptblock { Get-WmiObject win32_operatingsystem | select csname,@{LABEL=’LastBootUpTime’;EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}}}
Note that the script uses the server$i pattern to find out the last boot time of 8 servers at the same time.
Alternatively you can use one of the following commands on a single server:
(Get-CimInstance Win32_operatingSystem).lastbootuptime
Powershell last boot time

systeminfo | grep “System”

Powershell systeminfo command

net statistics server

Powershell net statistics server command

wmic os get LastBootUpTime

Last Boot Up Time Powershell

(Get-Date) – ([timespan]::FromMilliseconds([Math]::Abs([Environment]::TickCount)))

Get last boot up time with Powershell

Note that you can use the above command in an invoke-command statement to remotely find out the last boot time, just like in the following example:
invoke-command cmdlet
There are a lot of other methods in which you can achieve similar results, please feel free to post a comment with other commands that can be used.

Easy way to interact with several servers remotely using Powershell

Easy way to interact with several servers remotely using Powershell.
The following lines restart the first 10 servers from a server farm that are using similar naming convention:

1..10 | % {$i=”{0:0}” -f $_;$server = “srv-prod$i”; invoke-command -computername $server -scriptblock { shutdown /r /t 0 }}
1..10 | % {$i=”{0:0}” -f $_;$server = “srv-dev$i”; invoke-command -computername $server -scriptblock { shutdown /r /t 0 }}
1..10 | % {$i=”{0:0}” -f $_;$server = “srv-cert$i”; invoke-command -computername $server -scriptblock { shutdown /r /t 0 }}

The following lines disable a scheduled task (ScheduledTask1 and ScheduledTask2) from the first 10 servers in prod and dev while enabling ScheduledTask3 on cert environment:

1..10 | % {$i=”{0:0}” -f $_;$server = “srv-prod$i“; invoke-command –computerName $server -scriptblock { schtasks /Change /TN ScheduledTask1 /Disable }}
1..10 | % {$i=”{0:0}” -f $_;$server = “srv-dev$i“; invoke-command –computerName $server -scriptblock { schtasks /Change /TN ScheduledTask2 /Disable }}
1..10 | % {$i=”{0:0}” -f $_;$server = “srv-cert$i“; invoke-command –computerName $server -scriptblock { schtasks /Change /TN ScheduledTask3 /Enable }}
The following script retrieves the up-time in seconds of a specific service (in this case Netlogon). The script verifies the service state on several machines at the same time:
PS C:\Users\dan.popescu> 1..10 | % {$i=”{0:0}” -f $_;$server = “srv$i”; invoke-command -computername $server -scriptblock {$services = gwmi -class win32_service | ? {$_.name -like “Netlogon”};$hostname = “$env:computername.$env:userdnsdomain”.ToLower();write-host $hostname;foreach ($service in $services){$uptime = “{0:N2}” -f ((get-date) – (Get-Process -Id $service.processId ).starttime).totalhours; $info = @{Service = $Service.name; Uptime = $uptime};$results = New-Object -TypeName PSObject -Property $info; write-host $results}}}
If you cannot run these commands remotely it means that the Windows Remote management service does not run on the target machine. Open a Powershell prompt and type winrm quickconfig and follow the on-screen instructions. Once the service is configured, you will be able to run the scripts:
Windows Remote management service

How to use Powershell to import Server certificates

The following script is used to import a .pfx certificate to the local machine store on a Windows Server:

$servers = Get-Content “servers.txt”
$cert = Get-ChildItem | Where-Object { $_.Extension -eq “.pfx” }
$certpass = “sp8lp/Mih!tbsyc”

$WorkingCert = Get-ChildItem CERT:\LocalMachine\My | where {$_.Subject -match $cert} | select -first 1
$TPrint = $WorkingCert.Thumbprint
$certpath = “Cert:\localmachine\My\” + $TPrint

foreach ($s in $servers)

if (Test-Path -Path $certpath )
write-host “Certificate $cert already exists on $s”
Import-PfxCertificate -FilePath $cert -certstorelocation Cert:\localmachine\My -Password (ConvertTo-SecureString -String $certpass -AsPlainText -Force)
Start-Sleep -Seconds 2

if (!(Test-Path -Path $certpath))
write-host “Certificate $cert imported successfully on $s”
Write-Host “Certificate $cert not imported successfully on $s”