Thursday, April 30, 2015

#62 : Playing with Windows COM

This script is nothing more than just playing with Windows COM shell. I don't see any purpose of it. But this is good for playing, because as much you play, you learn a lot. If you cannot play with something, you will never understand things completely.





Hope you like this post, send your comments to me!
Enjoy!

Wednesday, April 29, 2015

#61 : How to connect SQL Server with Powershell?

Powershell can be used to run queries against SQL Server. In fact, what C# and other .NET Framework based languages can do, you can do all of them wit h Powershell. You can connect SQL Server and perform all operations which you do with Powershell.

Here is a simple code for this :


Hope you like this article! It's too late night (2:30 AM) and I have to go to bed.
Enjoy!

Sunday, April 26, 2015

#60 : Script to write into Excel Sheet

SUMMARY

In some cases, we need to create excel and upload as attachment to mail. This tasks is so simple when done manually, but we cannot be doing the same work everyday if we need to send Excel sheet everyday. We can try to automate it. But the automation should be as accurate as manual. It sounds very good, but sending a formatted excel document is not so easy.

We can simply attach a CSV which will automatically open in Excel, but CSV is not good for below reasons :

1. CSV does not show columns in correct length.
2. CSV does not color certain fields.
3. CSV will not show bold or italics.

So, the purpose will not be solved with CSV. So here I will use Microsoft ACE to generated the formatted report.

CODE




CONCLUSION

This article is still being written.
 

Saturday, April 25, 2015

#59 : Get Folder Size with Powershell

Sometimes, we need to check the folder size. Although, ls can give your results of certain files, but still you need to struggle to get the folder (directory) size. I wrote one small script to get this with Powershell. You may use this recipe if you are writing something where folder size is required to be checked.



Thanks for reading this article!

Thursday, April 23, 2015

#58 : Find the disk volumes in host

WMI gives a lot of such important information which makes windows administration more manageable. Scripting becomes more and more robust than ever before. 

Powershell can be used to call WMI objects and we can get so much information out of it. 

CODE : 
get-wmiobject win32_logicaldisk | select DeviceId,Size, FreeSpace



You might get a result in proper tabular format. There are lot many scripts possible with this. 
1. Script to report low disk space
2. Script to display disk inventory in multiple hosts 

If you have trouble writing scripts mentioned above, just add your request in comment,  I will pick from there.

Wednesday, April 22, 2015

#57 : Find running Services with Powershell

Find the List of Running Services:
You can get list of all Processes with command like Get-Service. This CmdLet gives you list of all services which are running and stopped.
But sometimes, you might need to know a list of Service which is currently running.
Below Statements can be used for the same -





#--Get the Names of Running Services --#  
Get-Service | where { $_.Status -eq "Running" } | format-table Name  




Stopping a Service with Powershell :

 


Stopping a service is fairly simple with Stop-Service command. Let's do it with a service named "Spooler".




#--Get the Names of Running Services --#  
Stop-Service "Spooler"  









Tuesday, April 21, 2015

#56 : Compression with Powershell or Creating zip file with Powershell

File compression is not at all straight forward in Powershell. Using Windows compression is error-prone. It gives unexpected results and fails silently. The problem is basically with file size larger than 3 Gigs. If file-size is larger than 3 Gigs, Windows 2003 based server will not complete the task and fail silently. If you have delivered it for any critical task, you will find yourself in a real trouble.

Windows native compression method:

Below is the code which can be used : 

#------------------------------------------------------------------------------------------
#     Script : compress_file.ps1
#     Author : Som DT.
#    Purpose : Compress file script
#------------------------------------------------------------------------------------------

function compress-file ([string]$file, [string]$zipfilename)
{
 echo "Compressing [$file] to [$zipfilename]."
 
 if(-not (test-path($zipfilename)))
 {
  set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
  (dir $zipfilename).IsReadOnly = $false
  
  $shellApplication = new-object -com shell.application
  $zipPackage = $shellApplication.NameSpace($zipfilename)
  
  $zipPackage.CopyHere($file)
 
  #--Add some delay to wait -# 
  do {
   $zipCount = $zipPackage.Items().count
   echo "Waiting for compression to complete ..."
   Start-sleep -Seconds 1
  }
  while ($zippackage.Items().count -lt 1)
 
  echo "Finished zipping successfully"
 
 }
} 

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

