Tag Archives: Microsoft

Ping computers via Powershell

We have all used ping.exe from a command line at some point for quickly resolving computer host names to an IP address. I created a Powershell script whilst onsite with a client last week to provide the same functionality. Using Active Directory as a data source to obtain all computer accounts which were enabled. Then utilizing the test-computer cmdlet via Powershell to check if the computers were online.

The output is then saved into a nice csv file which can be easily read in Excel.

There are a few freeware tools such as Angry IP scanner or Advanced IP scanner that can do something similar.

Initial code is below and available via GITHUB [davidmcisaac/Powershellpub].

Active Directory powershell module is required to be installed for script to execute.

<#Created by DM 050517 Resolve_ComputerName_2_IP.ps1 #>
$comp =@();$rep =@();$cp =@()
$IPNull = "N/A"
$PingSuccess ="Online"
$PingnonSuccess ="Offline"
$comp = Get-ADComputer -Filter * |Where-Object {$_.enabled -eq $true}|select DNSHostName
foreach ($cp in $comp)
    {#Loop through each computer found
        $t= Test-Connection -ComputerName $cp.DNSHostName -Count 1 -ErrorAction SilentlyContinue -ErrorVariable CatchError
        if ([string]::IsNullOrEmpty($catcherror))
            {#Test Connection received reply. Write IP to csv
            $rep += $t|select @{Name="Computer";exp={[string]$_.Address}},IPv4Address,ipv6address,@{Name="Status";exp={[string]$PingSuccess}}
            {#Write error to csv
            $rep += $cp|select @{Name="Computer";exp={$cp.DNSHostName}},@{Name="IPv4Address";exp={[string]$IPNull}},@{Name="IPv6Address";exp={[string]$IPNull}},@{Name="Status";exp={[string]$PingnonSuccess}}
$rep|export-csv -NoTypeInformation C:\computer_2_ip_report.csv

Plan to make a few changes in the future, to account for larger environment where filtering by Organisation Unit would be useful

Clear Exchange 2013 IIS Logs

Something I’ve been working on for a while is a script to clear up all those Exchange IIS logs which are generated through time.

Why are these logs not recycled after a period of time, well for good reason in most cases is to assist with troubleshooting when something goes wrong.

Anyhow, unlike logs such as the Exchange transport log these; which are recycled after they reach a certain size. The IIS logs don’t clear down automatically.

To help clear down disk space the following script can be used. Any IIS logs older than 30 days located in the “Exchange Back end” WWW will be purged.

Download this file save as ps1 and run as administrator on your Exchange servers. I have tested this on Exchange 2013 SP1 CU6 servers.

As always please test on non-production/test servers first to check that this will work with your own environment and have a solid backup of Exchange.

<# Created by DM 151216 
got date info from here https://technet.microsoft.com/en-us/library/ff730960.aspx #>

Write-host "Starting script"
$Retain_Logs =30
$TodaysDate = Get-Date
$ExchangeWWW = Get-Website -Name "Exchange Back End"
$ExchangeIISLog = $ExchangeWWW.logFile.directory
$LogFilesDeleted = "C:\temp\IISlogsDeleted_$(get-date -f dd-MM-yy).txt"
$DeleteOlderThan = $TodaysDate.AddDays(-$Retain_Logs)

if ($ExchangeIISLog -cge "%SystemDrive%")
            $newpath = $ExchangeIISLog -replace "%SystemDrive%","C:"
            $direction = "1"
        Write-host "IIS Log folder for Exchange located here $newpath"
            $direction = "2"
            Write-host "IIS Log folder for Exchange located here $ExchangeIISLog"

##Select the right path
switch ($direction)
        ##get list of files to delete from new path
            $LogsToDelete = Get-ChildItem $newpath -Include *.log -Recurse | Where {$_.LastWriteTime -le "$DeleteOlderThan"}
            add-content $LogFilesDeleted "Starting to delete IIS Logs files located in $IISLogsPath @ $TodaysDate" 
            add-content $LogFilesDeleted "------------------------------------------------------------------------"
        ##get list of files to delete from orignal    
            $LogsToDelete = Get-ChildItem $ExchangeIISLog -Include *.log -Recurse | Where {$_.LastWriteTime -le "$DeleteOlderThan"}
            add-content $LogFilesDeleted "Starting to delete IIS Logs files located in $IISLogsPath @ $TodaysDate" 
            add-content $LogFilesDeleted "------------------------------------------------------------------------"
#Loop through each file older than value set in $Retain_Logs and record success
Write-Host "Starting to clear Logs"
foreach ($File in $LogsToDelete)
        Remove-Item $File -ea SilentlyContinue
        $filestatus = Test-path $File    
        if ($filestatus -eq $True)
            add-content $LogFilesDeleted "Failed to delete $file"
        elseif ($filestatus -eq $False)
            add-content $LogFilesDeleted "Successfully deleted $file"
add-content $LogFilesDeleted "------------------------------------------------------------------------"
add-content $LogFilesDeleted "Finished deleting IIS Logs files located in $IISLogsPath @ $TodaysDate" 
add-content $LogFilesDeleted "------------------------------------------------------------------------"
Write-Host "Check $LogFilesDeleted for list of files deleted successfully and any errors"  

Script output
script execution



Sample output

Log file output

Log file output

Remove Windows 10 built in apps

A bunch of Windows 10 updates ran on my laptop yesterday and decided to re-install windows built in apps that I previously uninstalled.

The offending update seemed to be KB 3124263 Cumulative Update for Windows 10 Version 1511: January 12, 2016 

Wrote a wee powershell script to remove the apps I didn’t want, which will no doubt reappear sometime in the future.

The list of apps to uninstall should be saved in a file called applist.txt in C:\temp\ and the below powershell script can be saved as PS1 script and run as administrator.

<#Created by DM 180915
copy applist.txt file to C:\temp\ 
Additional apps can be uninstalled if required and add name to applist.txt. 
To find list of apps run the following command Get-AppxPackage|ft Name|out-file C:\temp\all_applist.txt 
Execution policy will have to be set to unrestricted before running script Open Powershell and run as Administrator Execute following command Set-ExecutionPolicy -ExecutionPolicy Unrestricted#>
$applist = get-content -path C:\temp\applist.txt
Foreach ($i in $applist)
Get-AppxPackage $i | Remove-AppxPackage
The following list can be copied into notepad and saved as applist.txt
Please note you don't need to uninstall these all apps, in this instance these are the ones I didn't required.


Create DFS Replication Healthcheck email report

DFS-R is the replication component of the Distributed File System (DFS). Windows Server 2012R2 introduces powershell cmdlets that can be used for management rather thsn relying on the old dfsutil commands.

Some of the common issues with DFS-R are files not replicating due to network latency or connectivity issues. The knock on effect leads to staging folders becoming full leading and file replication stopping.

If you dont have SCOM or other monitoring tools at hand to monitor DFS-R. The code below can be saved as a ps1 poweshell script and scheduled to run on one of the DFS-R servers. The script generates a healthcheck report and sends the report by email.

Amend the variables at the start to define replication group and email server/recipent/sender details.

Additonal DFS servers can be specified by extending the Write-DfsrHealthReport command by adding the “$DFSservers[..]” variable with array index value.

$DFSGroupName ="Enter DFS Replication group name here"
$DFSservers = (Get-DfsrMembership -GroupName $DFSGroupName |select -ExpandProperty computername)
$foldernamedate = $(get-date -f dd-MM-yyyy)
$source = "C:\DFSReportsImport\"
$destination = "C:\DFSReportsExport\$foldernamedate\DFS_Report.zip"
$emailServer = "mysmtpserver.example.com"
$sender = "sender@example.com"
$recipients = "recipient@example.com"
mkdir c:\DFSReportsImport\$foldernamedate
mkdir c:\DFSReportsExport\$foldernamedate
Write-DfsrHealthReport -GroupName $DFSGroupName -ReferenceComputerName $DFSservers[0] -MemberComputerName $DFSservers[0], $DFSservers[1] -CountFiles -Path c:\DFSReportsImport\$foldernamedate\

Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
remove-item -path c:\DFSReportsImport\$foldernamedate -Recurse -Force
send-mailmessage -from $sender -to $recipients -subject "DFS Report $foldernamedate" -Body "DFS Report generated from $DFSservers[0]" -smtpserver $EmailServer -attachments "C:\DFSReportsExport\$foldernamedate\DFS_Report.zip"
remove-item -path c:\DFSReportsExport\$foldernamedate -Recurse -Force

Microsoft Hyper-V 2012 R2 patches and hotfixes

A key update viewed in many eyes for any Hyper-V environment.

Released back in April 2015, a new security vulnerability has been discovered which could result in a denial of service to a virtual machine running in Hyper-V. Even thou this may not impact other running virtual machines this could affect manageability of the underlying hosts.

The following Microsoft KB provides further info and patch information. https://support.microsoft.com/en-us/kb/3047234

As per best practice, it best to ensure your Hyper-V environment’s have been fully patched with all the latest hot fixes and patches. The following articles should be used as guidance on what to install.



How many VM’s are running in Hyper-V cluster?

Common question asked by many admins, How many virtual machines are running in my Hyper-V cluster? This quick one line powershell cmd queries the cluster object for all VM’s and gathers some key usage configuration information and exports to CSV for easy reading.

Run this command on any Hyper-V node in the cluster. Tested on Microsoft Windows Server 2012 R2

Get-ClusterGroup | ? {$_.GroupType -eq 'VirtualMachine' } | Get-VM | ft VMName, State, ProcessorCount,@{label="MemoryStartup(GB)";Expression={$_.MemoryStartup/1024/1024}},DynamicMemoryEnabled |out-file C:\hvlist.csv