Trevor Sullivan's Tech Room

Minding the gap between administration and development

Posts Tagged ‘dotnet’

PowerShell: Finding Friday the 13th

Posted by Trevor Sullivan on 2012/01/13


Update (2012-01-13): Justin Dearing (aka @zippy1981) informed me that it would be more efficient to look at the 13th of each month, and test if it was a Friday. In theory at least, he’s absolutely correct; I wrote the function the first way I thought of it, and I always welcome suggested improvements.

This morning I noticed that it was Friday the 13th. No, I didn’t realize it by looking at the Windows 7 system clock. I realized it because I had the worst morning waking up for the past month. I started wondering when the next Friday the 13th would be, and how often they occurred. To satisfy my curiosity, I immediately thought to write a PowerShell advanced function to find them! This was also partially inspired by Jeff Hicks’ posting 13 PowerShell scriptblocks for Friday the 13th.

There are two parameters to this function:

  • StartDate (default to "today")
  • EndDate (default to "today" +1460 days, which is roughly 4 years in the future)

You can call this function using neither parameter, one of them, or both of them. Both parameters are [System.DateTime] structs, and PowerShell will automatically try to parse any string value passed into them. Here is an example:

Find-Friday13th -StartDate 2000-01-01 -EndDate 2005-01-01

And here is the function!

<#
    .Synopsis
    This function finds Friday the 13ths.

    .Parameter StartDate
    The date you want to begin searching for Friday the 13ths.
    .Parameter EndDate
    The end date you want to search for Friday the 13ths.

    .Outputs
    [System.DateTime] objects that represent Friday the 13ths.

    .Notes
    Written by Trevor Sullivan (pcgeek86@gmail.com) on Friday, January 13, 2012.
#>
function Find-Friday13th {
    [CmdletBinding()]
    param (
        [DateTime] $EndDate = ((Get-Date) + ([TimeSpan]::FromDays(1460)))
        , [DateTime] $StartDate = (Get-Date)
    )

    # Inform user that the $EndDate parameter value must be greater than the $StartDate parameter value
    if ($EndDate -lt $StartDate) {
        Write-Error -Message 'The EndDate must be greater than the StartDate!';
        return;
    }

    # Get the next Friday after $StartDate
    while ($StartDate.DayOfWeek -ne 'Friday') {
        Write-Host "Finding next Friday";
        $StartDate = $StartDate.Add([TimeSpan]::FromDays(1));
    }

    # While $StartDate is less than $EndDate, add 7 days
    while ($StartDate -lt $EndDate) {
        # If the Day # is 13, then write the [DateTime] object to the pipeline
        if ($StartDate.Day -eq 13) {
            Write-Output -InputObject $StartDate;
        }
        # Add 7 days to $StartDate (next Friday after current)
        $StartDate = $StartDate.Add([TimeSpan]::FromDays(7));
    }
}

# Call the function
Find-Friday13th -EndDate 2017-12-31

 

Here’s what the function’s output looks like. The objects returned to the pipeline are all [System.DateTime] objects, which are automatically being ToString()’d.

image

Posted in .NET, powershell, scripting | Tagged: , , , , , , , , | 2 Comments »

PowerShell: List Strongly Typed Names in Global Assembly Cache

Posted by Trevor Sullivan on 2011/12/30


I dislike using deprecated commands or APIs when I know that there’s a more modern method of performing an action. I also generally prefer to use Windows PowerShell as a .NET scripting language, rather than constantly relying on cmdlets. To be sure, I use a balance of both concepts, since cmdlets can save a whole lot of coding a lot of the time.

Every time I want to load an assembly into PowerShell, the first thing that pops into my mind is:

[Reflection.Assembly]::LoadWithPartialName();

Unfortunately Microsoft recommends against using that static method, and recommends use of other methods like:

[Reflection.Assembly]::Load(StronglyTypedAssemblyName);

In the interest of not breaking my conscience, I would like to use this method, but the problem then becomes that I have to constantly figure out what the strongly-typed name of the assembly I want is. To help solve this problem, I decided to write a PowerShell script that extracts information from the .NET assemblies in the Global Assembly Cache (GAC), since those are generally the most common ones I’ll need to reference.

Read the rest of this entry »

Posted in .NET, powershell, scripting, tools | Tagged: , , , , , , , | 6 Comments »

PowerShell: Shortening Web Service Type Names with a Hashtable

Posted by Trevor Sullivan on 2011/07/13


When you use the New-WebServiceProxy class, you probably have noticed that PowerShell dynamically generates some really ugly type names. For example, if we get a reference to the Bing web service (you’ll need to get an API key first):

$BingSearch = New-WebServiceProxy -Class BingSearch -Uri "http://api.search.live.net/search.wsdl?AppID=$ApiKey"

… and examine the types contained within it:

$BingSearch.GetType().Assembly.GetExportedTypes() | select FullName

… you’ll notice some ridiculously long type names based on your API key, such as:

Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxyXXXXXXXXXXXXXXXXXXXXXXXXXXX.SearchRequest

Read the rest of this entry »

Posted in powershell, scripting | Tagged: , , , , , , , , , , , , , , , , | 2 Comments »

PowerShell: Dynamic Parameters and Parameter Validation

Posted by Trevor Sullivan on 2010/11/15


Background on Parameter Validation

PowerShell advanced functions allow their creators to specify a fair amount of metadata that describes their parameters. One huge benefit of parameter declarations in PowerShell is that it’s possible to validate input right at the parameter level, before you execute any code in the body of the function. This helps make code more readable, by keeping the parameter validation code up with the parameters themselves, rather than somewhere inside the function’s body.

There are around 10 different built-in parameter validation attributes, including validation against regular expressions, a pre-defined set of values, or $null values. As a catch-all, there is also an attribute (called ValidateScript) that allows you to validate a parameter against arbitrary code. This is a truly powerful feature, which also shares a significant drawback that I will cover in more detail below. For the most part, these validation parameters work great, and are very easy to implement. While this is all nice in theory, unfortunately there are circumstances where it’s necessary to use other validation measures. Here is a mindmap that I’ve been working on, part of which contains some tidbits of information about PowerShell validation attributes:

PowerShell Mindmap - Advanced Parameters

Failing the built-in validation attributes, parameter validation can also occur within a function body, ideally in the BEGIN {…} block where it occurs before any objects are processed through the pipeline. Another powerful method of parameter validation is the use of PowerShell’s dynamic parameters.

Dynamic parameters

Benefits

Dynamic parameters are great, in theory. You can write arbitrary PowerShell code inside the code block where the parameters are defined. Perhaps the most significant benefit, among the few that there are, is the inherent ability for dynamic parameters to see the values of their siblings: static parameters. This exposes the drawback to the ValidateScript attribute that I mentioned before — although using ValidateScript with a static parameter lets you define an arbitrary PowerShell code block to validate a parameter value, it does not allow you to see values of other static parameters. See the section below titled “Example of [ValidateScript()]’s Shortcoming” for a real-world example of how I ran into this issue.

Drawbacks

As great as dynamic parameters can be, you should exercise some caution when using them. First of all, dynamic parameters simply take more effort to implement than static parameters. As a side effect of this, they are also less structured, which makes code maintenance a bit harder and more confusing. The parameter declaration itself, along with any attributes you want to apply to the parameter, must be explicitly created using the New-Object cmdlet, or compatible .NET APIs.

More importantly though, besides the fact that they’re more complicated to write, they are not discoverable in the same way that static parameters are. Given that PowerShell is all about discovery (among other things), this is an important point. Static parameters are easily discovered, as they can be easily analyzed (“reflected” to use proper .NET terminology) by the PowerShell engine prior to execution time.

Example of [ValidateScript()]’s Shortcoming

I’ll describe a situation to you, where the ability of dynamic parameters to read static parameter values during validation is important. I was writing an advanced function that takes two parameters: a WMI namespace (eg. root\cimv2), and a computer name (eg. Gandalf.mydomain.loc). My goal was to validate the existence of the WMI namespace in the parameter declaration, so that I wouldn’t have to worry about checking for its existence later on in the function body. Initially, not knowing any better, I assumed that I could use the ValidateScript attribute on the –Namespace parameter, and build a WMI path including the –ComputerName property (eg. \\$ComputerName\$Namespace:__thisNAMESPACE).

        [ValidateScript({
            if (([wmiclass]"\\${ComputerName}\root\cimv2:__ThisNamespace").__namespace -eq $_)
            {
                return $true
            }
            else
            {
                return $false
            }
        })]
        ${Namespace} = 'root\subscription'

