Feeds:
Posts
Comments

Posts Tagged ‘powershell’

Blog has moved! You should check this post out on kevinpelgrims.com

Since I had fun using the Bing Maps API in C# (see Bing Maps – Geocoding and Imagery), I decided to try and do the same in PowerShell. This didn’t seem to be very hard either, as it’s possible to use the same objects as you would in a regular .NET application. Go PowerShell!
The only difference is the web service trick on the second line.

$key = "apikey";
$ws = New-WebServiceProxy -uri http://dev.virtualearth.net/webservices/v1/geocodeservice/geocodeservice.svc?wsdl;
$wsgr = New-Object Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy1ervice_geocodeservice_svc_wsdl.GeocodeRequest;

$wsc = New-Object Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy1ervice_geocodeservice_svc_wsdl.Credentials;
$wsc.ApplicationId = $key;
$wsgr.Credentials = $wsc;

$wsgr.Query = 'Brussels, Belgium';
$wsr = $ws.Geocode($wsgr);

$wsr.Results[0] | select {$_.Address.FormattedAddress}, {$_.Locations[0].Longitude}, {$_.Locations[0].Latitude};

When you execute this in PowerShell, it looks like this:

Geocoding in PowerShell

Things like this make you think about the power of PowerShell. If you can do it in .NET, you can do it in PS!

Read Full Post »

PowerShell Script Commander

Blog has moved! You should check this post out on kevinpelgrims.com

I wrote this entry last year September, but for several reasons the post and the code never made it to the interwebs. After running into it again I decided to post it anyway and upload the code to Codeplex. So, here goes!

A while back I created this PowerShell script to remotely manage services (see Remote Service Manager), a bit later I made the available help a bit more professional (see Add help to your own PowerShell scripts). Now I was thinking it would be cool to create an interface in .NET for this script. So I started developing a WinForm application around the script. Initially, it looked like this:

This was the first (working) prototype of the RSM-GUI. But then I started thinking it would be much cooler to create an application that can run all scripts, even those with parameters. I started thinking about how to do this and actually it didn’t seem so hard. I started by creating a form that can execute simple PowerShell commands and show the output, then added support for running scripts stored on the hard drive. For the parameters I just made sure they are all displayed in a grid, where you can give them a value by simply typing something in. And that was it! I now have a Windows application that can run scripts on a more visual way. Now you can simply load the script with an OpenFileDialog and see what parameters are available. If you still don’t fully understand how the script works, you can press the Get-Help button to display the help information in the outputbox.

And now, it looks like this:

PowerShell Script Commander help function

PowerShell Script Commander running the RSM script, with parameters

A lot of work needs to be done to make this more reliable and to make it work with all scripts on the planet 😉 But I think it’s already pretty cool.

The source code can be found here: http://pscommander.codeplex.com/

Read Full Post »

Blog has moved! You should check this post out on kevinpelgrims.com

A while ago I created a script to manage services on a remote server (see Remote Service Manager). Included in that script was a way to display some information with the use of a switch (-help). A few days later I was wondering if there wasn’t a better way to include help in own PowerShell scripts. And of course there is! It’s even in the help files.

So, here’s what to do. First, check the information in PowerShell help by running following command:

Get-Help about_Comment_Based_Help

There we can see this help thing will be pretty straightforward to implement. Here’s what it says:

The syntax for comment-based Help is as follows:

    # .< help keyword>
    # <help content>

-or -

    <#
        .< help keyword>
        < help content>
    #>

So, this means we just have to make a comment block, with some specific keywords. Cool. So, what are the right keywords?  They’re also in the help. Here’s a small list of the most important stuff:

  • .SYNOPSIS
  • .DESCRIPTION
  • .PARAMETER <Parameter-Name>
  • .EXAMPLE
  • .NOTES
  • .LINK

For more details and a complete list of keywords, I suggest you look at the help in PowerShell. Here is a little example of how we’re going to put this to work:

<#

.SYNOPSIS
This is a simple Powershell script to explain how to create help

.DESCRIPTION
The script itself will only print 'Hello World'. But that's cool. It's main objective is to show off the cool help thingy anyway.

.EXAMPLE
./HelloWorld.ps1

.NOTES
Put some notes here.

.LINK
https://kevinpelgrims.wordpress.com

#>

Write-Host ‘Hello World!’

There, that’s all there is to it. I wish I looked at that before I made the RSM script 🙂 It adds some kind of professionalism to a script, don’t you think? And also, it’s intuitive for users to use the Get-Help command. Everyone is happy! Below is a screenshot of our own help.

Read Full Post »

Blog is moving! You should check this post out on kevinpelgrims.com

This is the last part (of four) in a series of articles on the new features in PowerShell 2.0. Last time we discussed modules, now it’s time for remoting!

Remoting

One of the coolest new features is remoting. It is kind of like running remote desktop in command line. Altough it’s an important piece of PowerShell 2.0, there’s not a lot to explain about this. It’s all pretty easy to use.

What’s fun is that we have the option of executing one command on different remote computers at the same time. This will save system administrators a lot of time. To demonstrate this consider following command:

Invoke-Command -ComputerName Server1 -scriptblock {Get-Service}

This gets all services from Server1. To run this on multiple servers we just adjust the command:

Invoke-Command -ComputerName Server1, Server2, Server3 -scriptblock {Get-Service}

Now we get all services from Server1, Server2 and Server3 in a really easy way.

Another way to use remoting is by connecting to a remote session with Enter-PSSession. You type commands in your local console, but everything is executed on the remote machine. Until you leave the remote session, by using Exit-PSSession.

PS D:\ProjectsPS> Enter-PSSession -ComputerName Server1

