Wednesday, 11 January 2017

Impact of Leap Second

What is Leap Second:


A leap second is a one-second adjustment that was added to Coordinated Universal Time (UTC) after midnight on 31st Dec 2016
Leap seconds are a periodic one-second adjustment of Coordinated Universal Time(UTC) in order to keep a system's time of day close to the mean solar time. However, the Earth's rotation speed varies in response to climatic and geological events, and due to this, UTC leap seconds are irregularly spaced and unpredictable. This article seeks to provide information regarding the leap seconds, along with addressing.

Impact of Leap Second:


Leap seconds help to keep clocks aligned with Earth’s rotation, which can vary due to geologic and even weather conditions. But an extra second can wreak havoc with applications and services that depend on systems being tightly synchronized. Time synchronization is critical for keeping replica up to date, determining which data-affecting operation happened last, and correctly reporting the order of searches and clicks, the company says.

Ordinary operating systems can’t accommodate a minute that’s 61 seconds long, so some organizations have used special-case workarounds for the extra second. But sometimes these methods raise issues, like what happens to write operations that take place during that second.

Solution:



Since the leap second was inserted by IERS (International Earth Rotation Services) at the moment. We all need to check with the respective application vendor about this leap second whether they have a fix to align with NTP. Obviously, we must install the fix if your application is not synching with Network time protocol through internet.  Keep your eye on scheduled jobs which used to synch with external third party API’s 

Tuesday, 29 March 2016

Automation of resource pool allocation

Operations teams are struggling to manage the resource pool. We have been either migrating or decommissioning lots of VM's everyday. We need to adjust the resource pool memory and CPU after every migration and decommission of VM's. 

I have written the below powerCLI script to automate this task. This script will identify only discrepancy resource pool by comparing the resource pool memory and CPU share values with vCPU and memory count of VM's  inside the resource pool.

By this way you can use an unused memory and CPU shares to another resources. 

I have asked you to type the details of $VIserver, $SMTPserver, $mailFrom and $mailTo in the below script. Please add the requested details before running. You will get the discrepancy report of resource pool to  your given "$mailTo" address after the completion of running script.  



#######################################################

# Created By = Sankar Munirathinam


########################################################


[string]$head = @'
<style type = "text/css">
p {font-family: Calibri;}
h1,h2,h3 {font-family: Calibri;}
ol {font-family: Calibri;}
li {font-family: Calibri;}
table {width: 50%;}
table, th, td {border: 1px solid black;border-collapse: collapse; font-size:10pt}
th {background-color:Orange; color:black}
td, th {padding: 3px; text-align:center;}
</style>
'@



$VIserver = "Type your datacenter here"

Connect-VIserver $VIserver
 $report = @()
 
 $datacenters = get-datacenter 

 
 foreach($datacenter in $datacenters)
 {
 
 $clusters = get-datacenter $datacenter | get-cluster
 
 foreach($cluster in $clusters)
 {
 $Resourcepool = get-cluster $cluster | Get-ResourcePool | select -ExpandProperty Name
 
 foreach($resource in $Resourcepool)
 {
 
  $numvcpus = 0
    $totalmemory = 0
    $numvms = 0
 $pool = get-resourcepool $resource -location $cluster
  $cpuShares = $pool.Numcpushares
$MemoryShares = $pool.Nummemshares
 
 [int]$ClusterCPUShares = $cpuShares/1000
 [int]$clusterMemShares = $MemoryShares/1000
 
$VMs = $pool | get-vm

 
 foreach($vm in $VMs)
 {
    #count number of CPUs
        $NumvCPUs += ($VM).NumCpu
        #count how much memory is allocated
        $TotalMemory += ($vm).MemoryGB
        #count number of VMs
        $NumVMs += 1
 
 }

  if((($numvcpus -lt $ClusterCPUShares) -or ($numvcpus -gt $ClusterCPUShares)) -or (($totalmemory -lt $clusterMemShares) -or ($totalmemory -gt $clusterMemShares)))
 {
  $totalmemory = "{0:N2}" -f $totalmemory
 
 $object = New-Object -TypeName Psobject
 $object | Add-Member -MemberType NoteProperty -Name "DataCenter" -Value $datacenter
 
$object | Add-Member -MemberType NoteProperty -Name "Cluster" -Value $cluster
$object | Add-Member -MemberType NoteProperty -Name "ResourcePool" -Value $resource



Write-Host "--------------------------------------------"
Write-Host "Cluster Name : $cluster" -ForegroundColor White
Write-Host "Resource Pool Name : $resource " -ForegroundColor White
Write-Host "Resource Pool CPU Shares : $cpushares" -ForegroundColor White
Write-Host "Total VM's vCPU Count : $numvcpus" -ForegroundColor White
Write-Host "--------------------------------------------"

$object | Add-Member -MemberType NoteProperty -Name "ResourcePool Cpu Shares" -Value $cpuShares
$object | Add-Member -MemberType NoteProperty -Name "Total VM's vCpu Count" -Value $numvcpus

Write-Host "--------------------------------------------"
Write-Host "Cluster Name : $cluster" -ForegroundColor green
Write-Host "Resource Pool Name : $pool" -ForegroundColor green
Write-Host "Resource Pool Memory Shares : $Memoryshares" -ForegroundColor green
Write-Host "Total VM's Memory : $TotalMemory GB" -ForegroundColor green
Write-Host "--------------------------------------------"
$object | Add-Member -MemberType NoteProperty -Name "ResourcePool Memory Shares" -Value $MemoryShares
$object | Add-Member -MemberType NoteProperty -Name "Total VM's Memory in GB" -Value $totalmemory
$report += $object
}

}
}
}