Note: If no value is passed to a parameter, and the parameter’s default value is used, the code block in [ValidateScript()] will not execute.

I quickly found out that this wouldn’t work, because the $ComputerName parameter was not available in the ValidateScript code block. Only the current parameter was accessible using the $_ automatic variable. With this in mind, I went ahead and moved the namespace validation into the BEGIN { … } block of my function — this was easy enough, but not quite how I wanted to structure it either. It was then that I remembered that dynamic parameters could read other parameter’s values, and went back to have a read about them.

Unfortunately I don’t have an example of using dynamic parameters, since I elected to stick with validating in the function body. The main reason I chose to go that route, was because I didn’t want to lose the discoverability of parameters on this function, or the other functions I’m writing that are similar to it. If you would like to better understand dynamic parameters, please see the links in the references section below.

Conclusion

As covered in this article, we have shown how parameter validation via the [ValidateScript()] attribute is both powerful and limited. We have also explored how the use of more flexible dynamic parameters can help us overcome these challenges, with some sacrifice in discoverability and complexity.

References

Posted in powershell, scripting, wmi | Tagged: , , , , , , , , , , , , | Leave a Comment »

PowerShell Quick Tip: Determine STA Threading Mode

Posted by Trevor Sullivan on 2010/11/02


Some code in PowerShell requires you to use the Single-Threaded Apartment (STA) threading model. The PowerShell version 2.0 console host uses Multi-Threaded Apartment by default. The PowerShell Integrated Scripting Environment (ISE) uses the STA threading model.

If you’re writing code using the WPK module included in the PowerShellPack, you will need to ensure that you are using the STA model. You can avoid errors in your code by adding a check for the threading model before you attempt to run WPK code. Here is a simple, one-line example of how to do that:

