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. )  
  5.   
  6. process {  
  7.     $config = New-Object $type  
  8.   
  9.     $config.AddContext('iheartpowershell.com''Domain''OU=Domain Controllers,DC=iheartpowershell,DC=com') | Out-Null;  
  10.     $config.AddContext('iheartpowershell.com''Domain''OU=Servers,DC=wfm,DC=wegmans,DC=com') | Out-Null;  
  11.   
  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: http://www.thecomplex.plus.com/highlighter.html

Comments

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.
OverloadDefinitions�����������������������������������������������������������������������������������������…

FIM 2010 R2 Self-Service Password Reset Auto-Registration

I have been working on our FIM 2010 R2 SP1 lab environment looking for ways to simplify some of the overly complicated scenarios we had to implement to workaround the limitations in FIM 2010. One of those workarounds was the auto-registration of SSPR for new employees. When we onboard a new employee, we want to create a simple SSPR for them to get their first-time password reset.

Prior to the R2 release we were using the http://fim2010client.codeplex.com/ client and PowerShell to complete the registration process on a daily schedule. I was working on converting this to use the R2 registration cmdlets and combined it with PowerShell 3.0 Workflows to get to a solution similar to this.
[CmdletBinding()]  param()  begin {      workflow Invoke-RegisterSSPR {          InlineScript {              Import-Module FIM          }  $workflow = InlineScript { Get-FIMResource -Filter '/WorkflowDefinition[DisplayName = "Password Reset AuthN Workflow for New Employees"]' }  $members  …

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…