$final = $report | ConvertTo-Html -Head $head


$SMTPServer = "Type your smtp address"
$mailto = ""
$mailfrom = ""
$subject = "Report of ResourcePool $VIserver"

[string]$Message = @"
<!DOCTYPE html>
<html>
<body style = "font-family: Calibri"; font-size:8px>
<font size = "3">

<p><center>$final</center></p>
<p>Regards</p>
<p><strong>Operation Team</strong></p>
</font>
</body>
</html>
"@

send-mailmessage -to $mailto -Subject $subject  -from $mailfrom  -smtpserver $SMTPServer -body $Message -BodyAsHtml
 ##############################################




Friday, 13 March 2015

Message Tracking Log for Distribution Group

Are you wondering how to take the transaction logs for distribution group?

I have written an exchange powershell to take the logs of distribution group which are receiving the mails from external network. We need to specify the event id as Expand as mentioned in the below script.

When you run Get-MessageTrackingLog on the hub server you could pull only the logs which are being sent the server where you are going to run this tracking log cmdlet.

To get an accurate log report we should pull the transaction logs from all the hub transport server installed in the organisation

How do you pull the tracking logs if you have multiple hub transport server?

$Servers = Get-ExchangeServer | where { $_.isHubTransportServer -eq $true -or $_.isMailboxServer -eq $true }

We are saving all the hub server details in the $server variable to get the logs from all the hub server installed in the organization

You just wanted to change the start date and end date based on the requirement. if you wanted to pull the logs for last 15 days you need to align with start and date in the below script.


###############Get-Messagetrackinglog from all installed hub servers######################

$Servers = Get-ExchangeServer | where { $_.isHubTransportServer -eq $true -or $_.isMailboxServer -eq $true }

$report = @()

try {

$logs = $servers | ForEach-Object { Get-MessageTrackingLog -EA SilentlyContinue -ResultSize Unlimited -Server $_.Name -Start (Get-Date).AddDays(-30) -End (Get-Date) -EventID Expand | select sender, RelatedRecipientAddress}


foreach ($log in $logs)
{

$MSGSender = $log.Sender
$DG = $log.RelatedRecipientAddress


$Obj = New-Object PSObject
$Obj | Add-Member -MemberType NoteProperty -Name "Sender" -Value $MSGSender
$Obj | Add-Member -MemberType NoteProperty  -Name"DistributionGroup" -Value $DG
$report += $Obj

}

} catch {

} finally {

$report | Export-Csv  C:\Users\sankar\Desktop\DG-MessageTracking.CSV

$report | Out-GridView
}

#####################################################################

Friday, 12 September 2014

Advanced Search Query

Use the Search-Mailbox cmdlet for the following scenarios

1. Deleting the meetings from the end user calendar.

2. Delete the Mail from the end user Mailbox

3. Copy the mails from one mailbox to other mailbox

4. Delete the meetings made by terminated users

5. Delete the meeting from Resource mailbox


Use the below cmdlet for taking the backup and see what emails you are going to recall. So if anything goes wrong you could use this backed up emails. 

search-mailbox -searchquery "kind:meetings from:$recipient" -targetmailbox $yourmailid -targetfolder "REPORT" 

Check $yourmailid to see what meetings you are going to delete. If you are ok then go ahead and use delete parameter for deleting the meeting

search-mailbox -searchquery "kind:meetings from:$recipient"  -deletecontent -force

Use the below cmdlet for copying emails from one mailbox to another mailbox