[System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.ApartmentState -eq [Threading.ApartmentState]::STA

What the above code does is:

  1. Gets the current (default) Runspace
  2. Looks at the ApartmentState property, whose value is an ApartmentState
  3. Compares it to the STA

Note: It’s important to note that, in testing, I discovered that when the threading state is set to MTA in the PowerShell console host, the Runspace.ApartmentState property is set to [Threading.ApartmentState]::Unknown. I don’t know why this is, but keep it in mind if you’re planning on performing a comparison against [Threading.ApartmentState]::MTA – this simply won’t work for the MTA model in PowerShell, unless someone else has a different experience than me.

Posted in .NET, powershell, scripting | Tagged: , , , , , , , , , , , , | 1 Comment »

PowerShell: ConfigMgr WMI Provider (feat. Lazy Properties)

Posted by Trevor Sullivan on 2010/09/28


What are Lazy Properties?

So if you’re a script writer, and you also use System Center Configuration Manager 2007 (ConfigMgr), you may have run into a concept called Lazy Properties. Lazy properties are certain (not all) properties on certain (not all) WMI classes, within the ConfigMgr provider namespace, that are marked with a WMI qualifier denoting the property as “lazy.” That was quite a mouthful! What exactly does this mean? Why are certain properties LAZY? Well, during the development of ConfigMgr, Microsoft realized that the enumeration of some information from the ConfigMgr provider could result in a high load on the server where the provider is installed. They introduced lazy properties as a method of providing only (what they deemed) “essential information” unless the script/software developer specifically requested more information.

How do I identify Lazy Properties?

Now that you know what lazy properties are, you are probably wondering how you’re supposed to know whether or not you have to design your code around lazy properties. This actually isn’t too hard. There are a couple different ways you’ll know that you’re dealing with a lazy property:

  • You’re not getting data back that you’d expect to when querying a ConfigMgr WMI class
  • You find a property marked with the lazy WMI qualifier using a WMI browsing tool (eg. wbemtest, SAPIEN WMI Explorer, CIM Studio, etc.)
  • Run a PowerShell script against the ConfigMgr namespace and look for property definitions with the lazy qualifier — read the last section of this article

Here is a screenshot of WbemTest (WMI utility built into Windows), browsing the class definition of root\sms\site_xyz:SMS_AuthorizationList. Instances of the SMS_AuthorizationList class represent Update List objects in ConfigMgr Software Updates. We can see that the property named “Updates” on this class is marked as lazy. This is just one example, and there are many more properties just like this one.

Ok, so how do I get values from Lazy Properties?

Getting values from lazy properties takes just a couple extra steps than normally working with WMI objects. The key thing to remember with lazy properties is that you have to get a reference to each WMI instance (aka. object) explicitly. You’re still ok to enumerate WMI instances using the SwbemServices.ExecQuery() COM interface in VBscript & PowerShell, or Get-WmiObject in PowerShell, but when you’re iterating over each instance, you must get a second, explicit reference to the WMI instance you’re wanting to work with. Let’s look at an example.

PowerShell Code – Retrieving a Lazy Property

Here is a sample script that retrieves all instances of the SMS_AuthorizationList class, that we examined above. Take note that as we iterate over each instance of SMS_AuthorizationList, we are redefining the $UpdateList variable by retrieving a direct reference to the instance. If we hadn’t done this, the Updates property that we looked at in WbemTest would appear to be empty!

# Retrieve an array of all Update List objects
$UpdateLists = Get-WmiObject -Namespace root\sms\site_lab -Class SMS_AuthorizationList

# Iterate over each Update List object in results
foreach ($UpdateList in $UpdateLists)
{
    # Using the __PATH property, obtain a direct reference to the instance
    $UpdateList = [wmi]"$($UpdateList.__PATH)"

    # Iterate over each update CI_ID in the Updates array
    foreach ($Update in $UpdateList.Updates)
    {
        # Get a reference to the update we're working with, based on its CI_ID
        $Update = Get-WmiObject -Namespace root\sms\site_lab -Query "select * from SMS_SoftwareUpdate where CI_ID = '$Update'"
        Write-Host "Update List ($($UpdateList.LocalizedDisplayName)) contains update: ",$Update.LocalizedDisplayName
    }
}

Code Results

Here is a screenshot of Quest’s free PowerGUI Script Editor running the script above, and retrieving a ConfigMgr lazy property (SMS_AuthorizationList.Updates). It’s actually doing a bit more than simply retrieving a WMI instance with its lazy properties — the lazy property (Updates) itself contains only an array of the UpdateIDs (aka. it’s CI_ID) associated to the Update List (SMS_AuthorizationList) object. We’re going one step further and cross-reference the UpdateID with the SMS_SoftwareUpdate class, so we can retrieve more information about the individual updates. This enables us to print out the friendly name of the update, as seen below in the lower-right PowerShell Console window.

What happens if I don’t retrieve lazy properties in my script?

So you’re thinking you can get off easy by just not retrieving lazy properties, right? Well, you can, but you’ll likely run into trouble. The thing is, if you make any changes to your WMI objects, and write them back to the ConfigMgr provider using the Put() method, you’ll effectively erase the values of any lazy properties on that object! It goes without saying that you need to be very careful when making any changes to your ConfigMgr objects via the provider (which is the only way you should be doing it in the first place, programatically).

If you’re simply reading information from the provider, and do not require the information contained within any lazy properties, then you are safe to read the information without performing the additional steps above.

Mega-Bonus Round: Listing All ConfigMgr Lazy Properties

Here’s a very simple PowerShell script we can use to spit out a list of all the lazy properties in the ConfigMgr namespace! Keep in mind that this could change with service pack or “R” revisions to ConfigMgr. I also would surmise that ConfigMgr vNext will introduce more changes to this list, and who knows, maybe they’ll eliminate lazy properties altogether! Just a theory, don’t quote me 🙂

PowerShell Code – Listing All ConfigMgr Lazy Properties

If you copy/paste/execute this code, after changing “lab” to your ConfigMgr site code, you should be able to get similar output to what I’ve included below for a reference. If you’re running the script from a remote management workstation, rather than on your server with the ConfigMgr provider, simply tack on the -ComputerName parameter to the Get-WmiObject cmdlet.

$WmiClassList = Get-WmiObject -List -Namespace root\sms\site_lab
$LazyList = @()

# Iterate over each WMI class in the namespace
foreach ($WmiClass in $WmiClassList)
{
    # Iterate over properties for current WMI class
    foreach ($WmiProperty in $WmiClass.Properties)
    {
        # Iterate over WMI qualifiers for current WMI property
        foreach ($WmiQualifier in $WmiProperty.Qualifiers)
        {
            # If qualifier is named "lazy", and the value is "true", then it's a lazy property
            if ($WmiQualifier.Name -eq 'lazy')
            {
                # Add class name, property name, and qualifier name to array for processing
                $LazyList += New-Object PSCustomObject -Property @{ "Class" = $WmiClass.__CLASS; "Property" = $WmiProperty.Name; "Qualifier" = $WmiQualifier.Name }
            }
        }
    }
}

# Sort array of lazy properties by WMI class name, property name
$LazyList = $LazyList | Sort-Object -Property Class,Property
# Write array of lazy properties to console
Format-Table -InputObject $LazyList -Property Class,Property,Qualifier | Out-File "All ConfigMgr Lazy Properties.txt"

ConfigMgr Lazy Property Reference

This is a reference of all ConfigMgr lazy properties, based on an installation of ConfigMgr 2007 SP2 with R3 Release Candidate installed. It’s possible that this list could change, but if you simply run the script above (change your site code from “lab), you can get a current list once again.

Class                                       Property                                    Qualifier
-----                                       --------                                    ---------
SMS_Advertisement                           AssignedSchedule                            lazy
SMS_Advertisement                           AssignedScheduleEnabled                     lazy
SMS_Advertisement                           AssignedScheduleIsGMT                       lazy
SMS_Advertisement                           ExpirationTimeEnabled                       lazy
SMS_Advertisement                           ExpirationTimeIsGMT                         lazy
SMS_Advertisement                           ISVData                                     lazy
SMS_Advertisement                           ISVDataSize                                 lazy
SMS_Advertisement                           PresentTimeEnabled                          lazy
SMS_Advertisement                           PresentTimeIsGMT                            lazy
SMS_AuthorizationList                       LocalizedInformation                        lazy
SMS_AuthorizationList                       Updates                                     lazy
SMS_BootImagePackage                        BackgroundBitmapPath                        lazy
SMS_BootImagePackage                        ContextID                                   lazy
SMS_BootImagePackage                        EnableLabShell                              lazy
SMS_BootImagePackage                        ImageDiskLayout                             lazy
SMS_BootImagePackage                        ImageIndex                                  lazy
SMS_BootImagePackage                        ImageProperty                               lazy
SMS_BootImagePackage                        ReferencedDrivers                           lazy
SMS_CategoryInstanceBase                    LocalizedInformation                        lazy
SMS_CertificateInfo                         Certificate                                 lazy
SMS_CertificateInfo                         PublicKey                                   lazy
SMS_CertificateInfo                         Thumbprint                                  Lazy
SMS_CI_CurrentComplianceStatus              ComplianceStatusDetails                     lazy
SMS_Collection                              CollectionRules                             lazy
SMS_Collection                              RefreshSchedule                             lazy
SMS_Collection                              RefreshType                                 lazy
SMS_Collection                              ReplicateToSubSites                         lazy
SMS_CollectionSettings                      CollectionVariables                         lazy
SMS_CollectionSettings                      PowerConfigs                                lazy
SMS_CollectionSettings                      ServiceWindows                              lazy
SMS_ConfigurationItem                       LocalizedEulas                              lazy
SMS_ConfigurationItem                       LocalizedInformation                        lazy
SMS_ConfigurationItemBaseClass              IsDigest                                    lazy
SMS_ConfigurationItemBaseClass              SDMPackageLocalizedData                     lazy
SMS_ConfigurationItemBaseClass              SDMPackageXML                               lazy
SMS_DeviceSettingItem                       PropList                                    lazy
SMS_DeviceSettingPackage                    DeviceSettingItemUniqueIDs                  lazy
SMS_DistributionPoint                       ISVData                                     lazy
SMS_DistributionPoint                       ISVDataSize                                 lazy
SMS_Driver                                  LocalizedEulas                              lazy
SMS_Driver                                  LocalizedInformation                        lazy
SMS_EULAContent                             EULAText                                    lazy
SMS_G_System_CollectedFile                  FileData                                    lazy
SMS_ImagePackage                            ImageDiskLayout                             lazy
SMS_ImagePackage                            ImageProperty                               lazy
SMS_MachineSettings                         MachineVariables                            lazy
SMS_ObjectContainerNode                     SearchString                                lazy
SMS_OperatingSystemInstallPackage           ImageProperty                               lazy
SMS_PackageBaseclass                        AlternateContentProviders                   lazy
SMS_PackageBaseclass                        ExtendedData                                lazy
SMS_PackageBaseclass                        ExtendedDataSize                            lazy
SMS_PackageBaseclass                        IconSize                                    lazy
SMS_PackageBaseclass                        ISVData                                     lazy
SMS_PackageBaseclass                        ISVDataSize                                 lazy
SMS_PackageBaseclass                        RefreshPkgSourceFlag                        lazy
SMS_PackageBaseclass                        RefreshSchedule                             lazy
SMS_PDF_Package                             Icon                                        lazy
SMS_PDF_Package                             IconSize                                    lazy
SMS_PDF_Package                             RequiredIconNames                           lazy
SMS_PDF_Package                             Status                                      lazy
SMS_PDF_Program                             Icon                                        lazy
SMS_PDF_Program                             IconSize                                    lazy
SMS_PendingRegistrationRecord               Certificate                                 lazy
SMS_PendingRegistrationRecord               PublicKey                                   lazy
SMS_PendingRegistrationRecord               Thumbprint                                  Lazy
SMS_Program                                 ExtendedData                                lazy
SMS_Program                                 ExtendedDataSize                            lazy
SMS_Program                                 IconSize                                    lazy
SMS_Program                                 ISVData                                     lazy
SMS_Program                                 ISVDataSize                                 lazy
SMS_Program                                 SupportedOperatingSystems                   lazy
SMS_Report                                  DrillThroughReportPath                      lazy
SMS_Report                                  ReportParams                                lazy
SMS_Report                                  SQLQuery                                    lazy
SMS_SiteControlFile                         BuildNumber                                 lazy
SMS_SiteControlFile                         FormatVersion                               lazy
SMS_SiteControlFile                         SCFData                                     lazy
SMS_SiteInstallMap                          BuildNumber                                 lazy
SMS_SiteInstallMap                          FormatVersion                               lazy
SMS_SiteInstallMap                          IMapData                                    lazy
SMS_SoftwareUpdate                          LocalizedEulas                              lazy
SMS_SoftwareUpdate                          LocalizedInformation                        lazy
SMS_SoftwareUpdateSource                    PublicKeys                                  Lazy
SMS_StateMigration                          UserNames                                   lazy
SMS_TaskSequencePackage                     BootImageID                                 lazy
SMS_TaskSequencePackage                     Category                                    lazy
SMS_TaskSequencePackage                     CustomProgressMsg                           lazy
SMS_TaskSequencePackage                     DependentProgram                            lazy
SMS_TaskSequencePackage                     References                                  lazy
SMS_TaskSequencePackage                     Reserved                                    lazy
SMS_TaskSequencePackage                     Sequence                                    lazy
SMS_TaskSequencePackage                     SupportedOperatingSystems                   lazy
SMS_TaskSequencePackage                     TaskSequenceFlags                           lazy
SMS_TaskSequencePackage                     Type                                        lazy
SMS_Template                                Data                                        lazy
SMS_UpdatesAssignment                       LegacyCollectInventory                      lazy
SMS_UpdatesAssignment                       LegacyDeploymentSchedule                    lazy
SMS_UpdatesAssignment                       LegacyDPLocality                            lazy
SMS_UpdatesAssignment                       LegacyForceReboot                           lazy
SMS_UpdatesAssignment                       LegacyInstallAllOnDeadline                  lazy
SMS_UpdatesAssignment                       LegacyInstallAllowedWindow                  lazy
SMS_UpdatesAssignment                       LegacyPostponeInstall                       lazy
SMS_UpdatesAssignment                       LegacySilentInstall                         lazy
SMS_VirtualApp                              IconSize                                    lazy

Posted in .NET, configmgr, powershell, scripting, tools, vbscript, wmi | Tagged: , , , , , , , , , , , , | Leave a Comment »