Last week I gave a presentation on PowerShell during Wipro internal KM Session. It was for beginners and don’t go into deep. Also the tone of ppt was kept “less technical” as a good percentage of audiences belonged to management or higher level. Thought to post it here. To maintain IP policy I removed 4 slides of presentation as they had reference to my project/Client.
My PowerShell presentation
Lesson of the day: the Common Parameters
Today while developing a PS script, I came across few interesting features of PowerShell. Generally command parameters depends on the cmdlet being used. But there are few parameters that can be used with almost every cmdlet. By design, every cmdlet bound to support them although using them in certain cases won’t produce any output. So what can they do for you? They can override PowerShell preference variables and system defaults for a single cmdlet.
Complete details can be found using get-help about_commonparameters
What I was using in my today’s case, is a “Risk mitigation parameter”’ ‘–confirm’. This parameter prompts user before executing the cmdlet. In my script I wanted to delete few log files that were generated by another part of script. I wanted a prompt for user before deleting the files. Here is the one liner “demo” script for it:
remove-item "Killme.TXT" -confirm:$true
Note that if you check the syntax in the help content of remove-item, you can see [<CommonParameters>] in the last.
Here is the screenshot what you will get from the demo script line.
PowerShell learning of the day
1. It’s best to use environment variables when getting things like the path to the Windows directory, because you can’t always assume that the result is going to be C:\Windows. To get any environment variable’s value, just use $env:<environment variable name>
2. Before you can use a function in Windows PowerShell, you must define it. If you want to define a function in a script, the definition (code) for the function must come before you use it the first time. This rule is especially important to keep in mind if you have some experience with VBScript, because unlike Windows PowerShell, VBScript allows you to define functions anywhere you want within the script.
Working with ‘Files & Folders’ in PowerShell
A fairly good amount of time we spend on our system for managing, searching files, folders. And when you are in learning phase of any new scripting language (just like me, in PS), it is obvious to have an eagerness about “How to” work with files and folder in that Scripting lang. Fortunately, PowerShell makes scripting files and directories as easy as working at the command line. Being an administrative shell, PowerShell directly supports tasks such as visiting all the files in a subdirectory or moving a file from one directory to another.
To retrieve the list of files in a directory, use the Get-ChildItem cmdlet. To get a specific item, use the Get-Item cmdlet:
· To list all items in the current directory, use the Get-ChildItem cmdlet:
Get-ChildItem
· To list all items that match a wildcard, supply a wildcard to the Get-ChildItem cmdlet:
Get-ChildItem *.doc
· To list all files that match a wildcard in the current directory (and all its children), use the –Include and –Recurse parameters of the Get-ChildItem cmdlet:
Get-ChildItem –Include *.doc -Recurse
· To list all directories in the current directory, use the Where-Object cmdlet to test the PsIsContainer property:
Get-ChildItem | Where { $_.PsIsContainer }
· To get information about a specific item, use the Get-Item cmdlet:
Get-Item test.txt
More to come in next post…
PowerShell: Building a Form
(My Article for Weekly PowerShell Column in office e-mag)
Today we learn about a surprising feature of PowerShell: forms. Many people think that PS is just another bro of cmd.exe and can’t do much fun with GUI. Hmmm…they are simply wrong. Since PS is based on .NET platform, it can access any .NET base class easily and Forms are no exception. So let’s try something into it.
Before calling any .NET namespace, we need to load that DLL into PS session. And this can be done with following commands:
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
For creating a form object, try this:
$form1 = New-Object System.Windows.Forms.Form
You can set various properties of form object directly. E.g. Name, text:
$form1.Text = "Ankit Form"
$form1.Name = "form1"
For a button object, try it:
$button1 = New-Object System.Windows.Forms.Button
$button1.Name = "button1"
We will discuss various aspects of forms in coming posts. For now, if you wanna play with some form code, try this PS Code:
function GenerateForm {
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null$form1 = New-Object System.Windows.Forms.Form
$button1 = New-Object System.Windows.Forms.Button
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState$button1_OnClick=
{
[System.Windows.Forms.MessageBox]::Show("Now call Police!")}
$OnLoadForm_StateCorrection=
{
$form1.WindowState = $InitialFormWindowState
}$form1.Text = "Ankit Form"
$form1.Name = "form1"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 284
$System_Drawing_Size.Height = 262
$form1.ClientSize = $System_Drawing_Size$button1.TabIndex = 0
$button1.Name = "button1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 104
$System_Drawing_Size.Height = 35
$button1.Size = $System_Drawing_Size
$button1.UseVisualStyleBackColor = $True$button1.Text = "Kill me!"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 89
$System_Drawing_Point.Y = 102
$button1.Location = $System_Drawing_Point
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.add_Click($button1_OnClick)$form1.Controls.Add($button1)
$InitialFormWindowState = $form1.WindowState
$form1.add_Load($OnLoadForm_StateCorrection)
$form1.ShowDialog()| Out-Null
}
#Call the Function
GenerateForm
Challenge of the Month!!
C# in PowerShell
In today’s training session, learned about how to mix-up C# with PowerShell. An Example here:
Add-Type -Typedefinition @"
using System;
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
public class Program
{
public static void Main(string[] args)
{
String[] items = new String[] { "Joe", "John", "Jimmy", "Jerr" };
int totallenght =0;
foreach(String item in items)
{
totallenght+= item.Length;
}
Console.WriteLine("the total is {0}",totallenght);
}
}
}"@
[ConsoleApplication1.Program]::Main($null)
Interestingly, the whole action of the above code can be done through this smaller (Only) PowerShell code too:
function list {$args}
$totallenght = 0
list Joe John Jimmy Jerry | foreach { $totallength+= $_.Length }
"the total is $totallength"
Toy Code: Dictionary in PowerShell
Note: The Code given here uses Google Dictionary for word definition. Its just a toy…
$Word= Read-host "What is your Word? "
$url = "http://www.google.com/dictionary?langpair=en|en&q=" + $Word
$ie = New-Object -com internetexplorer.application;
$ie.visible = $false;
$ie.navigate($url);
while ($ie.Busy -eq $true)
{
Start-Sleep -Milliseconds 1000;
}
$text = $ie.document.body.innertext
$atpos=$text.IndexOf("Synonyms")
if ($atpos -gt 0){
$len=$text.Length -$atpos
$result=$text.Substring($atpos,$len)
$atlast= $result.IndexOf("Web definitions")
$mean= $result.Substring(0, $atlast)
Write-Host $mean
}
else { Write-host "Dictionary:: not found"}
Childproofing PowerShell
Safe way to play with PowerShell!!
http://powershell.com/cs/blogs/tips/archive/2010/01/11/childproofing-powershell.aspx
Pipelining Implementation is Different in PowerShell & old CMD
Unlike the Old CMD, Windows PowerShell doesn’t pass text between commands; it passes objects. This arrangement is significant because the receiving command can access the various attributes of the object directly, rather than trying to parse out strings to interpret the data.