Search-Mailbox mailid@domain.com -SearchQuery "Kind:email AND sent: 06/01/14..09/16/14" -TargetMailbox sankar@domain.com  -TargetFolder Backup

Monday, 7 July 2014

Powershell Error Handling

There are two common parameters for error handling.

-Erroraction and -Errorvariable

To know about common parameters:

Get-Help -Name about_CommonParameters;

if an error occurs while running the script it will save that error in automatic variable

Automatic variable : $error

Error handling is very important when you write scripts. You should know what is happening when the script is running. you could catch errors if the error occurs while running the script

Syntax:

Try
{

}
catch
{

$_

}

Finally

{

}

Put your scripts in Try block and Catch block would catch the errors while running the scripts.

Monday, 23 June 2014

Remote Powershell



Use remote powershell if you dont have installed Exchange Management tool.

Use the below script to log in through remote powershell

$username = 'domain\username'
$password = '**************'
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))

$session = New-PSSession -Authentication basic -Credential $cred -ConnectionUri https://*****.******.com/PowerShell -ConfigurationName Microsoft.Exchange
Import-PSSession $session

If you want to login to the different machine through remote use the below code

$cred=Get-Credential
$session = New-PSSession -Credential $cred -ComputerName <remote machine>
Enter-PSSession $sessio

To exit the remote session

Exit-PSSession
Remove-PSSession $session

Powershell Execution policy

if the powershell scripts to be allowed to run the scripts on your computer, Use the below execution policy cmdlets

Set-ExecutionPolicy RemoteSigned

Then use the below cmdlet to check the execution policy

Get-ExecutionPolicy




Friday, 9 May 2014

Convert Powershell Script as Executable File

How to convert the Powershell Script as Executable File?

Sometimes we need to run the PS script as an executable file. In this case we could convert the powershell script as an exe file. Then run it on the windows OS. Please pay the attention on the Microsoft .Net Framework while creating the executable file.

1. Install the latest version of PowerGUI Script Editor

2. Write the script on the PowerGUI Script Editor which you want to convert it as EXE file

3. Then Click on "Tools"

4. Then Click on "Compile Script"

5. If you want you can show powershell script on console. Else you could disable that option


Wednesday, 22 January 2014

Disk Usage Information

Program to get Disk usage information 

Use the below script to find the disk usage on windows. This script would be helpful when you want to work on disk utilization tasks such as cleanup process on  disks, Auditing purpose etc,.

Use this script to check the limit of disk utilization. And use Send-Mailmessage to send the alert to the specific person and schedule the script on task scheduler.

function get-DiskUsage {

Get-ChildItem -Recurse -Directory | Select-Object FullName,
@{ Name="Size";
Expression={ ($_ | Get-ChildItem |
Measure-Object -Sum Length).Sum + 0 } }
}

Thursday, 9 January 2014

Make your Computer to speak with Powershell

Use the COM object to make the computer to speak. We could intimate the administrator using this computer speaking feature using powershell when they receive an error. This would be helpful to the scripting developer.

Use the New-Object cmdlet to create the COM object as mentioned in the below screenshot.




.Net Static Method

How to list the static method using Get-Member cmdlet?

Once you know the .net type, we can list the static method using the Get-Member.

[System.Guid]::Newguid()

[Sytem.Guid] -> .Net Type

Newguid() -> .Net Method

Have look at the below screenshot.



If you are in a situation to fetch the local machine timezone, you can use the method as mentioned in the below screenshot.

Wednesday, 13 February 2013

Deleting the Meeting Requests Made by terminated users from all the roommailboxes


Run this script on Exchange server 2010. You could delete the meetings made by terminated users from all the room mailboxes. Ensure that you are running this script only for terminated users. Else script will not run.

Give the required input while running this script.



[void][System.reflection.assembly]::LoadWithPartialName('microsoft.visualbasic')

$recipient=[Microsoft.visualbasic.interaction]::inputbox("Enter the Recipient Name to delete the Meeting requests from all the room mailoxes","name","Sankar_M")


$mailid=[Microsoft.visualbasic.interaction]::inputbox(" Enter your mail id to create a foler called REPORT in your outlook in which you can find the deleted contents","name","Sankar@Domain.com")

