Emil’s Blog

Programming Windows, .Net, EPiServer and whatnot…

[Powered by WordPress.]

January 21, 2010

Script parameter parsing in PowerShell

by @ 14:32. Filed under PowerShell

This is an example of how to do script parameter parsing in PowerShell:

switch ($args)
{
  'salesforceservice'
  {
    $deploy_service = $true
  }

  'web'
  {
    $deploy_web = $true
  }

  default
  {
    "Bad parameter: " + $_
    ShowHelp
    exit
  }
}

Pretty neat, huh?

/Emil

September 30, 2009

Working with cultureinfo in PowerShell

by @ 13:17. Filed under .Net programming, PowerShell

As a simple example of working with culture information in PowerShell, here's how to list Swedish monthnames:

(new-object system.globalization.cultureinfo("sv-SE")).DateTimeFormat.MonthNames

The result is an array:

januari
februari
mars
april
maj
juni
juli
augusti
september
oktober
november
december

Try doing that in a BAT file... :-)

/Emil

September 14, 2009

Powershell script to kill long-running processes

by @ 10:02. Filed under PowerShell

Here's a small script to kill all Word or Excel-processes that have been running for more than 5 minutes. This can be useful on a server that launches those applications to generate documents. You probable shouldn't do it that way but if you do you're likely to discover that the processes don't always terminate as they should. In those situations, scripts like this come in handy.

$startTimeLimit = (get-date) - (new-timespan -minutes 5)
$processes_to_kill = get-process |
    where {$_.StartTime -lt $startTimeLimit -and ($_.path -like "*winword.exe" -or $_.path -like "*excel.exe") }
if ($processes_to_kill -ne $null)
{
    $processes_to_kill | foreach { $_.Kill() }
}

/Emil

May 4, 2009

Using PowerShell for login scripts (HTTP POST)

by @ 19:52. Filed under PowerShell

Here's a small example of how to use PowerShell to pretend it's a web browser to login to a service. In my case it's used to let my computer get access to a customer's network, but it could also be used to login to other services, such as public WiFi services, etc. It also serves as an example of how to do a HTTP POST operation in PowerShell, something that can be very useful in many situations.

param($username=($env:username), $password=$(throw "The 'password' parameter is required!"))

$nvc = new-object System.Collections.Specialized.NameValueCollection
$nvc.Add('username',$username)
$nvc.Add('password',$password)
$wc = new-object net.webclient
[void] $wc.UploadValues('http://123.123.123.123/loginuser', $nvc)

The code is very simple:

I think simple examples like this really shows the potential of PowerShell and that making .Net types so easily accessible in the language was a really smart design desicion by the language designers.

/Emil

Calling a PowerShell script from a Windows shortcut

by @ 19:35. Filed under PowerShell

Executing a PowerShell script from outside PowerShell (for example via a Windows shortcut) can be a little complicated, especially if the path to the script contains spaces and it has parameters, so here's how to do it:

powershell.exe -command "& 'C:\A path with spaces\login.ps1' -password XXX"

Note that I'm using the PowerShell & operator to execute the script. This is because I have to surround the path with quotes so that it's interpreted by PowerShell as a single literal even though it contains spaces. If I would leave out the "&" then the quoted string would simply be interpreted as a string literal to output, so the script would not be executed.

The parameters to the script should not be included within the single quotes since they are not part of the first literal, which should only contain the path to the script to execute.

/Emil

April 22, 2009

Working with remote Windows services in PowerShell

by @ 20:01. Filed under PowerShell

Here's how to list, start and stop Windows services on a remote computer using PowerShell:

[reflection.assembly]::loadwithpartialname("System.ServiceProcess")

# List all services on the remote computer
[System.ServiceProcess.ServiceController]::GetServices('10.123.123.125')

# Stop the service and wait for it to change status
$service = (new-object System.ServiceProcess.ServiceController('Service name','10.123.123.125'))
$service.WaitForStatus('Stopped',(new-timespan -seconds 5))
$service.Stop()

# Start the service again
$service.Start()

This can come in really handy in deployment scripts, etc.

(Parts of this post came from The PowerShell Guy).

/Emil

Update: In the earlier version of this post I used new-object every time I needed a reference to the service. That's not necessary, it's much prettier to use a variable for the reference, so I have now updated the code.

April 16, 2009

Working with .Net assemblies in PowerShell

by @ 21:29. Filed under PowerShell

It's quite easy to load and use .Net assemblies in Windows PowerShell, which of course is one of the main selling points of the script language. In this post I'll show a few examples.

Listing all loaded assemblies:

PS> [AppDomain]::CurrentDomain.GetAssemblies()

GAC    Version        Location
---    -------        --------
True   v2.0.50727     C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\Microsoft.PowerShell.Conso...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System\2.0.0.0__b77a5c5619...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System.Management.Automati...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System.Configuration.Insta...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\Microsoft.PowerShell.Comma...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\Microsoft.PowerShell.Secur...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\Microsoft.PowerShell.Comma...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System.Management\2.0.0.0_...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System.DirectoryServices\2...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_32\System.Data\2.0.0.0__b77a5c5...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System.Xml\2.0.0.0__b77a5c...

To load a new assembly, do the following:

[reflection.assembly]::loadfile('C:\...\bin\Entities.dll')

When an assembly has been loaded, types and code in it can be used with the new-object Cmdlet, for example:

PS> $obj = new-object Entities.Affär
PS> $obj.Affärsnummer = "2323232"
PS> $obj.Kundnamn = "Acme"
PS> $obj

Kundnummer               :
Kundnamn                 : Acme
Organisationsnummer      :
KontaktpersonKund        :
Referens                 :
Affärsnummer             : 2323232
Fas                      :
Betalningsvillkor        :
Status                   : None
Fakturaaddress           :
Fakturor                 : {}
Id                       : 0

PS> $obj.Validate()
Exception calling "Validate" with "0" argument(s): "Affärsnummer: Felaktig data: Affärsnummer skall alltid vara 9 siffror"
At line:1 char:14
+ $obj.Validate( <<<<)

Pretty cool, huh? (BTW, Validate() is a method on the "Affär" class.)

Also note that some command completion works with imported types. For example, if I type "$obj." and then press TAB, then the console will cycle through the available members of the type in question.

There's more to write about this interesting subject, so more posts will come...

/Emil

Windows PowerShell reference (incomplete)

by @ 21:12. Filed under PowerShell

I recently decided to start learning the (fairly) new Windows PowerShell script language and thought it would be useful to write down some of its pecularities. The list below is by no means complete, it's just my own notes when learning the language.

BTW, I'm quite impressed of the power of this script language and will be using it from now on instead of the good old CMD.EXE and BAT files. However, there is a learning curve involved and it's steeper than it could have been. The creators' idea of "elastic syntax" (you can write the same logic in many ways) doesn't exactly help... Thus there is a need for a reference like this one.

Here we go:

Setup
To allow script execution, do this:

Set-ExecutionPolicy RemoteSigned

Virtual drives
More things than files can be accessed using a file system-like method using the virtual drives mechanism.

Example:

dir variable:*

Error handling
PowerShell has a quite powerful error handling arsenal.

Errors can be trapped:

trap { "Something bad happened: " + $_;break } 1/$null

trap { "Something bad happened: " + $_.Exception; break } 1/$null

The first example uses the $_ variable to access the ErrorRecord object of the current error, and the second example displays the underlying .Net exception (including call stack, etc).

The previous errors are stored in the $errors array.

Using the console
Display text in the console (and don't send it down the pipeline):

write-host -fore red -back green "unreadable, colored text"

Send text to stderr:

write-error "my error"

Change the console prompt:

function prompt
{
    "$(write-host -NoNewLine -fore cyan (pwd))> "
}

The prompt function should return a single string.

Special operators

# swap variable values
$b,$c = $c,$b

# array with values 1 through 10
1..10

# read file (or variable) content. NB, no whitespace after "{"!
${c:\boot.ini}

# encapsulate in array if needed
@( "foobar" )

# initialize an empty array
$a = @()

# initialize an array with 1 element
$a = ,1

# initialize an array
$a = 1,2,3

# (assigns elements from the array to variables $b == 1, $c == 2,3)
$b,$c = $a

# retrieves values for index 0 and 2 from an array
$a[0,2]

# retrieves values for index 0 through 2 from an array
$a[0..2]

# expression sequence (all results is merged into an array)
"foo"; "bar"
 
# & - execute script block
$a = { Get-Process | Select -First 2 }
& $a

# . - same as &, but execute in current scope
$x = 2
. { $x = 3 }
$x          # $x is now 3, if we used & instead it would still be 2

# % can be use as a shortcut for the Foreach-Object Cmdlet
1..5 | % { $_ * 3 }

# ? can be used as a syntax shortcut for the Where-Object Cmdlet
1..17 | ? { $_ % 2 -eq 0 }

Hash tables (object imitations)

# initialize hash table
$user = @{FirstName = "John"; LastName="Smith"}

# object property syntax
$user.FirstName = "Mary"

# array syntax
$user["FirstName"] = "Mary"

# all values from the hash table
$user.Values

# all keys from the hash table
$user.Keys

# all values from the hash table using an array as input
$user[$user.keys]

Constants
These are fairly self-explanatory:

Built-in variables

Pattern matching
Wildcard matching (true/false):

"foo bar" -like "f*bar"

Regular expressions (true/false + matching results in $matches):

"foo bar" -match "([a-z]*) ([a-z]*)"; $matches

Output:
True

Name                        Value
----                           -----
2                              bar
1                              foo
0                              foo bar

Discarding output of a command

Any of the following will do the trick:

[void] (dir)
dir | Out-Null
dir> $null

Conditional and looping statements

The switch statement is mighty cool:

switch (3) { 1 {"one"} 3 {"three"} default {$_}}
switch (1..5) { 1 {"one"} 3 {"three"} default {$_}}
switch (1..5) { {$_ -gt 3} { "[$_]" } default { $_} }
switch -wildcard ("one", "two", "three", "four", "five") { t* { "[$_]" } default { $_} }
switch -regex ("one", "two", "three", "four", "five") { ^o.* { "[$_]" } default { $_} }

That's it for now. I will probably extend this posting later as i discover more things that are difficult to remember...

/Emil

[powered by WordPress.]

jour·nal n. A personal record of occurrences, experiences, and reflections kept on a regular basis; a diary.

Internal links:

Categories:

Search blog:

Archives:

September 2010
M T W T F S S
« Jun    
 12345
6789101112
13141516171819
20212223242526
27282930  


View Emil Åström's profile on LinkedIn

General links:

I read:

Visitors

Recent Comments

Spam caught

Other:

Clicky Web Analytics

36 queries. 0.964 seconds