Getting started with Powershell

Posted by – September 4, 2010

Powershell is an awesome scripting language for Windows machines, last Sunday I wrote a small script to gather computer monitor info stored on windows registry, this is one of the possibilities behind the power of powershell, you can do much more than it.

Here’s a sample script:

1
2
3
4
5
6
7
8
[CmdletBinding(DefaultParameterSetName="Name")]
param (
    [Parameter(Mandatory = $TRUE, ParameterSetName="Name", HelpMessage="Your name")]
    [String]
    $Name
)

write-output "Hello $Name"


The lines 1 to 6 contains script parameters definitions, this script has only one parameter, called “Name”, once parameter is defined we can now print its value on line 8, we can write to standard output by calling write-output.

Working with files:

With cmdlets you can easily manipulate files, the following script gives an idea about how you can test if a file exists and how to write content on it.

1
2
3
4
5
6
7
8
9
10
11
$file = "$env:userprofile\Desktop\User.csv"
$header = $false
$file_exists = test-path $file
   
If(! $file_exists) {
    $header = $true
}
   
if($header) {
        "Name,City,Country,Phone" > $file
}

In the first line we are setting the file location, in the third line we are calling the test-path cmdlet, we use this cmdlet to test if the file exists at this path, if the path doesn’t exists it means that we will create it and set the header in the first line. The line 10 shows how we can reset the file and print the string into first line of the file.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>