Friday, September 28, 2012

Shellshocked! - Powershell basics

This is a basic FAQ, reference table, cheat sheet, dummies guide, whatever you want to call it for Microsoft Powershell.


I started using Powershell regularly recently at my current assignment at a company that does Business Intelligence and only use Windows based systems.  I decided to document my recently acquired knowledge for my own good and I thought that maybe it'll be help to someone else out there. This is by no means a complete reference to Powershell, it's just a collection of the stuff I use the most. And I'll be adding more and more to it as time progresses.
If you spot any errors or can suggest improvements please let me know.

Running Scripts

You might get an error the first time you try to run a powershell script on a new computer, the error you get will look something like this.
File C:\scripts\test.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.
To fix this you need to open Powershell in Administrator mode and run
Set-ExecutionPolicy RemoteSigned
Now it should be possible to run your scripts.

Commands

Create Directory
Let's say we want to create a folder called "Appname" in our Apps folder.
new-item C:\ProgramData\Corp\Apps\Appname -itemtype directory

Wait for input
If you want user input you can use Read-Host
$a = Read-Host "Press enter to End"

Write to Screen
Write-Host "Hello World"

Download file from Internet
Want to download something from the web? No problem. Create a Webclient object and use DownloadFile.
$webclient = New-Object System.Net.WebClient
$url = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhspnpZGK25blu0_PtvwrljVqhr7cMKHk30jlTLniStMgmlhIjx5UmnIsU93QBrX0kXXa2xFNlZds9NVM3TnPmxn7BSj0QctDlwKrz3ziAEmMMzQGu1qgc1FfroTDuwlpAwBb17D_HjdqY/s220/jonas_bw.jpg"
$file = "good_looking_guy.jpg"
$webclient.DownloadFile($url,$file)
>> WebClient at MSDN

Fun Trivia 

When writing this Google's Chrome gave me a typo warning for "Powershell" and suggested "Powers-hell". Coincidence? :)