#--Starting comressing the file --# 
compress-file "D:\new.txt" "D:\new.zip"

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




This works fine with Windows 2008 and above operating system. But still there are two problems -

1. CopyHere function is a real mess. It does not stick to the point where this function is called. It moves ahead, so you need to put a logic to make the script wait till compression is over.
2. This is hard to predict if compression failed. Script might run infinite in some cases. This is genuine problem and above script is not recommended.

Monday, April 20, 2015

#55 : Process Handling with Powershell

You can get list of running Processes with command like Get-Process. 

Below command be used to get Names of all processes running - 


CODE: 
 

Stop a Process if the process is running :

I am not sure why somebody would need this. But anyways, just for learning - you can use below -
Below statement would stop each occurence of Notepad running.
CODE:
 

Find the Process which is using maximum CPU :

Yeah, this might be a good example.
CODE:
 

Find the Process which is using minumum CPU :

Below code is just one word different from above. Select-Object -First 1.
CODE:
Find the Process with more than one Occurences : 
CODE:

Sunday, April 19, 2015

#54 : How to upload file to SharePoint with Powershell?

Uploading to SharePoint is fairly simple with the below snippet. I am sharing the Gist script which might be useful for you. The only carefulness required here is to make sure that credentials are properly granted to the executing account.



Try above and let me know how it goes. Please update me in case of any issues.

Thanks for reading this article!

Saturday, April 18, 2015

#53 : Error Handling with $Error

$Error is an interesting array which records all error messages from current session. It can be cleared also and looked up for presence of any error message in last command. In most of the cases, you may want to set it clear and then look for $error[0].

Make sure when you check the $error.count right after you run the statement which you think as problematic statement.

Code:

$error.clear()

copy-item “c:\temp\abc.txt” “d:\abc.txt”

if ( $error.count -ne 0 )

{

echo “An error occurred in copy operation. Please review the message below:”

echo $error[0]

}

When you run the above in console and abc.txt does not exist, you will get an error message in red color and then from echo part as well. You might be thinking why we need this if error message is there in console. The reason behind using is that if you run the script from a scheduler and want output to be there in log file, this approach can help you a lot.

Other better methods of catching exceptions are:

Try.. Catch

Trap

We will discuss about them in next article. Test this approach and let know your responses.

Enjoy!

Friday, April 17, 2015

#52 : How to display fields of a Delimited file?

I think that delimited file might be a confusing term, but I simply mean with a file which has fields into it separated by a delimiter such as pipe(|) or tilde (~). In course of programming, you may see several such situations where you will have to read a CSV or something similar to that.

Okay, let's open Powershell command prompt and check the below code which will demonstrate you how to do it. Below is the piece of code which you can use :



With the above example, you can see that first field will be 0, second field will be 1 and so on.

Hope, you enjoyed reading!

Thursday, April 16, 2015

#51 : How to check if Port if open or not?

This is fairly simply to test if certain host is able to connect to a port or not with Telnet. Some of the new SQL Server installation do not have Telnet installed. In those cases, we can use Powershell to test is the port.


I will use System.Net.Sockets.TcpClient class to accomplish it. Below is the simple statement to get the Port status.

$tcp = New-Object System.Net.Sockets.TcpClient

$tcp.connect(“HOST1″ , 1234 )


The above results as blank where connection is successful, otherwise, you get an error message.


Thursday, April 2, 2015

#50 : How to check with Powershell that URL is responsive or not?

You can write script in Powershell to check the status of certain URL (Uniform Resource Locator). In some cases, we may need to monitor if certain intranet application is working or not. Sometimes SQL Server Reporting services are required to be checked if URL is responsive.



To use it, you may call the function like below :

Check-URL "http://yourapplicationname.com"


That’s it! You are done and nothing more is required.

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