if(get-recipient $recipient -warningaction:silentlycontinue)
{
[Microsoft.visualbasic.interaction]::msgbox("Recipient is Existing in Production. Ensure that You are running this program for Terminated User")

Write-host "Recipient is Existing in Production. Ensure that You are running this program for Terminated User"

break
}
else
{

[Microsoft.visualbasic.interaction]::msgbox("Hello, Please Wait Until the Program completes")

Write-Progress -Activity "Preparing" -Status "Retrieving Roommailbox list" -PercentComplete 0
$rooms=get-mailbox -recipienttypedetails roommailbox -resultsize unlimited -warningaction:silentlycontinue| where {$_.name -notlike "*test*"}

$count=$rooms.count




foreach($room in $rooms)

{

$i=$i+1
$percentage=$i/$count*100


Write-Progress -Activity "Collecting mailbox details" -Status "Processing mailbox $i of $Count - $room" -PercentComplete $percentage


$room | search-mailbox -searchquery "kind:meetings from:$recipient" -targetmailbox $mailid -targetfolder "REPORT" -deletecontent -force
}}

Friday, 7 December 2012

Powershell Help

To get help in Graphical window

C:\> help Get-EventLog -showwindow

Wednesday, 3 October 2012

Powershell Tips

How to change the element of an array?

$array = 1, 2,3, 4, 5

$array.Item(0) = 100

$array

How to sort an array ?

Use the static sort method from array class

$a = 1,3, 4,2

[array]::sort($a)



How to display Loaded and available Modules in Powershell?

Use the Get-Module cmdlet to display loaded

To see the path of the module

Get-Module | select path

To list the modules,

Get-Module -Listavailable

How to open a pipeline results in editor?

 dir | Out-File result.txt; notepad result.txt


How to list all parameters of parametersets?

PS C:\Users\sankar> (Get-Command Get-Date).parametersets | foreach {$_.parameters} | foreach {$_.name}



How to check the folder counts ?

We can find the number of files available on desktop this way


PS C:\Users\sankar\Desktop> @(get-childitem -name *).count
35

In case if you want to exclude some files when counting.

 @(Get-ChildItem -exclude *.txt).count

How to exclude the files from displaying?

Get-ChildItem -exclude *.txt

How to get all the child items from the container that has child items?

We should use  -Recurse Parameter if we need to get all the child items from the container

get-childitem -Recurse $env:USERPROFILE\desktop

we can use -filter if we want to filter with some specified extension file like *.txt , *.docx etc

get-childitem -Recurse $env:USERPROFILE\desktop -filter *.txt

How to check the version of Powershell and .Net Framework?


PS C:\Users\sankar\Desktop> $PSVersionTable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.5456
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

To check version for .Net Framework


PS C:\Windows\Microsoft.NET\Framework> dir


    Directory: C:\Windows\Microsoft.NET\Framework


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----          3/3/2012   8:27 AM            v1.0.3705
d----         7/13/2009  10:20 PM            v1.1.4322
d----          8/4/2012   9:22 AM            v2.0.50727
d----         2/17/2011   9:25 PM            v3.0
d----          3/3/2012   8:27 AM            v3.5
-a---         11/4/2010   6:57 PM      86864 NETFXSBS10.exe
-a---          3/3/2012   2:50 AM      41392 netfxsbs12.hkf
-a---         6/10/2009   4:22 PM      13648 sbscmp10.dll
-a---         6/10/2009   4:22 PM      13648 sbscmp20_mscorwks.dll
-a---         6/10/2009   4:22 PM      13648 sbscmp20_perfcounter.dll
-a---         6/10/2009   4:22 PM      11104 sbs_diasymreader.dll
-a---         6/10/2009   4:22 PM      11088 sbs_iehost.dll
-a---         6/10/2009   4:22 PM      11112 sbs_microsoft.jscript.dll
-a---         6/10/2009   4:22 PM      11656 sbs_microsoft.vsa.vb.codedomprocessor.dll
-a---         6/10/2009   4:22 PM      11096 sbs_mscordbi.dll
-a---         6/10/2009   4:22 PM      11096 sbs_mscorrc.dll
-a---         6/10/2009   4:22 PM      11096 sbs_mscorsec.dll
-a---         6/10/2009   4:22 PM      11120 sbs_system.configuration.install.dll
-a---         6/10/2009   4:22 PM      11088 sbs_system.data.dll
-a---         6/10/2009   4:22 PM      11112 sbs_system.enterpriseservices.dll
-a---         6/10/2009   4:22 PM      11080 sbs_VsaVb7rt.dll
-a---         6/10/2009   4:22 PM      11104 sbs_wminet_utils.dll
-a---         6/10/2009   4:22 PM      13648 SharedReg12.dll

To Create New Item Using Powershell

C:\Users\Sankar> New-Item <File Name> -ItemType File


PS C:\Users\sankar\Desktop> 1..5 | %{New-Item
-Name "$_.txt"  -Value (Get-Date).tostring() -ItemType file}

NULL Value and Parameter Type


