Sunteți pe pagina 1din 25

June 2015 Powershell Tips

(c) Som Dutt Tripathi

Disclaimer
The content of this book has been taken from personal blog. The opinions expressed here represent my own and not
those of my employer.

All content provided on this blog is for informational purpose only. I am solely responsible for all content published
here and any views or opinions expressed here are strictly my own. Content published here is not read, reviewed, or
approved in advance by any company and does not necessarily represent or reflect the views or opinions of my
employer or any of its divisions, subsidiaries, or business partners.

The owner of this blog makes no representations as to the accuracy or completeness of any information on this site or
found by following any link on this site. The owner will not be liable for any errors or omissions in this information nor
for the availability of this information. The owner will not be liable for any losses, injuries, or damages from the display
or use of this information. You can use this information on your own risk.While every caution has been taken to provide
most accurate information , please use your discretion before taking any decisions based on the information in this blog.
Articles cannot be used, reprinted, or published without my written consent. Everyone can use the scripts/commands
provided here without any written permission but owner will not be liable for any damage, loss to the systems.

Trademark Notice
"MicrosoftPowershell" is a registered trademark of Microsoft Corporation in the United States and other countries.

"MicrosoftWindows" is a registered trademark of Microsoft Corporation in the United States and other
countries.
"Microsoft Internet Explorer" is a registered trademark of Microsoft Corporation in the United States and
other countries.
"MicrosoftWord" is a Microsoft Corporation product name in the United States.
"MicrosoftExcel" is a Microsoft Corporation product name in the United States.
TM and 2014 Apple Inc. All rights reserved.
Apple, the Apple logo, iPad, iPhone, iTunes, QuickTime, the QuickTime logo, Mac OS are trademarks of
Apple Inc., registered in the U.S. and other countries. The iPhone trademark is used under license from
AiPhone Co., Ltd. App Store, AppleCare are service marks of Apple Inc., registered in the U.S. and other
countries.
"Google", the "Google logo", "Google Maps", "Chromecast", "Google Play", the "Google Play logo",
"Android" and the "Android logo" are trademarks or registered trademarks of Google Inc.
"YouTube" and the "YouTube logo" are registered trademarks of Google Inc.
"Gmail" is a registered trademark of Google Inc.
"Mobile Suica" is a registered trademark of East Japan Railway Company.
"i-mode"is a trademark or registered trademark of NTT DOCOMO, INC.
"FeliCa" is a registered trademark of Sony Corporation. "FeliCa" is the contactless IC card technology
developed by Sony Corporation.
"Rakuten Edy" is a registered trademark of Rakuten Edy, Inc.
"WAON" is a registered trademark of AEON Co., Ltd.
"mixi" is a registered trademark of mixi, Inc.
"Twitter" is a registered trademark of Twitter, Inc.
"Facebook" is a registered trademark of Facebook, Inc.
"Evernote" is a registered trademark of Evernote Corporation in the United States.
Skype, associated trademarks and logos and the "S" symbol are trademarks of Skype Limited.
The "AQUOS logo", "AQUOS", "AQUOS SHOT", the "AQUOS PHONE logo", "AQUOS PHONE",
"SERIE", the "Eco Waza mark", "Eco Waza", "Feel UX", "SV engine", "Veil view", "Fami-link", "CGSilicon"
and "IGZO" are trademarks or registered trademarks of SHARP CORPORATION.
"HTC EVO" is a registered trademark of HTC Corporation.
"REGZA" and "REGZA Phone" are registered trademarks of Toshiba Inc.
"Sony", "Exmor R for mobile", the "Exmor R for mobile logo", "WALKMAN", the "WALKMAN logo", "NET
JUKE", the "NET JUKE logo", "BRAVIA" and "Cyber-shot" are trademarks or registered trademarks of Sony
Corporation.
"G'zOne", "G-SHOCK", "EXILIM" and "EXILIM Keitai" are trademarks or registered trademarks of CASIO
COMPUTER CO., LTD.
"MEDIAS" is a trademark or registered trademark of NEC CASIO Mobile Communications, Ltd.
"Wooo" and "Picture Master" are registered trademarks of Hitachi Consumer Electronics Co., Ltd.
"ARROWS" is a registered trademark of Fujitsu Limited.
SIRIUS is a trademark of Pantech Co., Ltd.
MOTOROLA, MOTOROLA XOOM, the MOTOROLA logo mark and MOTOROLA PHOTON are registered
trademarks of Motorola Trademark Holdings, LLC.
"Wi-Fi" is a registered trademark of Wi-Fi Alliance.
"Wi-Fi CERTIFIED Miracast" and "Miracast" are registered trademarks of Wi-Fi Alliance.
"Xperia" is a trademark or registered trademark of Sony Mobile Communications AB.
GALAXY is a registered trademark of Samsung CO., Ltd.
"DIGNO" is a registered trademark of Kyocera Corporation.
"Sekai Camera" is a registered trademark of Tonchidot Corporation.
"Kisekae touch" is a trademark of Acrodea, Inc.
"Jblend" is a registered trademark of Aplix Corporation.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of
their respective owners.
"NetFront" is a trademark or registered trademark of ACCESS CO., LTD. in Japan and other countries.
"BREW" and its associated trademarks are trademarks or registered trademarks of Qualcomm Incorporated.
"Picsel", "Picsel Powered", "Picsel Viewer", "Picsel File Viewer", "Picsel Document Viewer", "Picsel PDF
Viewer" and the "Picsel Cube" logo are trademarks or registered trademarks of Picsel Technologies.
"Chaku-Uta", "Chaku-Uta-Full" and "Chaku-Uta-Full-Plus" are registered trademarks of Sony Music
Entertainment(Japan)Inc.
"RecoChoku" and the "RecoChoku logo" are trademarks or registered trademarks of RecoChoku Co, Ltd.
Uta tomo is a registered trademark of Label Gate Co., Ltd.
QR Code is a registered trademark of DENSO WAVE INCORPORATED.
DBEX is a registered trademark of DiMAGIC Co., Ltd.
"mora" and its name and logo are trademarks or registered trademarks of Label Gate Co., Ltd.
"Any Music" is a registered trademark of Any Music Inc.
"Global Assist" is a trademark or registered trademark of Sony Mobile Communications Inc.
"Windows", "MicrosoftWindows", "Windows Vista" and "Windows LiveWindows Live" are
trademarks or registered trademarks of Microsoft Corporation.
"Microsoft", "Microsoft ActiveSync", "Microsoft Office OneNote", "Microsoft Office Outlook",
"Microsoft Office Excel", "Microsoft Office PowerPoint", "Windows", "Windows7", "Windows
Mobile" and "Internet Explorer" are trademarks or registered trademarks of Microsoft Corporation.
"Macromedia", "Flash" and "Flash Lite" are trademarks and registered trademarks of Adobe Systems,
Inc. in the United States and other countries.
"microSD", "microSDHC", "microSDXC" and "miniSD" are trademarks or registered trademarks of
SD Card Association.
"SDHC" is a registered trademark of SD Card Association.
"Bluetooth" is a registered trademark of Bluetooth SIG, Inc. USA.
"i-mode" is a registered trademark of NTT DOCOMO, INC.
"Wii" is a registered trademark of Nintendo Co., Ltd.
"PlayStation", "PlayStation 2", "PlayStation 3", "PS3" and "PSP" are registered trademarks of Sony Computer
Entertainment Inc.
"Adobe", the "Adobe logo" and "Adobe Reader" are registered trademarks of Adobe Systems
Incorporated in the United States and other countries.
"IntelPentium" is a registered trademark of Intel Corporation in the United States and other countries.
"Netscape" is a registered trademark of Netscape Communications Corporation in the United States and other
countries.
"Rovi", "G-GUIDE" and the "G-GUIDE logo" are trademarks or registered trademarks of Rovi Corporation in
the United States and/or its affiliates in Japan.*The names of other companies and products are trademarks or
registered trademarks of their respective companies.
Introduction
This book is a collection of articles from my blog http://powershell-tips.blogspot.com. In my daily
schedule, I give a certain hour in writing to my blog. I have created this book as collection of the
articles written in my blog so that you get all of them together at one place.

