Sunday, June 14, 2015

#86 : Mastering Powershell

A free ebook of powershell is 'Mastering Powershell' written by Dr. Tobias. The book is written in a very simple language and gives a full glimpse of Powershell Programming.

 

Download
(Download link might change anytime, please search in google/bing if required)

I like the way of expression of this book. But I feel there are some portions where you feel like the book is unorganized and it looks like writer has so much to say but still so much is left over. It covers most of the portions of Powershell programming especially if you have started learning Powershell.

This book can also help you learning scripting skills. Whether you at advaced, intemediate or novice level of scripting, this book might be very useful to you. As this book is free of cost, you don't have to bother, do have a look.


Powershell-Tips Rating : 3/5

Thursday, June 11, 2015

#85 : Find ODBC Drivers installed on the host with Powershell

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)                                                                                                                    
....

Thanks for reading!

 

Wednesday, June 10, 2015

#84 : Difference between redirection operator and Out-File

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.

Thanks for reading this article!
 

Tuesday, June 9, 2015

#83 : Save File Dialog with Powershell

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





Hope this article was useful for you. Thanks for reading!

Monday, June 8, 2015

#82 : Open File Dialog with Powershell

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



 

Friday, June 5, 2015

#81 : String handling with Substring function

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"

That's all for today. You may ask questions if you want.
Thanks for reading this article!

Thursday, June 4, 2015

#80 : Find difference in two dates with Powershell?

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'


Hope this was helpful tip.
Enjoy learning Powershell!

Wednesday, June 3, 2015

#79 : Find Free Memory Status on a Computer

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.

Enjoy!

Tuesday, June 2, 2015

#78 : Find who is logged in list of machines using Powershell

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 ...

Enjoy!

Monday, June 1, 2015

#77 : How to get directory size using Powershell?

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"
 
Hope this was easy, right?
 

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...