Tuesday, May 19, 2009

3 reasons for using PowerShell

I wish to learn PowerShell as Windows finally has a great shell making it possibile to automate tasks that are long winded using the GUI.

Here are three very simple task which were hard to achieve using the MS-DOS shell.

Connect to UNC paths

To browse a network share in cmd.exe you first had to map a drive. With PowerShell you can navigate to server shares as you would a local drive.

set-location \\\\servername\sharename
view raw example1.ps hosted with ❤ by GitHub

Easy to recurse folders and files

While it is possible to recursively delete files in cmd.exe, PowerShell has built in support for the ** operator making operations on sets of files very simple. For an example, the following will delete all files with the extension .bak from the C:\temp and all folders within it.

remove-item c:\temp\**\*.bak
view raw example2.ps hosted with ❤ by GitHub

Controlling remote servers

Often I have to administer a service on a remote machine, a recent example is starting the W3SVC on a server which kept failing. As PowerShell has access to the Windows Management Interface API I can run this command instead of using IIS manager over Remote Desktop

(Get-WmiObject -computer servername Win32_service -Filter "Name='W3SVC'").StartService()
view raw example3.ps hosted with ❤ by GitHub

In fact PowerShell finally provides a useful wrapper around those rich but hard to get at WMI APIs. The following script will enumerate all websites and display the path to their log file

Get-WmiObject -namespace "root/MicrosoftIISV2" -ComputerName "Server" -Credential "yourname" -Authentication PacketPrivacy -Query "SELECT * FROM IIsWebServerSetting" | select { $_.ServerComment, $_.LogFileDirectory }
view raw example4.ps hosted with ❤ by GitHub

No comments: