Skip to main content

I <3 PowerShell

I finally have found a topic I want to blog about: PowerShell. If you don't know what PowerShell is then I suggest you do some lite reading about it or just keep reading here and I'm sure the mental light bulb will turn on shortly.

So, why blog about PowerShell out of all the other things I could blog about, and probably will blog about? I am a literal dev-admin, the fusion of a developer and system administrator. For the past 10 years I have been working in the I.T. as a developer that also does system administrator work as his primary job. Having the development background I do, I am constantly looking for ways to automate my day-to-day tasks or create automation that I can have other people use if I am not around to keep the business/infrastructure running smoothly.

I started creating web-automation applications within a few months of becoming a sysadmin. Since then I have been looking for a way to make those applications easier to maintain and more powerful. If you have any experience trying to use WMI in C# you know it can be a pain. However, PowerShell makes WMI extremely easy.

With C# 4.0 we have been blessed with the "dynamic" keyword. This has made it possible for the ultimate fusion of code and script. Essentially, everyone object in PowerShell is a "dynamic" object. Bringing those powerful objects straight into a .NET application previously required you to navigate the PSObject object. With an easy DynamicObject wrapper around a PSObject, we can now use the PSObject almost as if we were writing PowerShell script instead of .NET code.

Being a web-centric thinker, more than 80% of the tools I make for my job are web-based. Being able to now quickly and easily bring a PSObject into ASP.NET and use the properties/methods of that object as if I was writing PowerShell script is invaluable.

This invention of a dynamic PSObject for .NET has lead me over the past few weeks to spend time creating a framework that allows the seamless use of PowerShell within ASP.NET, time I would just typically spend glued to my computer questing/farming/raiding on WoW has been well spent. Here is an example MVC3 action that calls PowerShell to kill a process:

  1. public ActionResult Kill(string computerName, uint pid)  
  2. {  
  3.     HttpPowerShell.Invoke(@"param($ComputerName, $ProcessId) Get-WmiObject Win32_Process -ComputerName $ComputerName -Authentication PacketPrivacy -Filter ""ProcessId = $ProcessId"" |% { $_Terminate() }", parameters: new { ComputerName = computerName, ProcessId = pid });  
  4.     return View();  
  5. }  

Once you can use PowerShell in your ASP.NET applications you start thinking of crazy ways to customize, configure, manage, etc... your application. An example of this is that during the build-out of a demo app that uses this I wanted a way to run a configuration factory through a PowerShell script rather than having to write a configuration section or hard code some values that would make it difficult to manage later on.

This train of thought lead me to creating a configuration factory that leverages PowerShell for the creation of the configuration object. In the framework I'm using (custom right now) you would override the configuration factory as so:

  1. Configuration<ComputerRepositoryConfiguration>.Factory = HttpPowerShellConfigurationFactory<ComputerRepositoryConfiguration>.FromFile("~/App_Data/New-ComputerRepositoryConfiguration.ps1");  

The PowerShell script would look similar to this:

  1. param(  
  2.     [Parameter(Mandatory = $true, ValueFromPipeline = $true)]  
  3.     [Type] $type  
  4. )  
  6. process {  
  7.     $config = New-Object $type  
  9.     $config.AddContext('''Domain''OU=Domain Controllers,DC=iheartpowershell,DC=com') | Out-Null;  
  10.     $config.AddContext('''Domain''OU=Servers,DC=wfm,DC=wegmans,DC=com') | Out-Null;  
  12.     $config  
  13. }  

So, there you have it. This doesn't even begin to scrape the surface of some of the uses for PowerShell within ASP.NET but I will surely grace you with that knowledge in future posts.

I promise you I will do somethings that will not make sense, probably more often than doing something that makes me seem like a decent/normal guy. Until then, time to launch PowerShell ISE, it misses me...

P.S. Special thanks for the syntax highlighting:


Popular posts from this blog

PowerShell SupportsShouldProcess Worst & Best Practices

This has been a very big discussion within the Scripting Games 2013 community and I want to add my two cents in an official blog post.

I've left several people comments on how they might be misunderstanding how SupportsShouldProcess works, but I also realize, everyone of these individuals has given me more insight into its use and perhaps, how it should best be utilized.

For those of you that don't know, SupportsShouldProcess is a parameter on the CmdletBinding attribute you can place on your cmdlets that automatically adds the -WhatIf and -Confirm parameters. These will naturally flow into other cmdlets you use that also SupportsShouldProcess, e.g. New-Item, Move-Item.

The major discussion has been around, should you just let the other cmdlets handle the $PSCmdlet.ShouldProcess feature, and if not how should you implement it. ShouldProcess has the following definitions.

Generate Random SecureString Key

Ever need to encrypt a SecureString that can be used across multiple servers? I suggest storing this BASE64 value in a secure location only accessible by the account(s) that need to decrypt the SecureString.
$secret = 'secret1234'$key    = [Convert]::ToBase64String((1..32 |% { [byte](Get-Random -Minimum 0 -Maximum 255) }))  $encryptedSecret = ConvertTo-SecureString -AsPlainText -Force -String $secret | ConvertFrom-SecureString -Key ([Convert]::FromBase64String($key))  $encryptedSecret | Select-Object @{Name='Key';Expression={$key}},@{Name='EncryptedSecret';Expression={$encryptedSecret}} | fl  $ss = ConvertTo-SecureString -Key ([Convert]::FromBase64String($key)) -String $encryptedSecret(New-Object System.Management.Automation.PSCredential 'SECURESTRING',$ss).GetNetworkCredential().Password

PowerShell Error Handling Behavior Debunked

Note: I am using simple error messages as an example, please reference the best practices and guidelines I outlined on when to use custom error messages.

I have been churning in my mind for the last few days all the entries in the 2013 Scripting Games and how they handle errors, or lack thereof.

I am coming to the conclusion through some testing that the simple fact of seeing a try..catch or throw statements does not mean there is proper error handling.

I've been testing several variations and forms of error handling, so lets start with the basics.
function Test-WriteError {      [CmdletBinding()] param()  "Test-WriteError::ErrorActionPreference = $ErrorActionPreference"Move-Item -Path 'C:\Does\Not\Exists.log' -Destination 'C:\No\Where'"Test-WriteError::End"}   Test-WriteError::ErrorActionPreference = Continue
Move-Item : Cannot find path 'C:\Does\Not\Exists.log' because it does not exist.
At line:6 char:5
+     Move-Item -Path 'C:\Does\N…