This book has all the aricles written in June 2015. Hope you would like this effort.
Thanks to everyone who helped me in writing this book.

- Som Dutt Tripathi


Content

1. Find ODBC Drivers installed on the host with Powershell


2. Difference between redirection operator and Out-File
3. Save File Dialog with Powershell
4. Open File Dialog with Powershell
5. String handling with Substring function
6. Find difference in two dates with Powershell?
7. Find Free Memory Status on a Computer
8. Find who is logged in list of machines using Powershell
9. How to get directory size using Powershell?
10. Using Choice Box in Powershell
DedicatedtomywifeanddaughterwhobearwithmewhenIamalways
stucktomylaptop...
1. Find ODBC Drivers installed on the host with Powershell
Friday 12 June 2015 08:25 PM

ODBC Drivers are generally installed on servers to allow communication with different database
engines. You can use Powershell to get the list of ODBC drivers installed on the host.
You need to run Get-ODBCDriver cmdlet which will give you all the details.

Get-OdbcDriver

Name : Microsoft Access-Treiber (*.mdb)

Platform : 32-bit

Attribute : {Driver, APILevel, FileExtns, FileUsage...}

Name : Driver do Microsoft Paradox (*.db )

Platform : 32-bit

Attribute : {Driver, APILevel, FileExtns, FileUsage...}

