Tag: PowerShell

  • Visual Basic/PowerShell interaction

    Through the .NET Framework, Visual Basic can talk to PowerShell. If PowerShell is installed, you can add a reference to an assembly named System.Management.Automation. You will have to browse for it, and you will find it here:

    C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0

    Also, scripting needs to be activated in PowerShell.

    A RunSpace is a context where PowerShell scripts run. Any variables that are set in one runspace, can be read from that same runspace, but not any other runspace. Before the opening Using, I will create a variable (Result) that will hold the response from PowerShell.

    Dim Result As _
       System.Collections.ObjectModel.Collection(Of System.Management.Automation.PSObject)
    
     Using R As System.Management.Automation.Runspaces.Runspace = _
       System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()

    Next, you open the runspace and create a pipeline.

    R.Open()
    Dim P As System.Management.Automation.Runspaces.Pipeline = R.CreatePipeline()

    The pipeline has a Commands collection where you add your commands or complete scripts. These two lines will create two output objects.

    P.Commands.Add("C:\test.ps1")

    When you’re done, you can execute the script using the Invoke function of the pipeline object, and close your runspace. The response is saved in the Result variable I created earlier.

    Result = P.Invoke()
    R.Close()
    End Using
    
    For Each Res As System.Management.Automation.PSObject In Result
       MessageBox.Show(Res.ToString())
    Next

    The content of my script file, test.ps1, is:

    Write-Output "Hello!"
    $x = 10 + 3
    Write-Output $x

    The output of course will be one message box saying Hello! and another saying 13.

  • Easy archiving of files using PowerShell

    This example shows easy compressing and archiving of files using the WindowsBase library and PowerShell. This code will use the WindowsBase library to create a ZIP archive from a couple of images. In this example, I am working in the C root, and the files I want to add to my ZIP archive are also located there.

    #Load some assemblys. (No line break!)
    [System.Reflection.Assembly]::Load("WindowsBase,
       Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
    
    #Create a zip file named "MyZipFile.zip". (No line break!)
    $ZipPackage=[System.IO.Packaging.ZipPackage]::Open("C:\MyZipFile.zip",
       [System.IO.FileMode]"OpenOrCreate", [System.IO.FileAccess]"ReadWrite")
    
    #The files I want to add to my archive:
    $files = @("/Penguins.jpg", "/Lighthouse.jpg")
    
    #For each file you want to add, we must extract the bytes
    #and add them to a part of the zip file.
    ForEach ($file In $files)
    {
       $partName=New-Object System.Uri($file, [System.UriKind]"Relative")
       #Create each part. (No line break!)
       $part=$ZipPackage.CreatePart($partName, "application/zip",
          [System.IO.Packaging.CompressionOption]"Maximum")
       $bytes=[System.IO.File]::ReadAllBytes($file)
       $stream=$part.GetStream()
       $stream.Write($bytes, 0, $bytes.Length)
       $stream.Close()
    }
    
    #Close the package when we're done.
    $ZipPackage.Close()

    Now, my image files are archived to one ZIP file.

  • Reacting to user input

    Continued from here.

    The concept of events is that when a GUI component (a “control”) reacts on something like user actions, the control has the power to inform anyone who wants to know about that action. This is the event system of the .NET Framework. Thanks to delegates, the component can have a PowerShell function invoked. I want to add a button to my form, and then, I want a function to be called when the button is clicked.

    To start, before the ShowDialog call, I create a button and add that to the form.

    #Addition: Create a button and add it to the form.
    $myButton=New-Object Windows.Forms.Button
    $myButton.Text="Click me!"
    $myButton.Location=New-Object Drawing.Point(200,60)
    $myForm.Controls.Add($myButton)

    Now, before we add the function that will be called when the button is clicked, we need to add code to register events. In C#, we can add delegates to a list and in Visual Basic, we can call a member function for this. In PowerShell, there are a few steps that must be taken. Get an event reference, create a delegate and connect a function. The MSDN blogger Brett Ernst has written a function for this, that I add to my script.

    This function takes the object we want to listen to, the name of the event that will cause our function to be called, and the actual function that will be called.

    #Addition: Brett Ernst's function for adding an event handler.
    function AddHandler([object]$target,[string]$eventName,$script)
    {
    $evt = $target.GetType().GetEvent($eventName)
    $eh = [EventHandler]$script
    $del = [Delegate]::CreateDelegate($evt.EventHandlerType,$eh.Target,$eh.Method)
    $evt.AddEventHandler($target,$del)
    }

    This is my function. It extracts the user input from the text field and displays it in a message box.

    #Create the target function.
    $myHandler={
    
    #Exctract the user text from the text field.
    $userInput=$someField.Text
    
    #Show the text in a messagebox.
    [Windows.Forms.MessageBox]::Show($userInput)
    }

    This is the final row that I add before the existing ShowDialog call. It uses the AddHandler function to connect my function with the Click event of the button.

    #Event handling: Connect a function to a control event.
    AddHandler $myButton "Click" $myHandler

    This is the complete code:

    #Remenber: No line break here!
    [System.Reflection.Assembly]::Load("System.Windows.Forms, 
    Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    
    $myForm=New-Object Windows.Forms.Form
    $myForm.Size=New-Object Drawing.Size(360,200)
    $myForm.Text="Using Windows GUI from PowerShell"
    
    $someLabel=New-Object Windows.Forms.Label
    $someLabel.AutoSize=$true
    $someLabel.Text="Enter your name:"
    $someLabel.Location=New-Object Drawing.Point(10,10)
    
    $someField=New-Object Windows.Forms.TextBox
    $someField.Size=New-Object Drawing.Size(300,16)
    $someField.Location=New-Object Drawing.Point(10,30)
    
    $myForm.Controls.Add($someLabel)
    $myForm.Controls.Add($someField)
    
    #Addition: Create a button and add it to the form.
    $myButton=New-Object Windows.Forms.Button
    $myButton.Text="Click me!"
    $myButton.Location=New-Object Drawing.Point(200,60)
    $myForm.Controls.Add($myButton)
    
    #Addition: Brettern's function for adding an event handler.
    function AddHandler([object]$target,[string]$eventName,$script)
    {
    $evt = $target.GetType().GetEvent($eventName)
    $eh = [EventHandler]$script
    $del = [Delegate]::CreateDelegate($evt.EventHandlerType,$eh.Target,$eh.Method)
    $evt.AddEventHandler($target,$del)
    }
    
    #Create the target function.
    $myHandler={
    
    #Exctract the user text from the text field.
    $userInput=$someField.Text
    
    #Show the text in a messagebox.
    [Windows.Forms.MessageBox]::Show($userInput)
    }
    
    #Event handling: Connect a function to a control event.
    AddHandler $myButton "Click" $myHandler
    
    $myForm.ShowDialog()

    And this is the result:

    And now I take a two week vacation from blogging. I will have guests from the other side of the planet, and I will work with my podcast during their stay.

  • Using the Graphical User Interface

    If you are doing this as a script, you must have given yourself the permission execute scripts.

    To start, you must load the library that holds the classes that are used for GUI programming. Remember, you cannot do a line break here. I only do it so that the whole line will visible.

    [System.Reflection.Assembly]::Load("System.Windows.Forms,
    Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")

    (Again, the above code is one single line.)

    If you are unsure about versions and public keys, check your assembly folder in your Windows folder. If you right click on an assembly, and open the Properties dialog. There you highlight and copy the assambly information.

    When the assembly is loaded, you can create a Form. This code will give it a caption and a size.

    $myForm=New-Object Windows.Forms.Form
    $myForm.Size=New-Object Drawing.Size(360,200)
    $myForm.Text="Using Windows GUI from PowerShell"

    The next thing I want to do, is to add a text label and a text input fileld on my form. I will position the text field under my label field.

    $someLabel=New-Object Windows.Forms.Label
    $someLabel.AutoSize=$true
    $someLabel.Text="Enter your name:"
    $someLabel.Location=New-Object Drawing.Point(10,10)
    
    $someField=New-Object Windows.Forms.TextBox
    $someField.Size=New-Object Drawing.Size(300,16)
    $someField.Location=New-Object Drawing.Point(10,30)
    
    $myForm.Controls.Add($someLabel)
    $myForm.Controls.Add($someField)

    To show this form, call the ShowDialog function of the form object.

    $myForm.ShowDialog()

    This is the result:

    The next thing to do, is to react on user input.

  • There is nothing that can’t be done with PowerShell

    Basically, what makes PowerShell a so much better command line shell and scripting language than its competitors, is that you can do anything and everything. If you want to create scripts, you must give yourself permission to do so (shown here). In addition, if you are using Windows 7 or later, you must start PowerShell as an administrator to be able to give yourself permission to run scripts.

    The secrets behind the versatility of PowerShell is the power of the syntax, excellent type management, and access to both COM components and the .NET Framework. My twitter example is really just an example of accessing the .NET Framework from PowerShell. I could just as well have shown how to convert a JPG image to PNG, which by the way could be done like this:

    #Load the Drawing library (no Enter strokes here):
    [System.Reflection.Assembly]::Load("System.Drawing, Version=2.0.0.0, 
    Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    
    #Load a JPG.
    $img=New-Object System.Drawing.Bitmap("C:\Anders\mypicture.jpg")
    
    #Save the desiered format in a variable.
    $format=[System.Drawing.Imaging.ImageFormat]::Png
    
    #Save as PNG.
    $img.Save("C:\Anders\converted.png", $format)
    
    #Delete the object.
    $img.Dispose()

    So, let’s say that you want to access a COM object from PowerShell. You would still use the New-Object, but you append the -ComObject argument. This gives me a handle to Excel (if you have it installed):

    $xl=New-Object -ComObject Excel.Application

    Now, you have state of the art spread sheet automation at your fingertips. You can display it like so:

    $xl.Visible=$true

    How about that!?

  • Checking a twitter feed using PowerShell

    To check a twitter feed using PowerShell, you must have an URL to an XML feed (probably RSS). Open the web site of the account you’re interested in (http://www.twitter.com/username/) and find the RSS link. Mine is http://twitter.com/statuses/user_timeline/33177615.rss.

    You can load the URL into a variable like so:

    $url="http://twitter.com/statuses/user_timeline/33177615.rss"

    Then, the Net assembly must be loaded. Use the Load function of the System.Reflection.Assembly class (without inserting any Enter strokes).

    [System.Reflection.Assembly]::Load("System.Net, 
    Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

    If you’re not sure about public key token or version, check you assembly folder in your Windows installation folder. Next, you create a web client from the assembly that you just loaded.

    $wcli=New-Object System.Net.WebClient

    Use the OpenRead function of the web client to acquire a web stream.

    $s=$wcli.OpenRead($url)

    Use the stream object to create a stream reader.

    $r=New-Object System.IO.StreamReader($s)

    To save the result stream data in a variable, call the ReadToEnd function of the reader. You then have to close the reader and destroy the web client.

    $response=$r.ReadToEnd()
    $r.Close()
    $wcli.Dispose()

    You can just type the name of the variable to see its content.

    $response

    You should now see my twitter feed!

  • Getting started, part 3 of 3

    Getting started, part 3 of 3

    About providers and cmdlets: If you just start PowerShell and use these cmdlets, they are for file management.

    The Add-Content cmdlet can create a file if it doesn’t exist, and append information to that file. If you execute the following line, you will get a new file in your C root called MyFile.txt.

    Add-Content “C:\MyFile.txt” “This is new content.”

    The file will contain one line of text (the second parameter). If you run the same command again, the file will contain two lines. If the file exists, information is appended.

    There is also a set of commands that can be used to manage files. Your new created file can be moved using the Move-Item cmdlet. Just specify the source and the destination:

    Move-Item “C:\MyFile.txt” “D:\MyDestination.txt”

    The Copy-Item cmdlet works in the same way, but leaves the original file.

    If you don’t want to use absolute paths, you can type Get-Location to find the current directory. Set-Location (or CD for short) changes the current directory.

    But again, the reason these cmdlets are used for file management, is that the underlying provider is a FileSystem provider. To see the available providers, type Get-PSProvider. If you change provider from FileSystem to Registry, the cmdlets will be used to manipulate the registry instead of the file system. To change provider to Registry, type:

    Set-Location HKLM:

    Now, try the Get-Location cmdlet again. This time, it will give you a location in the registry instead of a location in the file system. If you wonder what happened here, type Get-PSDrive. Now you can see what providers are mapped to what drives. The Get-Location cmdlet is used to select an available drive. The provider associated with the drive will also be selected. If you want to use the file system again, just type Set-Location C: (since C: is associated with the FileSystem provider).

  • Getting started, part 2 of 3

    Getting started, part 2 of 3

    When you know about cmdlets and how to get help on them, the next thing is to learn how to use the window.All commands you type in are saved in the command buffer. The keys you use to access the buffer is:

    – [Up] for the previous command in the buffer
    – [Down] for the next command in the buffer
    – [PgUp] for the first and [PgDn] for the last command in the buffer

    If you want to move the cursor on the line you are editing for the moment, [Left] and [Right] moves the cursor sideways, [Home] takes you to the first character of the line and [End] takes you to the last one. If you hold [Ctrl] while pressing [Left] or [Right], you move one word at a time, instead of one character.

    The [Tab] key is used to auto-complete a word. For example, if you type Write-O and press [Tab],Write-O will be replaced with Write-Output. To pick a command from the buffer, press [F7].

    If you want to execute a script, you can create a text file that contains your commands, and execute that, just by entering the scripts path and name. If you want to execute a script (a text file with a ps1 ending) in the directory you’re currently in, and the script file name is “myscript.ps1”:

    .\myscript.ps1

    PowerShell might complain about the script not being signed. You can remove the requirements for signing by executing this command:

    Set-ExecutionPolicy Unrestricted

    To test this, create a new text file, type in any commands, for example:

    $x=”Sven”
    Write-Output $x

    Then save it with ps1 file ending, and execute it, just by typing the path and the name of the file.

  • Getting started, part 1 of 3

    Getting started, part 1 of 3

    First of all, your old commands that you used in cmd.exe still work. You have to be a tiny bit stricter in syntax. For example, when you navigate to the parent folder in cmd.exe, you could write:

    cd..

    In PowerShell, you have to add a space between cd and .., but if you do that, it will work fine.

    cd ..

    Then, when you approach the new commands (cmdlets) in PowerShell, it might be good to know how to get help. To get a list of all available cmdlets, type Get-Command:
    Programmen (cmdlet) i Powershell har namn som består av ett verb, ett bindestreck och ett substantiv, t.ex. Write-Progress. För att få en lista över alla cmdlets, skriv:

    Get-Command

    All cmdlets have name that consists of a verb and a noun. You should see a list of all cmdlets. If you know the verb, and want to see what available cmdlets that begins with that verb, you add the argument -Verb followed by the actual verb. For example, if you want to see a list of all cmdlets that begin with the verb Move, type:

    Get-Command –Verb Move

    You now see a list with all cmdlets that begin with the verb Move (Move-Item, Move-ItemProperty).
    To get help on a specific cmdlet, type Get-Help followed by the cmdlet. Example:

    Get-Help Move-Item

    Add the parameter -detailed for a deeper description, or -full for the complete documentation on the cmdlet. This will tell you all there is to know about Move-Item:

    Get-Help Move-Item –full