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


How to sort an array ?

Use the static sort method from array class

$a = 1,3, 4,2


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 {$}

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

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}
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
-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
    [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
[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

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

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 {
$_.hide –eq “yes”
Write-host  “ $ will be set as $true”

Monday, 30 July 2012

Program for Helpdesk people to retrive the information of maiboxes

How to retrieve the Mailbox info from the particular mailbox server

Using the below program, we can extract the details of mailbox information from the specified exchange server. Even if you type the mailbox name instead of typing exchange server name, you will get the mailbox info output. This program is very useful to Helpdesk people to retrieve the info of mailbox information and mailbox server information.
 Please Click Here if you want to know about (if else) statement
If ($arg[0] –eq ‘server’)
Write-Host “Retrieving info from the server ” $arg[1]
Get-exchangeserver –server $arg[1] | select name, FQDN, ServerRole, Edition | FL
Write-host “ The mailboxes Hosted on : “ $arg[1]
Get-mailbox –server $arg[1] | select name, severname, database
Write-host “ Retrieving information of maibox “ $arg[0]
Get-mailbox $arg[0] |select name, servername, database
Copy the program in notepad and save it as mailboxinfo.ps1

C:\temp>.\mailboxinfo.ps1 –server exchageserver1
Retrieving info from the server  exchageserver1
Server Role:
The mailboxes Hosted on : exchageserver1

Sankar M 

Wednesday, 25 July 2012

Exchange Server Cmdlets

1. quick shortcut to get all the commands

Get-Command | Format-List Definition

2. How to move mailbox

Get-Mailbox -Server SRV1 | Move-Mailbox -TargetDatabase SRV2

3. To get a list of all users on an Exchange server who are not Unified Messaging-enabled type, 

Get-UmMailbox | ForEach { If($_.UmEnabled -Eq $False){$_.Name}} 

4. To display the user’s alias formatted in a table together with the user’s Exchange server name and telephone extension, type:

Get-UmMailbox | Format-Table ServerName,@{e={$_.SamAccountName};Label=”User Alias”},@{Expression=”Extensions”;Label=”Telephone numbers

5. If you want to test all IP Block List providers, you just have to pipe the Get-IpBlockListProvider cmdlet to the Test-IpBlockListProvider

Get-IpBlockListProvider | Test-IpBlockListProvider -IpAddress 192.168.0.

6. Before you remove an object by using the Remove verb, use the WhatIf parameter to verify the results are what you expect.

7. Get all Win32 WMI information, such as perfmon counters and local computer configurations. For example,

Get-WMIObject Win32_PerfRawData_PerfOS_Memory 

8. You can configure real-time block list (RBL) providers with the Exchange Management Shell by running the following two commands:

Set-IPBlockListProvidersConfig -Enabled $True -ExternalMailEnabled $True
And then

Add-IPBlockListProvider -Name -LookupDomain -AnyMatch $True 

9. Access the event log from the Exchange Management Shell. To retrieve the whole event log,

Get-EventLog Application | Format-List

To retrieve all Exchange-related events

Get-EventLog Application | Where { $_.Source -Ilike “*Exchange*” } 

10. you can use wildcard characters to retrieve all properties that matches the part of the name that you specify:

Get-Mailbox | Format-Table Name,*SMTP* 

11. Do you want to configure a group of objects that have similar identities? You can use a wildcard characters with the Identity parameter when you use a Get cmdlet and pipe the output to a Set cmdlet. Type:

Get-Mailbox *John* | Set-Mailbox -ProhibitSendQuota 100MB

This command matches all mailboxes with the name “John” in the mailbox’s identity and set the ProhibitSendQuota parameter to 100MB. 

Get-MailboxDatabase “Normal” | Get-Mailbox | Set-Mailbox -ProhibitSendQuota 100MB

This command retrieves all the mailboxes that reside in the “Normal” mailbox database and sets their ProhibitSendQuota value to 301MB

12. Use Test-MapiConnectivity to troubleshoot connectivity problems between your users and your servers. Combine Test-MapiConnectivity with a variety of cmdlets to target your specific issue without having to manually dig for the information:

Mailboxes: Get-Mailbox | Test-MapiConnectivity

Mailbox databases: Get-MailboxDatabase | Test-MapiConnectivity

Servers: Get-MailboxServer | Test-MapiConnectivity 

13. Do you want to record exactly what happens when you’re using the Exchange Management Shell? 

Use the Start-Transcript cmdlet.

 Anything that you do after you run this cmdlet will be recorded to a text file that you specify. To stop recording your session, 

use the Stop-Transcript cmdlet.

Notice that the Start-Transcript cmdlet overwrites the destination text file by default. If you want to append your session to an existing file, use the Append parameter:

Start-Transcript c:\MySession.txt -Append 

14. How to check the Exchage server version, server role, site?

Get-ExchangeServer | fl name, edition, serverrole, site

Tuesday, 24 July 2012

Script For Folder Item Count

I have been using the below exchange management command for the folders item count.

Get-Mailbox | Get-MailboxFolderStatistics | Where {$_.ItemsInFolder -gt 5000} | Sort-Object -Property ItemsInFolder -Descending | fl Identity, ItemsInFolder

Since there are different folder item limits for each version of Exchange, I thought it might be beneficial to write a script that could analyze folders on all versions, and determine if they were over their limit. The limits are as follows:


Version                                      Folder Item Count

Exchange 2003                               5,000

Exchange 2007                               20,000

Exchange 2010                               100,000

Sankar M

Monday, 23 July 2012

Script For Folder Count


Using the below script we can dump the list of users and their folder size in exchange server 2010

# script to list the number of folders in each mailbox
$mbx|select Displayname,@{n="FolderIdCount";e={(get-mailboxfolderstatistics -id $_.Identity | select FolderId).count}} | Sort-Object -Property Displayname | export-csv c:\files\results.csv

If you want to know how many items are in every mailbox and if all items in mailbox is more than 500 you can use this below script:

$data = $((get-date).ToString('dd.MM.yyyy'))
Function New-Array {,$args}
$Report = New-Array
$count_max = 500
$mbxs = get-mailbox | select -first 100 -resultsize unlimited
foreach ($mbx in $mbxs){
$mbxstat = get-mailboxstatistics $mbx.SAMAccountName
if ($mbxstat.ItemCount -gt $count_max){
$report_tmp = New-Object System.Object
$report_tmp | Add-Member -type NoteProperty -name DisplayName -value $mbx.DisplayName
$report_tmp | Add-Member -type NoteProperty -name ItemCount -value $mbxstat.ItemCount
$Report += $report_tmp
$Report | ft -auto | Out-String -Width 4096 > d:\scripts\report_count_$data.txt
Send-MailMessage -To -From -Subject "Mailbox items count $data" -SmtpServer youremailserver -Attachments d:\scripts\report_count_$data.txt

Sankar M