Name : Driver do Microsoft Excel(*.xls)

Platform : 32-bit

...

The output might not be pleasant. If you think so, you can try the line below:

Get-OdbcDriver | ft Name

Name

----

Microsoft Access-Treiber (*.mdb)

Driver do Microsoft Paradox (*.db )

Driver do Microsoft Excel(*.xls)

Microsoft Text Driver (*.txt; *.csv)

Driver da Microsoft para arquivos texto (*.txt; *.csv)

....
2. Difference between redirection operator and Out-File
Friday 12 June 2015 07:26 PM

Redirection operator can be used most of the scripting languages. If you use single redirection
operator (>), it means create a file and write or overwrite the file with the string.
In Powershell, you can use them, but we have advantage of Out-File cmdlet. Let us try to see what
is major difference. The difference is that redirection operator will always go with unicode
character.

For example:

echo "Line - 1" > c:\temp\file.ps1

echo "Line - 2" >> c:\temp\file.ps1

It will generate a file with Unicode character set.

Repeating the same with Out-File :

echo "Line - 1" | Out-File c:\temp\file.ps1 -Encoding "ASCII"

echo "Line - 1" | Out-File c:\temp\file.ps1 -Encoding "ASCII" -Append

It will generate a file with ASCII character set.

Mind that we have use -Append in the second line. This will allow appending. Check yourself that
what will happen if you don't use -Append switch.

There are below character sets possible with -Encoding option:


Unicode
UTF7
UTF8
UTF32
ASCII
BigEndian
Unicode
OEM

If you don't mention Encoding switch, Unicode will be taken as default.

Don't mix character set if you don't want to see unexpected graphics in file. For example, if you run
below lines, you will understand what I mean.

echo "Som" > file.txt

echo "Som" | out-file .\file.txt -Encoding "ASCII" -Append

When you open file.txt, you would see first line written correctly and second line written in chinese.
I have faced such situations where output is coming from multiple command line apps like osql and
sqlplus and mixing them together created a real mess. The difficult part is that you can barely
troubleshoot where problem is coming from. Try to stick to ASCII in my opinion.
3. Save File Dialog with Powershell
Friday 12 June 2015 07:26 PM

This is continuation of previous article. In fact, there is no difference in save dialog and open file
dialog. The difference if that here you can get message of replacing file. Save File dialog does not
save anything, you have to save it yourself.

Below is the code for the same :

#----------------------------------------------------------------------------------------#

#-- Function Declaration

#----------------------------------------------------------------------------------------#

function Save-File([string] $initialDirectory )

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

$OpenFileDialog = New-Object System.Windows.Forms.SaveFileDialog

$OpenFileDialog.initialDirectory = $initialDirectory

$OpenFileDialog.filter = "All files (*.*)| *.*"

