Learning Powershell

by Oliver 30. May 2014 21:34

Today, I finally decided that I want to get to grips with PowerShell and have it available in my toolbox for those everyday developer tasks. For a fresh start, I wanted to make sure I'm running the latest and greatest of PowerShell, but how do I find out which version I have installed? What version am I running? Just fire up a PowerShell instance and type $psversiontable or $host.version: PS C:\Windows\system32> $psversiontable Name                           Value ----                           ----- PSVersion                      4.0 WSManStackVersion              3.0 SerializationVersion  CLRVersion                     4.0.30319.18444 BuildVersion                   6.3.9600.16406 PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0} PSRemotingProtocolVersion      2.2 PS C:\Windows\system32> $host.version Major  Minor  Build  Revision -----  -----  -----  -------- 4      0      -1     -1 Actually, when I ran this I didn't have the 4.0 version installed yet. So where did I get it? How to install Powershell 4.0 (the newest version as of mid 2014)? Go here and choose the right link for you: How to Install Windows PowerShell 4.0. That's it. Make use of great tooling: use the ISE Last but not least, especially for those of you who like me are just getting started, make sure you're using the great Integrated Scripting Environment (ISE) that comes bundled with PowerShell: Now, get scripting!

Automatic Deployment of a New Discoverize Portal

by Oliver 11. March 2013 15:02

This is a technical post about how we automatically deploy new portals that will be run by our own portal software discoverize. After filling in and submitting our portal creation form we do the following: Save the entered information into /App_Data/<PortalName>/portal.xml Trigger the TeamCity build through a web request to a specific URL Send an email with the request status or any errors that occurred Display a Thank You page. Now, the TeamCity build configuration that was triggered under 2. does the following: Execute the Powershell script create-portal.ps1 in c:\projects\discoverize create the AppPool Discoverize-Portals if it doesn't exist yet (all our portals run within it) iterate over all folders inside wwwroot\discoverize.com\App_Data if a folder with the same name exists under wwwroot\discoverize-portals, skip it else move the current folder from wwwroot\discoverize.com\App_Data to wwwroot\discoverize-portals add a line with the full path to the new portal folder to newportals.txt (e.g. C:\inetpub\wwwroot\discoverize-portals\<PortalName>) add a new site to IIS and set its AppPool to Discoverize-Portals start the new site in IIS (needs Admin privileges, that's why we use a parameterized task scheduler task for that) Build the source code from the repository Execute the Deploy-NewPortals target from deploy.proj using MSBuild in c:\projects\discoverize Iterate over the entries in newportals.txt, for each entry do: Copy the build output from step 2. to wwwroot\discoverize-portals\<PortalName> Run the site setup (this uses Orchard's setup method) with our own recipe (using Orchard.exe) Call an action (SetupComplete) on the new site to mark deployment as done Create a default entry so there's something to look at (using Orchard.exe) The SetupComplete action then finishes doing this: save the information of the portal.xml into an application specific configuration file create new user "portal-owner" for content management send an email about the successful installation of the new portal Quite complex, if I look at it now, but it works!

Get all target names from an MsBuild script – with Powershell

by Oliver 31. July 2012 17:27

Developing our web application www.marinas.info using Orchard CMS, I often find myself at the command prompt to run different sets of build actions: in place compilation packaging for stage deploying to a local app instance running spec tests … Sometimes I have trouble remembering the correct target name, so today I set out to attack this simple problem (displaying the names of all target defined in our build script) using Powershell. I’ve long waited for a good occasion to get my hands on it – today was finally the day. Following this inspiring walk-through by the Windows Scripting guy to parse an XML file, I made my first firm steps in Powershell, and after some guesswork I came up with this one-liner that omits the definition of a variable: [xml](Get-Content C:\Projects\discoverize\Discoverize.proj) | Foreach-Object {$_.project.target} | % {$_.Name} | sort It might help to know that % is an alias for the Foreach-Object cmdlet, and $_ references the item currently piped in. I saved this into a file that from now on I can simply call to get an up-to-date list of build target names.

Deployment mit Powershell – Schritt 5: Einrichten von Webseiten im IIS.

by robert 10. May 2009 13:30

Nun geht es darum die kopierte Webseite auch im IIS einzurichten. Da der redundante Server auf EC2 noch als Windows 2003 Maschine läuft muss das Script sowohl IIS6 als IIS7 unterstützen. (Ob durch Azure, EC2 niemals von Hause aus Windows 2008 Instanzen unterstützen wird?). Duch die benötigte Rückwertskompatibilität setzen wir daher WMI ein. function IISCreateWebSite { $service = Get-WmiObject -namespace "root\MicrosoftIISv2" -class "IIsWebService" $bindingClass = [wmiclass]'root\MicrosoftIISv2:ServerBinding' $bindings = $bindingClass.CreateInstance() $bindings.IP = "" $bindings.Port = "80" $bindings.Hostname = $iis_app_hostheader   $result = $service.CreateNewSite($iis_app_name, $bindings, $path_targetDeployment) } Die Umsetzung war verblüffend einfach und in 10 Minuten geschafft (Dank  GBP “Google Based Programming”). Die Variablen sind nach bester Programmierermanier global.

Deployment mit Powershell – Schritt 4: Benutzerrechte von Ordnern setzen.

by robert 8. May 2009 21:20

Für eine Reihe von Ordnern benötigt der IIS User Schreibrechte. Hierfür verwenden wir eine Datei “user-rights.template”, die die entsprechenden Rechte erhält. Folgende Ordner in unserer deployten Webseite sollen diese Rechte erhalten: "ProductImages", "PunchOutImages", "Style", "TempFiles", "CmsImages". Nun hilft diese Funktion: 1: function SetFolderUserRights 2: { 3: $folderNames = "ProductImages", "PunchOutImages", "Style", "TempFiles", "CmsImages" 4: 5: $templateAcl = Get-Acl ($path_sourceRoot + "/user-rights.template") 6: 7: foreach($folderName in $folderNames){ 8: Set-Acl -Path ($path_targetDeployment + "/" + $folderName) -AclObject $templateAcl 9: } 10: } Im nächsten Schritt gilt es, die IIS Web-Application mit Powershell einzurichten: 

Deployment mit Powershell – Schritt 3: Werte in der Web.Config über Variablen setzen.

by robert 8. May 2009 21:07

Beim Einrichten einer neuen Webseite geht es immer auch darum ein paar Konfigurationswerte anzupassen. In unserem konkreten Fall benötigen wir lediglich: ApplicationPath ConnectionString Hier hilft der klassische Template Processor: Wobei “Deployment.ps1” die “Template-Engine” ist 1: function CopyAndChangeWebConfig 2: { 3: $webConfigTemplate = Get-Content -Path $path_sourceConfigTemplate -Encoding UTF8; 4: $webConfigTemplate = $webConfigTemplate -replace("#ApplicationPath#", $path_targetDeployment ); 5: $webConfigTemplate = $webConfigTemplate -replace("#ConnectionString#", $Server ); 6: Set-Content -Path ($path_targetDeployment + "/web.config") -Encoding UTF8 -Value $webConfigTemplate; 7: } Lesen, ersetzen, zurückschreiben und leicht zu erweitern. :-)