PS Server1> Get-Process powershell

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
547       8    95660       8852   199     6,84   5136 powershell

PS Server1> Exit-PSSession
PS D:\ProjectsPS>

Of course, there are a lot of other commands available, so for the last time I will tell you to use the PowerShell 2.0 help: Get-Help about_PSSessions. Much can be learned from the official documentation (yes, it’s really good!).

And another good resource is of course Technet, where all the available cmdlets are explained in a more readable manner (see resources).

So that’s all for today folks! I hope you learned some things that will be useful in future projects.

Recources

A list of resources on the discussed topics:

Read Full Post »

Blog is moving! You should check this post out on kevinpelgrims.com

This is part three of four in a series of articles on the new features in PowerShell 2.0. Last time we discussed transactions, now it’s time for modules!

Modules

A module is a package that contains a bunch of PowerShell commands, like cmdlets, functions, variables, ..

This can be very useful when sharing your code with others, or deploying it to different servers. Think of a module as kind of an assembly for PowerShell.

Consider the next piece of code:

function Add {
  if(!(Test-Path variable:script:count)) { $script:count = 0 }
  $script:count++
  "We add one and the total becomes {0}!" -f $script:count
}

function Substract {
  if(!(Test-Path variable:script:count)) { $script:count = 0 }
  $script:count--
  "We substract one and the total becomes {0}!" -f $script:count
}

function SetCount($value) {
 $script:count = $value
}

# Export only the Add and Substract functions, not SetCount.
Export-ModuleMember Add, Substract
# End of Script

This is our module. Now what do we do with it? To deploy this module we just need to create a new folder in C:\Users\username\Documents\WindowsPowerShell\Modules\ and put our files in there. I’ll call this file Calculatron.psm1 and create the folder Calculatron at the Modules root.

All we need to do now is import the module by calling Import-Module and then we can use the new functions we created! They even become available in the tab command completion (you know what I mean, type “subs” and press the tab button).

Now you can use this awesome power to do some fun stuff and make your scripts easily reusable.

Recources

A list of resources on the discussed topics:

Read Full Post »

Blog is moving! You should check this post out on kevinpelgrims.com

This is part two of four in a series of articles on the new features in PowerShell 2.0. Last time we discussed background jobs, now it’s time for transactions!

Transactions

When you run scripts, generally, three things can happen:

  • The script runs, my favorite
  • The script fails, this is not cool, but you can probably fix it
  • The script runs only partially and dies unexpectedly in the middle of executing stuff. This is very bad and this is probably not what you want.

PowerShell 2.0 has the solution: transactions. They can help you to solve these issues and make sure the script just succeeds, or fails, but nothing inbetween.

Starting a transaction is pretty easy with the Start-Transaction command, but it doesn’t magically fix everything. You still have to use the -UseTransaction switch on your regular commands. Commands that use this switch will run inside the scope of the transaction, those who don’t will run on the outside. To commit the results of the transaction, use Complete-Transaction. If there is something wrong and you need to undo the changes, call Undo-Transaction. A little transactionsdemo in the new Microsoft PowerShell ISE:

This small script creates a transactionscope and creates a string object. Then we append some text to it twice. Once out of the transactionscope, the second time inside of the transactionscope. When we do a ToString(), we see that the text that is appended inside of the transaction is not visible at this point. This is kind of normal, because the transaction is not yet completed. Then we complete the transaction and do a ToString() again, and we can see the second text too.

Again, use the power of the shell for more info: Get-Help about_Transaction

Recources

A list of resources on the discussed topics:
I already told you about a few cool new features in PowerShell 2.0, now it’s time to play with them. I’ve divided one large article into four small ones, to make it a bit more readable. We’ll start with background jobstransactions and modules and end with remoting. These will become very useful for the PowerShell master.

Read Full Post »

Blog has moved! You should check this post out on kevinpelgrims.com

I already told you about a few cool new features in PowerShell 2.0, now it’s time to play with them. I’ve divided one large article into four small ones, to make it a bit more readable. We’ll start with background jobstransactions and modules and end with remoting. These will become very useful for the PowerShell master.

Background jobs

What do these things do again? Background jobs are commands that run asynchronously. When you run a background job, the command prompt returns immediately, even if the command is still running.
Background jobs can be really useful to run complex commands on the background, while continuing some other work. Let’s see how this works and start off with the commands, it’s actually pretty easy.

The basic (and most important) commands are Start-JobGet-Job and Stop-Job. A small demonstration:

As you can see, Start-Job starts a background job (surprise, surprise!) and shows us some info of the newly created job.

In the small script above I created a command that would normally pause the execution of it for 30 seconds. Now, because of the use of a background process we can immediately continue our work, while the first piece of script keeps running in the background.

Get-Job gets a list of running or completed jobs in the current session, as you probably expected. Using this command we also get a lot of useful information, like state and command of the job.

Using the Id we can find with the Get-Job command, we can also stop the execution a running job with Stop-Job.

PS D:\ProjectsPS> Stop-Job 3

If we want to get rid of the job completely, we simply remove it:

PS D:\ProjectsPS> Remove-Job 3

What if you want to run a command that returns data? Use Receive-Job!

$job = Start-Job -scriptblock {Get-Process}
Receive-Job -job $job

The Receive-Job command will output the data from the scriptblock used in Start-Job (in this case, a list of processes on the computer).

These are pretty basic uses of background jobs, but it demonstrates how powerful this can be when creating large scripts that have to execute fast. For more information on this topic, use the PowerShell help, it’s all there! Tip: Get-Help about_Jobs

Do try this at home!

Recources

A list of resources on the discussed topic:

Read Full Post »

Older Posts »