Tuesday, November 29, 2011

“Smart Backup” using PowerShell

As a Network Admin I always worry about my backups. I was planning to write a simple script which create a new folder by date and copy the desired files and folder in to it recursively.
so i successfully  able to write a script for it and sharing it with you and I hope it is useful to you too. {or at least for tally administrators they always worried about there data, or we can say they this article contain “How to Automate Tally Backup”
I am running this script on my Tally server:
Script Logic:
  1. Map a Network Drive where you want to save the backup
  2. Create a Folder by using Date as Name
  3. Copy the backup
  4. Create a log file name as “backup_log.txt”
  5. When all some send a email to admin ($to) with backup_log.txt as attachment.
  6. Remove the Map Drive
you can download the script from here : http://dl.dropbox.com/u/17858935/Smart_Backup_Create%20folders_by_Date.zip

Note : change \\T_server\Tally with your folder where you want to take backup.
          Change $source with your source folder which you want to backedup

1: #System Variable for backup Procedure
2:  $date = Get-Date -Format d.MMMM.yyyy
3:  New-PSDrive -Name "Backup" -PSProvider Filesystem -Root "\\T_Server\Tally"
4:  $source = "D:\Tally\Data\"
5:  $destination = "backup:\$date"
6:  $path = test-Path $destination
7: #Email Variables
8:  $smtp = "Exchange-server"
9:  $from = "Tally Backup <tally.backup@xyz.com>"
10:  $to = "Aman Dhally <amandhally@gmail.com>"
11:  $body = "Log File of TALLY bacupk is attached, backup happens on of Date: $date"
12:  $subject = "Backup on $date" 
13: # Backup Process started
14:  if ($path -eq $true) {
15:     write-Host "Directory Already exists"
16:     Remove-PSDrive "Backup"  
17:     } elseif ($path -eq $false) {
18:             cd backup:\
19:             mkdir $date
20:             copy-Item  -Recurse $source -Destination $destination
21:             $backup_log = Dir -Recurse $destination | out-File "$destination\backup_log.txt"
22:             $attachment = "$destination\backup_log.txt"
23: #Send an Email to User 
24:             send-MailMessage -SmtpServer $smtp -From $from -To $to -Subject $subject -Attachments $attachment -Body $body -BodyAsHtml
25:             write-host "Backup Sucessfull"
26:             cd c:\ 
27:  Remove-PSDrive "Backup"  
28:  }
I hope it may be useful to someone :) 
Aman Dhally

Storing Pictures in Active Directory


PowerTip of the Day, from PowerShell.com:

When you need to store a picture into an AD account, the picture will have  to be converted to byte values before it can be stored. Just make sure you adjust the path to the picture you want to store and the LDAP path of the AD object you want the picture to be stored in:


  1: # adjust picture path:
  2: $file = "C:\pic.jpg"
  3: $bild = New-Object system.Drawing.Bitmap($file)
  5: $ms = New-Object IO.MemoryStream
  6: $bild.Save($MS, 'jpeg')
  7: $MS.Flush()
  8: $byte = $MS.ToArray()
  9: # adjust user LDAP path:
 10: $user = New-Object System.DirectoryServices.DirectoryEntry`
 12: ("LDAP://,CN=Users,DC=powershell,DC=local")
 14: $User.Properties["jpegPhoto"].Value = $byte



Thanks to www.PowerShell.com

Monday, November 28, 2011

Finding IP and MAC address


PowerTip of the Day, from PowerShell.com:


Finding IP and MAC address

When you query network adapters with WMI, it is not easy to find the active network card. To find the network card(s) that are currently connected to the network, you can filter based on NetConnectionStatus which needs to be "2" for connected cards. Then you can take the MAC information from the Win32_NetworkAdapter class and the IP address from the Win32_NetworkAdapterConfiguration class and combine both into one custom return object:

PS> Get-WmiObject Win32_NetworkAdapter -Filter 'NetConnectionStatus=2'

ServiceName : NETw5s64

MACAddress : 00:22:FA:D9:E1:50

AdapterType : Ethernet 802.3

DeviceID : 11

Name : Intel(R) WiFi Link 5100 AGN

NetworkAddresses :

Speed : 54000000

This gets you the network hardware but not the network configuration. To get the configuration data for this network card (like its IP address), get the related Win32_NetworkAdapterConfiguration instance:

########### Script Start Here ###########################

function Get-NetworkConfig {

Get-WmiObject Win32_NetworkAdapter -Filter 'NetConnectionStatus=2' |

ForEach-Object {

$result = 1 | Select-Object Name, IP, MAC

$result.Name = $_.Name

$result.MAC = $_.MacAddress

$config = $_.GetRelated('Win32_NetworkAdapterConfiguration')

$result.IP = $config | Select-Object -expand IPAddress




###################### Script end Here #####################


PS> Get-NetworkConfig

Name IP Mac

---- -- ---

Intel(R) WiFi Link 5100... {, fe80::a... 00:22:FA:D9:E1:50


Thanks to www.PowerShell.com

“Script to list all folder of Outlook and total number of emails store in them” using PowerShell



from past few days I tried to writing a script which shows me that how many folders I do have in my Outlook and total number of emails stored on them.

I get only 50% success so far, I am able to see the folders but somehow not able to see the total number of items store in them

Then I tried searching the Internet and found a script which does it. This script is written by well knows PowerShell MVP “Shay levy”

This script solve my problem and then i thought i should share it with you.

you can download the script from here:  http://dl.dropbox.com/u/17858935/ListOutlook_Folders_Total_Emails.zip

Screenshot of the output when you run script.

Before: When first time I run the Script

After: I removed 2 email from my “Junk-Junk” folder and test it again and precise result

Thanks “Shay”




Aman Dhally

Friday, November 25, 2011

“Find how many types of files you have in you laptop” using Powershell.



Today i was searching for one PDF file on my laptop and then I just thinks “How Many PDF files do i have?”, i have no idea, one way to find is go to windows search and find all .PDF files? but “how can i find this with powershell”

we can

let try it ..

Cmdlet Used: Get-ChildItem,Group-Object, Sort-Object

Command: $files =  Get-ChildItem -Path C:\Users\aman.dhally\Documents –Recurse

In $files variable i am saving the result of Get-ChildItem -Path C:\Users\aman.dhally\Documents –Recurse  command , Get-ChildItem in equal as DIR command and we are using –Path switch parameter to give the path of the folder in which we want to search for files, –Recurse means including sub folders.


lets run $files variable and see what it has stored

It showing the files and folders located in my “Document” folder


let filer the results

$files | Group-Object -Property Extension | Sort-Object Count –Descending

now pipe the $files variable to Group-Object cmdlet and the grouping Property is Extensions because we want to group files by there extensions, now piped the command to Sort-Object and we are sorting the results by Count,

OoPs 751 .torrent files,, going to delete them . )



aman dhally

Thursday, November 24, 2011

Finding Network Adapter Data Based On Connection Name


PowerTip of the Day, from PowerShell.com

Sometimes it would be nice to be able to access network adapter configuration based on the name of that adapter as it appears in your Network and Sharing Center. To find the network configuration data for any network card with a "LAN" in its name, use this code:

Get-WmiObject Win32_NetworkAdapter -Filter 'NetConnectionID like "%LAN%"' |   ForEach-Object { $_.GetRelated('Win32_NetworkAdapterConfiguration') }

If you want to further narrow this down and cover only NICs that are currently connected to the network, extend the WMI filter:

Get-WmiObject Win32_NetworkAdapter -Filter '(NetConnectionID like "%LAN%") and (NetConnectionStatus=2)' |   ForEach-Object { $_.GetRelated('Win32_NetworkAdapterConfiguration') }

Tuesday, November 22, 2011

How to find “Stopped” windows Services, whose start up mode is set to “Automatic” using PowerShell.

I called these services as “Problematic services”. The start-up mode of these services are “Automatically” so that whenever windows starts or reboot these services should start automatically.
So logically if any of windows services start mode is set to “Automatic” then the Window Service should be running not “stopped”
we are using WMI query language to find these “Problematic Services”
Cmdlet use: Get-WmiObject, Where-Object , Select-Object, Format-List
we are using Win32_Service WMI call to retrieve the list  and status of the services.
   1: Get-WmiObject win32_Service

above command will show the list of all windows services.


Let’s check the all properties of a single “Service”

Get-WmiObject win32_Service  | select -First 1 | fl *

we are piping the result of “Get-WmiObject win32_service” to select-Object cmdlet and choosing -first 1 single Service and then piping further to “Format-List” cmdlet and using * wildcard to show everything.

In below properties we are interested in Name,Status, StartMode, and State property of services.

Get-WmiObject win32_Service  | where {$_.StartMode -eq "Auto" -and $_.State -eq "stopped"}

we are piping the previous command to Where-Object cmdlet and filtering to show  only those services whose “StartUp” mode is “Automatic” and “Status” is “Stopped”

oh!!! we have three problematic services. Okkk!!!


Let’s filter a little bit more
Get-WmiObject win32_Service  | where {$_.StartMode -eq "Auto" -and $_.State -eq "stopped"} |  Select Name,StartMode,State

now we are piping all the previous command to Select-Object cmdlet and choose to show only Name, StartMode, and State property.

Now it seems little bit formatted.

Now you can start these service manually .



Aman Dhally

Outputting Text Reports without Truncating


PowerTip of the Day, from PowerShell.com:

If you want to capture PowerShell results in a text file, you can redirect the results or pipe them to Out-File. In any case, what you capture is the exact representation of what would have been displayed in your PowerShell console. So, depending on the amount of data, columns may be missing or truncated.
Here is a function called Out-Report. You can pipe any result to it to create a text file that does not truncate columns. In addition, with the –Open switch parameter, you can open the resulting text file, too:
   1: function Out-Report {
   3:  param(
   5:   $Path = "$env:temp\report.txt",
   7:   [switch]$Open
   9:  )
  13:  $Input |
  15:   Format-Table -AutoSize |
  17:   Out-File $Path -Width 10000
  21:   if($Open) { Invoke-Item $Path }
  23: }

Try it:

Get-Process | Out-Report -Open



Monday, November 21, 2011

I know its funny :)


total Page views are: 420  :D


Funny-420 visitors

Find the List of Installed software using WMI and PowerShell.



how you find the which software is installed on your computer, most of users answered  in “Control Panel” , yes it is right . but, if you are creating an Inventory of which system have which software then it’s not so useful for admins.

lets use WMI to retrieve the list of Install list of Softwares:

Cmdlet used: Get-WmiObject, Select-Object, Sort-Object, Export-CSV

Command is:

   1: Get-WmiObject win32_Product  | Select Name,Version,PackageName,Installdate,Vendor | Sort InstallDate -Descending

using Get-WmiObject cmdlet we query the win32_Product class which have the information of list of all software installations. Then we piped the command to Select cmdlet and we are selecting Name, Version, PackageName and installation date of the softwares and then pipe the command to Sort-Object cmdlet and sorting the result to descending order which mean latest first.


let export the result to CSV for future reference using Export-CSV cmdlet.

   1: Get-WmiObject win32_Product  | Select Name,Version,PackageName,Installdate,Vendor | Sort InstallDate -Descending| Export-Csv d:\report.csv


all command is same but we piped the command further to Export-CSV cmdlet and saving the file to D:\ with name of Report.CSV


let see if this created a csv file .


yes, file is created lets open it!!!

Done !!! seems good isn’t.



Thanks for viewing

Aman Dhally

Sunday, November 20, 2011

Turning SIDs into Real Names using PowerShell


PowerTip of the Day, from PowerShell.com:

Sometimes, you'd like to turn security identifiers (SIDs) into real names. Here is a function that can do this for you:

   1: function SID2Name($sid){
   3:   $objSID = New-Object System.Security.Principal.SecurityIdentifier($sid)
   5:   try {
   7:   $objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
   9:   $objUser.Value
  11:   } catch { $sid }
  13: }

And, here is a show case for the function: to enumerate all profiles on your computer, you can read them from the Registry. However, all profiles are stored with SIDs only. Thanks to your new function, you can now display the real user names of everyone who has a profile on your machine:

   1: function Get-Profile {
   3: $key = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList'
   5: dir $key -Name | ForEach-Object { SID2Name $_ }
   7: }

Thanks to www.Powershell.com

Friday, November 18, 2011

Converting User Names to SIDs using PowerShell


PowerTip of the Day, from PowerShell.com: 

Converting User Names to SIDs

If you want to translate a valid user name to its security identifier (SID), here is a function to do that for you:


Converting User Names to SIDs

If you want to translate a valid user name to its security identifier (SID), here is a function to do that for you:

function Name2SID($name, $domain=$env:userdomain) {

$objUser = New-Object System.Security.Principal.NTAccount($domain,$name)

$strSID =$objUser.Translate([System.Security.Principal.SecurityIdentifier])



Try it with your current user name:


Name2SID $env:username


Note: Tip copied from PowerShell.com

Copy Files and Folders using PowerShell




Copy files and folders this is the task which every Admin or even a end user performs daily.

How we can Copy files and folder using PowerShell?

Quite Easy, we just need to use Copy-Item cmdlet with few Switch Parameters that all.

Cmdlet used : Copy-Item

:::: Copy Files

Lets create a a new folder to Backup files currently I have  one Folder named “Folder_A” which contain Data and we will create a new folder named as “Backup_A” , and then copy data from “Folder_A” to “backup_A”


let create a new folder named “Backup_A”


Now we have two folders “Folder A” and “Backup_A”


now copy a file from “Folder_A” to “backup_A” ,

command is: Copy-Item D:\Demo\Folder_A\Book.txt -Destination D:\Demo\Backup_A

file successfully copied.


:::: Copy Txt file only


if we want to copy specific type of files only then we can use –Include switch Parameter followed by the type .


We can use –Verbose switch to see which files are getting copied

command: Copy-Item D:\Demo\Folder_A\* -Destination D:\Demo\Backup_A -Include *.txt –Verbose

see the screenshot, command copied the .Txt files only


:::: Exclude files to copying


If we are using Copy-Item cmdlet in a backup script it would be good we don’t backup Music,Video files on server. As a Ideal Policy we should not fill our SAN, Server storage with the backup of users music and videos.

to exclude these files to be copied use –Exclude switch parameter followed by file types example *.mp3,*.mp4 etc

in my Folder_A i have few MP3 audio and few MP4 video files, lets stop them copying to our Backup_A folder.


note: * means all

Command: Copy-Item D:\Demo\Folder_A\* -Destination D:\Demo\Backup_A -Exclude *.mp3,*.mp4

When i search for *mp3 and  *mp4 no result were found and you can also see there is not a single MP3 and MP4 in “Backup_A” folder.


:::: Copy Folders

the command is same like copying file but rather then specify file we need to specify folder

Command : Copy-Item D:\Demo\Folder_A\Recurse_Testing -Destination D:\Demo\Backup_A\

Folder Copied


BUTTTTTTTT !!! wait…!!!!!!!!!!!!!

Check the folder again, Recurse_Testing have some Sub-folders which are not copied in backup_A



to Copy All folder including sub-folders use –Recurse while copying

Command is:

Copy-Item -Recurse D:\Demo\Folder_A\Recurse_Testing -Destination D:\Demo\Backup_A\  -Verbose


let check if it copied subfolder also.

Seems Identical isn’t.


:::: Copy all files and Folders

To copy all file and folder we use * wildcard which means all , and –Recurse to copy sub-directories also and we also use –force do that if there any file exists with same name on backup folder it should get overwrites.

command : Copy-Item -Recurse D:\Demo\Folder_A\* -Destination D:\Demo\Backup_A -Force –Verbose


lets check if these two folders are identical.

Seems like TWINS isn't ;-)


Hope it is useful to someone .


Aman Dhally

Thursday, November 17, 2011

Use PowerShell as “Calculator”



this is a very basic tip.

The tip is “You can use PowerShell as a calculator”, so guys stop using CALC use PowerShell instead.

I don’t teach you how to use Addition (+), Subtraction (-), Multiplication (*) and Division (/), tried it yourself :)





Wednesday, November 16, 2011

“VIM” a console based Script Editor for PowerShell



I hope some of you know about what is VIM is and for those who don’t know what VIM is for them “VIM” is console based text editor and it’s very advance text editor. Basically VIM was made for LINUX and it’s come pre-installed in most of the Linux Distributions. Now they also make it compatible with Windows. You can download VIM executable from VIM website or you can download VIM directly from this Download link ftp://ftp.vim.org/pub/vim/pc/vim73_46w32.zip 

Why to use VIM?

hummm.. if you want to do edit PowerShell scripts directly from PowerShell Console or you don’t want to use EDIT command to edit PowerShell Script and want some more advance features then VIM is for you. We will use VIM as console based test Editor.

How to use it?

Download vim  ftp://ftp.vim.org/pub/vim/pc/vim73_46w32.zip  and save it anywhere on your laptop and Extract the .ZIP file.


Now Paste the extracted Vim.exe folder in C:\Windows\System32 so that it automatically added to your environmental path so that we can execute the VIM.exe from anywhere in the console.


Now lets open PowerShell Console and see if we able to run VIM successfully.


It’s Open.. to quit this windows type :q


Now open a PowerShell Script using VIM , Vim  and location of PowerShell Script


Looks good isn’t


Press Escape and type :se nu in vim and hit Enter and Line Number appear in the script :)


to quit the vim without saving the script Press Escape Key and type :q! and hit enter.

To know more about vim see this online documentation : http://vimdoc.sourceforge.net/htmldoc/usr_toc.html 


Thanks for reading


Aman Dhally

Tuesday, November 15, 2011

Ping Multiple Servers using “PowerShell”



Today I was looking for  a little PowerShell script which can Ping multiple servers and give a consolidated view on PowerShell console that which one is Live and which one is Dead.

Then a decide to write my own and finally wrote  it: ) and it is a only a 9 line script :)

You can copy and paste the script from below or you can download it from here : http://dl.dropbox.com/u/17858935/Ping_Multiple_Servers.zip 

let me explain the script :

$Servername: is a variable which contain a list  of comma separated Server name

in foreach script block we are selecting all servers in $ServerName variable and run Test-Connection cmdlets against them

in If Test-Connection evaluates that servers in Pinging that it writes “S$server is alive” otherwise it write “Server is dead”,

In test-connection Cmdlet we define that it should send only 2 Pings to the server using –count 2 switch parameter and used –Quiet Switch parameter so that is show the output in Boolean (true or false)


   1:  #### Provide the computer name in $computername variable
   3:  $ServerName = "Dc-2","LocalHost","Server-2","Not-Exists","Fake-computer"
   5:  ##### Script Starts Here ###### 
   7:  foreach ($Server in $ServerName) {
   9:          if (test-Connection -ComputerName $Server -Count 2 -Quiet ) { 
  11:              write-Host "$Server is alive and Pinging " -ForegroundColor Green
  13:                      } else
  15:                      { Write-Warning "$Server seems dead not pinging"
  17:                      }            
  18:  }
  20:  ########## end of script #######################

The output of the script will be like below link.



Download Link : http://dl.dropbox.com/u/17858935/Ping_Multiple_Servers.zip 



aman dhally

Monday, November 14, 2011

How to create and change “Windows Registry Keys” using PowerShell.



The Best thing about PowerShell is that you can manipulate “windows  Registry Keys” very easily with it. How? Let me show to you.

Why we need to create a registry Hive/key manually?

Actually for lots of reason, for example if you want to install some particular software on all accounting computer automatically and then you can need write a script which check the predefined registry Keys and if it found that the in key  Department is “accounts” then install it may install some accounting software on it otherwise don’t do anything.

Cmdlets used: New-Item , New-ItemProperty, Set-ItemProperty

Before running the below command  make sure you run PowerShell as Administrator.

How to run PowerShell as Administrator?

to do this , Search for PowerShell { you can also access the same from Start > All Programs > Accessories > windows PowerShell > Windows PowerShell} , Right Click on it and Choose “Run as Administrator


When you run PowerShell as Administrator you will see that the title bar of PowerShell windows shows Administrator:


Now let’s create a new Folder named “CompanyName” in “Hkey_Local_machine” and  beneath Software key folder.

In PowerShell we can use Registry hives as Local drives so we can use New-item cmdlet to create a new registry hive.

new-Item -Name "CompanyName"  -Path 'hklm:\SOFTWARE\'  -type Directory

New-Item : used to create a new folder for file

-Name : Name of the Folder

-Path: where we want to create a new folder

-Type: Directory in our case because “CompanyName” will contain some sub registry keys.


Let’s  check . . . Yes “Registry Hive” is created . .


now lets create a new Registry key in “ComanyName”  names as “Department” which have some information about which on Department the laptop/desktop belong to.

New-ItemProperty -Path 'hklm:\software\CompanyName\' -Name "Department" -Value "I.T"


Let’s check ….. Key is created . . . .



what if you need to change the value of the key?, you can do it easily using Set-ItemProperty cmdlet.

Now Lets change the department name from “I.T.” to “Accounts”

set-ItemProperty -Path 'hklm:\software\CompanyName\' -Name "Department" -Value "Accounts"


Let’ See…….yes Department name is changes from “I.T.” to “Accounts”



I hope this post will save someone time :) ..


Aman Dhally


Friday, November 11, 2011

How to create New files using PowerShell.



Yes Yes I know its very Simple, But I love to share :) , I know may be everyone know how to create new files using PowerShell, but still I want to share it :)

Cmdlet to use: New-Item

Let’s start:

the command is :

New-Item -Name "Test.txt" -Path "D:\demo" -ItemType File

New-Item: Cmdlet use to create a new file or Directory

-Name: Name of the file, provide file type by giving them proper file extension for example .txt, .csv, .ppt etc.

-Path: File Location  where you want to save the file

-ItemType : It should be file when you are creating files.


Our Test.Txt file is successfully  created in D:\Demo


now lets create a new blank MSWORD file using the same command but we changed the file extension .txt to .DOC

New-Item -Name "Test2.doc" -Path "D:\demo" -ItemType File


let’s see the file. , It’s Created



What if you want to overwrite an existing file. to do this use –Force switch parameter with the command.

New-Item -Name "Test.txt" -Path "D:\demo" -ItemType File -force

See in the below screenshot, before running the above command the length/size of test.txt was 20 bytes but after running the above command the old file “test.txt” overwritten by new “test.txt” and the new file don’t have any content in it that’s why the new file size is Zero.


I Hope this is Helpful…… at least to someone :)



Aman Dhally

How to create a New folder using PowerShell.



I know it is very simple to do :) , but sometime dumb like me don’t know how to do it . Or which Command is used to  do it ..

The Command which is used to create a new folder is : New-Item

You can also create a new folder using old mkdir command: Mkdir “Folder Name”

but let’s use PowerShell way to do this.

Lets Start:

Open PowerShell Console

To create a new Directory use this command  and hit enter:

New-Item -path D:\Demo -Name "Foo" -ItemType Directory

-path:  location path where you want to create folder

-Name : Name of the Folder / directory to be Created

-ItemType: it is “directory” to create a folder

and It creates a folder name “Foo” in D:\Demo


what if you want to create a new folder which is already exists?

you will got an error “Directory Name Already exists”


and If you want to create a new folder and that folder already exists and you want overwrite it, try      –Force switch parameter with the command.



Hope this is helpful . . .


Aman Dhally