ASP.NET Weblogs

Welcome to ASP.NET Weblogs Sign in | Join | Help
in Search

The Technical Adventures of Adam Weigert

August 2008 - Posts

  • PowerShell: Keeping Secrets for Batch Scripts

    As a system administrator, I write a lot of utility scripts, and I love using PowerShell. However, I cannot always use the local scheduler with a service account to run a script, sometimes I have to provide a username and password to an application or service. I hate storing them in plaintext, and while I don't fully like storing the encrypted text, key, and IV in the script, it is one step better than the plaintext solution. While the ultimate solution would be to have it stored as part of the user profile for the job, this is an issue when I don't have direct access to the production system to be able to run as the service account and I just need an encrypted file / text to later decrypt and use.

    So, I started working with ConvertTo/From-SecureString and hit a little problem. I discovered, via Reflector, that the ConvertTo-SecureString and ConvertFrom-SecureString use an IV that is specific to that instance of the PowerShell runtime. Thus, using it at a later time is no good for me. So, long story short, I cranked up Reflector, took a look at the commands, and created a script version that does exactly what I need.

    You will find the script attached.

     

  • PowerShell: Adding the Using Statement

    So, I happened to come across a need for the using statement from C#. I basically didn't want to use Try...Finally when I am so used to the short-hand using statement. Thank goodness I already have a Try..Catch..Finally statement/function for PowerShell, I can just use that existing framework and make a using statement/function pretty easily.

    function Using {
        param (
            [System.IDisposable] $inputObject = $(throw "The parameter -inputObject is required."),
            [ScriptBlock] $scriptBlock = $(throw "The parameter -scriptBlock is required.")
        )
        
        Try {
            &$scriptBlock
        } -Finally {
            if ($inputObject -ne $null) {
                if ($inputObject.psbase -eq $null) {
                    $inputObject.Dispose()
                } else {
                    $inputObject.psbase.Dispose()
                }
            }
        }
    }
    
    # Short example ... 
    Using ($user = $sr.GetDirectoryEntry()) { 
      $user.displayName = $displayName 
      $user.SetInfo() 
    } 
    

    Update: Take note on variable scope, variables in the using statement will not be available outside of it, this can make it tricky, but it should be easy enough to work with.

More Posts