Deployment mit Powershell – Schritt 2: Kopieren der Dateien

by robert 8. May 2009 20:23

Das Script wächst: Hier die Funktion “CopyTemplateToTarget”: 1: ################################################## 2: # FILE SYSTEM: DATA SECTION 3: ################################################### 4: function CopyTemplateToTarget 5: { 6: if ((Test-Path $path_targetDeployment) -eq $false ){ 7: New-Item $path_targetDeployment -Force -ItemType directory; 8: } 9: 10: copy-item $path_sourceDeploymenPackage* $path_targetDeployment -recurse -force 11: 12: PrintElapsedTime 13: } Die Variable $path_targetDeployment beinhaltet den Ordner, in den kopiert werden soll. Existiert dieser Ordner nicht, so wird er erstellt.

Deployment mit Powershell – Schritt 1: PseudoCode

by robert 8. May 2009 20:06

Für das wiederkehrende Einrichten von Webseiten zu vereinfachen, habe ich die Aufgabe eine Deployment-Script mit Powershell zu entwickeln. Um die Aufgaben  zu beschreiben, erstelle ich zunächst eine erste Pseudocode Version: Unten (Ab Zeile 18) ist im wesentlich der geplante Programmablauf zu finden. Das automatische Ausschecken aus SVN und das Erstellen des Programms ist zunächst nicht geplannt. Auch automatisierte Tests, Rollbacks etc. sind zukünftigen Versionen vorbehalten. Es geht erst mal darum ein vorbereitetes Webprojekt so zu deployen, das der IIS, die Webseite und Datenbank angelegt, eingerichtet und Konfigurationswerte korrekt gesetzt werden.

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for javascript. Enjoy MVC 4 and Orchard CMS, and I do TDD whenever I can. I like clean code. Love to spend time with my wife and our children. My profile on Stack Exchange, a network of free, community-driven Q&A sites

About Anton

shades-of-orange.com code blog logo I'm a software developer at teamaton. I code in C# and work with MVC, Orchard, SpecFlow, Coypu and NHibernate. I enjoy beach volleyball, board games and Coke.