PS C:\> Get-ChildItem $env:windr | ?{$_.length -eq $null}


    Directory: C:\


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         7/17/2012   2:11 PM            Intel
d----         7/14/2009   8:07 AM            PerfLogs
d-r--        11/12/2012   1:53 PM            Program Files
d----         8/28/2012   2:43 AM            Quarantine
d----         7/18/2012  12:02 AM            source
d-r--        10/17/2012   8:25 PM            Users
d----         12/7/2012   3:50 PM            Windows


function NULLValue
{
  param
  (
    [string]$a = $( throw "Missing: parameter a"),
    $b = $( throw "Missing: parameter b")
  )

  if ($a -eq $null) { Write-Host "a is null" } else { write-Host "a is not null" }
  if ($b -eq $null) { Write-Host "b is null" } else { Write-Host "b is not null" }
}

If I call this function with: NULLValue $null $null

I will get the following result:

a is not null
b is null

How to round the number?

Use static Round method using math Class as mentioned below









Monday, 17 September 2012

How to pull the report to only 500 group ids even if your organisation is having more than 10000 groups?

For example,  you are having more than 2000 groups in your organisation. Now you are in a situation to get the details of owners name of 500 groups only. How you will do?

We can use Get-content to get the data from the text file with the path name mentioned and do the pipeline to the command like below


[PS] C:\Users\sankar\desktop>$list = Get-Content .\groupid.txt | ?{$_ -ne ""} |%{$_.Trim()}
[PS] C:\Users\sankar\desktop>$list.Count
547
[PS] C:\Users\sankar\desktop>$list | % {Get-DistributionGroup -Identity $_ -ResultSize Unlimited | Select-
Object Name,@{L="ManagedBy";E={$_.ManagedBy}}} | Export-Csv -NoTypeInformation grouplistfromtext.csv


Friday, 7 September 2012

Find out No longer Existing Group

This exchange cmdlet would be helpful if you are dong auditing in your organization. You could filter no longer users details using last log on time.


Get-MailboxStatistics -Server <ServerIdParameter> | Sort-Object LastLogonTime Descending

Wednesday, 5 September 2012

How to get the details of email addresses Using Powershell

We can use the below exchange cmdlet to pull the details of email addresses. Then export it to the CSV file using Export-CSV cmdlet. 

Get-Mailbox -resultsize unlimited | Select Name, @{Name=’EmailAddresses’;Expression={[string]::join(";", ($_.EmailAddresses))}} | Export-CSV EmailAddress.csv

Tuesday, 21 August 2012

How to set the forwarding SMTP Address through Powershell

You cannot set the Fowarding SMTP Address through EMC. But we can set it through EMC

If you want to forward the mails from local mailbox to outside the organization, we should follow the below steps in powershell

1. DeliverToMailboxAndForward:

set-mailbox -DeliverToMailboxAndForward $true

2. Forwarding Address

set-mailbox intials -forwardingaddress Username

3. ForwardingSMTPAddress

set-mailbox intials -forwardingsmtpaddress email@domain.com

Thursday, 9 August 2012

Get Large Mailboxes from exchange

Using the below script we can get the large mailboes report from the exchange 2007


Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Where {$_.TotalItemSize -gt 500MB} `
| Select-Object DisplayName, ItemCount, TotalItemSize, TotalDeletedItemSize, StorageLimitStatus `
| Export-Csv "BigMailbox$(Get-Date -f 'yyyyMMdd').csv" -NoType

Friday, 3 August 2012

How to set the pimary email address and making the existing one as secondary email address

Here is the script to set the primary email address and making the existing as the secondary. if we do so, if anyone sending a mail to old email address, we can avoid the NDR

Import-Csv d:\alias.csv | Foreach-object { Set-Mailbox $_.alias -emailaddresspolicyenabled $false -PrimarySmtpAddress $_.SmtpAddress }


how to change the primary smtp using login id?

$Users = Import-CSV c:\myfile.csv
ForEach($User in $Users)
{
write-host "Processing $($User.loginid)"
set-mailbox -identity $user.loginid -PrimarySmtpAddress $user.primaryemail -EmailAddressPolicyEnabled $false
}

Regards,
Sankar M

Thursday, 2 August 2012

How to import file using Powershell

How to Import the file using powershell

Declare the variable to load CSV file.

C:\temp>$V = import-csv c:\reprot.txt


If you want to see the ouput in console , just type the $v variable, you will be shown with  content loaded into the text file

Then we have run the script line by line, so we must use foreach alias

$v | foreach {
If
{
$_.hide –eq “yes”
}
{
Write-host  “ $_.name will be set as $true”
}