$OpenFileDialog.ShowDialog() | Out-Null

return $OpenFileDialog.filename

#----------------------------------------------------------------------------------------#

#Usage :

#----------------------------------------------------------------------------------------#

$File=Save-File "C:\temp\tips"

if ( $File -ne "" )

echo "You choose FileName: $File"


}

else

echo "No File was chosen"

}
4. Open File Dialog with Powershell
Friday 12 June 2015 07:26 PM

This is interesting that all GUI operations can be done with Powershell without any problem.
Basically, most of the resources available to any .NET application applied to Powershell. This make
Powershell more vast and limitless (in my opinion).

So, let's see the code which will be used to open a dialog. The requirement is simple, the script will
show a dialog to open any file, if user has open a file then script will display file name or show if
user has cancelled the dialog. I would suggest not to use this script for any scheduling or automated
job as this will stuck your job till host reboot (I think).

#----------------------------------------------------------------------------------------#

#-- Function Declaration

#----------------------------------------------------------------------------------------#

function Open-File([string] $initialDirectory )

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog

$OpenFileDialog.initialDirectory = $initialDirectory

$OpenFileDialog.filter = "All files (*.*)| *.*"

$OpenFileDialog.ShowDialog() | Out-Null

return $OpenFileDialog.filename

#----------------------------------------------------------------------------------------#

#Usage :

#----------------------------------------------------------------------------------------#

$File=Open-File "C:\temp\tips"

if ( $File -ne "" )


{

echo "You choose FileName: $File"

else

echo "No File was chosen"

}
5. String handling with Substring function
Friday 12 June 2015 07:26 PM

Substring function is available in nearly all the programming and scripting languages. This function
is best suited for traversing each character or set of characters of string based on length and rank of
character to start with. In fact, you can do chopping of certain string from the complete string. I
have used substring a lot with T-SQL Programming. Let us take a look how substring can be used in
Powershell.

1. Chop last three characters from a string using substring. If string is less than 3 character, return
whole string.

#-------------------------------------------------------#

#--Function to find last three characters of a string --#

#-------------------------------------------------------#

function chop-last-three([string]$str)

if ( $str.length -ge 3 )

echo $str.substring($str.length - 3, 3)

else

echo $str

chop-last-three "ABCDEFGHIJKLMNOP"

2. Chop first three characters of a string using substring. If string is less than 5 characters, return
whole string.
#-------------------------------------------------------#

#--Function to find first three characters of a string --#

#-------------------------------------------------------#

function chop-first-three([string]$str)

if ( $str.length -ge 3 )

echo $str.substring(0, 3)

else

echo $str

chop-first-three "ABCDEFGHIJKLMNOP"
6. Find difference in two dates with Powershell?
Thursday 04 June 2015 06:05 PM

Sometimes we need to get this information like total time taken by script or total time a program
ran. This is quite simple to get the difference between two dates if the data type is set to DateTime.

Below is a sample script for the same :


This script will show the difference in Seconds, Hours and Minutes. You can also go to even deeper
such as milliseconds.

Function Get-DateDifference( [DateTime]$FromDate, [DateTime] $ToDate , [String]$OutputType


)

[int]$Output=-1

if ( $FromDate -gt $ToDate )

echo "Error: [From date] should not be greater than [To Date]."

else

Switch ( $OutputType )

"Seconds" { $Output=$($ToDate - $FromDate).TotalSeconds }

"Hours" { $Output=$($ToDate - $FromDate).TotalHours }

"Minutes" { $Output=$($ToDate - $FromDate).TotalMinutes }

if ( $Output -ne -1 )

echo "$Output $OutputType"

}
$Date1=Read-Host "Enter the From Date"

$Date2=Read-Host "Enter the To Date"

Get-DateDifference -FromDate $Date1 -ToDate $Date2 -OutputType 'Seconds'


7. Find Free Memory Status on a Computer
Thursday 04 June 2015 04:26 PM

Today's tip is about getting the free space in memory on a computer. This can easily done with
WMI. Let's take a look in a one-liner.

Get-WmiObject win32_operatingsystem | select csname, FreePhysicalMemory,


FreeSpaceInPagingFiles, FreeVirtualMemory

This can play a good role when you are writing a script which might consume too much of memory,
you can plan the execution when memory usage is normal.
8. Find who is logged in list of machines using Powershell
Thursday 04 June 2015 04:26 PM
Recently, there were list of workstations assigned to our team. As there are many people working on
those workstations, it was difficult to find who is logged in on which machine without asking.
Finally, I ended with below script which can tell the same easily.

Below are steps for testing the script :

1. Create a directory, say WhoLoggedIn.


2. Create a file with name list.txt.
3. Use Notepad and edit list.txt and add all servers with one line for each server.
4. Create a Powershell script say WhoLoggedIn.ps1

Paste the code from below :

$THIS_SCRIPT_NAME=${myInvocation}.ScriptName

$SCRIPT_LOC=Split-Path -parent ${Script:THIS_SCRIPT_NAME}

$VALS=gc $SCRIPT_LOC\List.txt | where { $_ -match "^[1-9]" } | foreach { $_ + $(& query


user /server:"$_") }

$FINAL_VAL=$VALS | foreach { $_.replace("USERNAME SESSIONNAME ID


STATE IDLE TIME LOGON TIME ","") } | foreach { $_.replace(" ", " ") }

echo $FINAL_VAL

Run the same and you will see results in proper format. I made a script which will log the same info
into SQL Server using the same script. Choice is all yours what you do with it. My job is to give
direction ...
9. How to get directory size using Powershell?
Thursday 04 June 2015 04:26 PM

A quick tip, to get the size of the folder, you can use below line :

"{0:N2}" -f ($(ls "c:\temp" -recurse | Measure-Object -property length -sum).sum /1MB) +


" MB"

Replace MB with KB if you want in KB.

"{0:N2}" -f ($(ls "c:\temp" -recurse | Measure-Object -property length -sum).sum /1MB) +


" MB"
10. Using Choice Box in Powershell
Thursday 04 June 2015 04:27 PM

I got an interesting requirement to allow users choose from a list. The list will be dynamic and will
display all items of the file in a drop down list.

Preparation:
1. Create an empty file called list.txt.
2. Add below entries to the file:
ABC
XYZ
PQR
RST
UVX
123

3. Create script and paste below code:

function showDialog([string]$file)

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")

$objForm = New-Object System.Windows.Forms.Form

$objForm.Text = "Choice-Box"

$objForm.Size = New-Object System.Drawing.Size(300,200)

$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True

$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")

$x=$objListBox.SelectedItem;$objForm.Close()}

})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")

{$objForm.Close()}})

$OKButton = New-Object System.Windows.Forms.Button

$OKButton.Location = New-Object System.Drawing.Size(75,120)

$OKButton.Size = New-Object System.Drawing.Size(75,23)

$OKButton.Text = "OK"

$OKButton.Add_Click({$x=$objListBox.SelectedItem;$objForm.Close()})

$objForm.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button

$CancelButton.Location = New-Object System.Drawing.Size(150,120)

$CancelButton.Size = New-Object System.Drawing.Size(75,23)

$CancelButton.Text = "Cancel"

$CancelButton.Add_Click({$objForm.Close()})

$objForm.Controls.Add($CancelButton)

$objLabel = New-Object System.Windows.Forms.Label

$objLabel.Location = New-Object System.Drawing.Size(10,20)

$objLabel.Size = New-Object System.Drawing.Size(280,20)

$objLabel.Text = "Please choose any of the below :"

$objForm.Controls.Add($objLabel)

$objListBox = New-Object System.Windows.Forms.ListBox

$objListBox.Location = New-Object System.Drawing.Size(10,40)

$objListBox.Size = New-Object System.Drawing.Size(260,20)

$objListBox.Height = 80

$items = gc $file | where { $_ -ne "" }

foreach ( $item in $items)

[void] $objListBox.Items.Add($item)

$objForm.Controls.Add($objListBox)
$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})

[void] $objForm.ShowDialog()

$x

showDialog .\list.txt

Once your run it, you will get a popup like below:

That's it! You can see the value of $x can be used further in any place of your code.

S-ar putea să vă placă și