Trevor Sullivan's Tech Room

Minding the gap between administration and development

Archive for the ‘.NET’ Category

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 3.0: List of Windows 8 Cmdlets & Modules

Posted by Trevor Sullivan on 2011/09/14


Here is a list of modules available in the new Windows Server 8:

Name
—-
ADDeploymentWF
AppLocker
Appx
BestPractices
BitsTransfer
BranchCache
CimCmdlets
ClusterAwareUpdating
DirectAccessClientComponents
Dism
DnsClient
DnsConfig
DnsLookup
DnsNrpt
FailoverClusters

 

Read the rest of this entry »

Posted in .NET, powershell, scripting, Windows 8 | Tagged: , , , , , , | Leave a Comment »

Extreme PowerShell / ConfigMgr: Extending Hardware Inventory

Posted by Trevor Sullivan on 2011/07/05


Introduction

In previous versions of Microsoft System Center Configuration Manager (ConfigMgr / SCCM), a common task for administrators, engineers, and consultants, was to extend the hardware inventory configuration. These inventory extensions were written in Managed Object Format (MOF) and allowed the SCCM client agents to report back a wider array of information to the central site database for reporting purposes, collection building, and other management tasks. Making changes to the configuration could be a tedious task, as MOF is not very forgiving, and rather quite strict, in its syntax.

In Microsoft Systems Management Server 2003 (SMS 2003), each time a configuration change was made, it was necessary to deploy the updated MOF file to the SMS clients — this made ensuring hardware inventory consistency across all clients a challenging task. In SCCM, Microsoft included changes to these MOF files (SMS_DEF.mof and Configuration.mof) as part of the machine policy refresh task, which is a client-side polling mechanism for configuration changes.

In SCCM 2012 Beta 2, Microsoft is taking it a step further and has eliminated the SMS_DEF.mof altogether, left the configuration.mof behind by itself, and stuck the WMI inventory configuration in … WMI. What is WMI? WMI stands for Windows Management Instrumentation, a service built into the Windows Operating System since Windows XP (and Windows 2000 Service Pack 4, I think). It provides a standard method of exposing hardware and software level system information to applications, such as storage, processor, memory, running processes, installed software, and other application configuration data. SCCM is built on top of this technology, and often makes developing software and scripts around the product much easier than it otherwise might be.

For the remainder of this article, we’re going to look at specifically how to extend hardware inventory in SCCM 2012 programmatically using Windows PowerShell with the SCCM WMI provider.

Read the rest of this entry »

Posted in .NET, configmgr, ConfigMgr vNext, powershell, scripting, tools, wmi | Tagged: , , , , , , , , , , , , , , , | 2 Comments »

Removing Permanent WMI Event Registrations

Posted by Trevor Sullivan on 2011/01/18


Introduction

Since I’ve worked on the PowerEvents PowerShell module, several folks have been confused about how to remove event registrations once they’ve been created. I wrote some documentation that’s included in the download, that explains how to manually remove these registrations using the built-in wbemtest tool. This is the fool-proof method, since wbemtest is included in every Windows installation.

In the interest of making things easier, however, I wrote a WinForms utility in C# a little while back. This utility simply enumerates the various permanent event objects in the WMI repository (filters, consumers, and bindings), and allows you to remove them. That’s all it does 🙂

In the remainder of this blog post, I’ll talk about the manual method of removing event objects, and show you the utility I just mentioned.

The Manual Method

While experimenting with the PowerEvents module, you might accumulate many WMI event filter and consumer objects. At some point, you’ll probably want to clear those out. As of this writing, the PowerEvents module needs further work on the Get-* and Remove-* advanced functions. Until this functionality can be implemented, use the following procedure to remove the filter/consumer bindings.

Here are the individual steps to remove an unwanted event binding:

  1. Open wbemtest as an administrator
  2. Click Connect
  3. In the Namespace field, type root\subscription
  4. Click Connect or press {ENTER}
  5. Click Enum Instances
  6. Type __FilterToConsumerBinding in the text box
  7. Click OK or press {ENTER}
  8. Click the binding instance you want to remove
  9. Click the Delete button

Upon removal of the __FilterToConsumerBinding instance, the consumer will no longer respond to events. This process can be repeated to remove filters and consumers. Rather than enumerating instances of __FilterToConsumerBinding however, you would use “__EventFilter” or any of the five consumer class names.

The WMI Event Helper Utility

The utility I wrote a little while back is intended to display all filters, consumers, and event bindings to you, so that you can remove them from a friendly GUI. Although it works quite well in my personal testing, the tool has one important limitation, albeit it probably won’t affect most people.

The Limitation

In its current form, it does not allow you to specify a WMI namespace where the event objects reside. As I said, most folks should be OK, but you should be aware that you can create WMI filter objects in ANY WMI namespace, not just root\subscription (the default). The out-of-box consumer instances can be created in either root\default or root\subscription (latter is default). Finally, event bindings can be created in ANY WMI namespace.

Unless you’re explicitly specifying an alternate WMI namespace when creating the various WMI event objects, you won’t be affected by this. Just be aware that, if you’re a power user, you might want to make sure you don’t have event objects in other namespaces.

The Tool

Here’s what the tool looks like:

image

As you can see, it lists filters, consumers, and bindings in the root\subscription namespace. You might notice that above the consumer list, there’s a “Consumer Type” combo box. By clicking the arrow, or scrolling through the list using your mouse scroll wheel (the control must have focus), you can select the Consumer Class that you want to enumerate instances of.

Simply click on the item you want to delete, and select the appropriate “Remove” button. That’s all there is to it!

You can download the WMI Event Helper utility on the PowerEvents project page.

Conclusion

This blog post has covered the removal of WMI permanent event objects both manually, and using a C# event management utility. For more information, please review the comprehensive documentation included in the PowerEvents module release download.

Posted in .NET, 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: Disable CapsLock

Posted by Trevor Sullivan on 2010/10/13


Here’s a quick code snippet that shows how to disable CapsLock using PowerShell, combined with some embedded C# and .NET Interop (aka. P/Invoke.NET) code.

Credit goes to “BobS00327” for the C# code necessary to handle this.

function Set-CapsLock([switch]$Disable = $true)
{
    $CapsCtrl = @"
    using System;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;

    public class CapsLockControl
    {
        [DllImport("user32.dll")]
            static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,UIntPtr dwExtraInfo);
        const int KEYEVENTF_EXTENDEDKEY = 0x1;
        const int KEYEVENTF_KEYUP = 0x2;

        public static void Main()
        {
            if (Control.IsKeyLocked(Keys.CapsLock))
            {
                keybd_event(0x14, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr) 0);
                keybd_event(0x14, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
                    (UIntPtr) 0);
            }
        }
    }
"@

    if (-not [CapsLockControl]) {
        Add-Type $CapsCtrl -ReferencedAssemblies System.Windows.Forms
    }
    if ($Disable) {
        [CapsLockControl]::Main()
        Write-Host "Capslock has been disabled"
    }
}

Set-CapsLock -Disable

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

PowerGUI: Save Time, Customize Snippets

Posted by Trevor Sullivan on 2010/10/01


Introduction

Quest’s PowerGUI Integrated Development Environment (IDE) offers the ability to insert code snippets, similar to Microsoft Visual Studio. This saves a lot of typing, and gives you the general framework for whichever PowerShell construct you’re trying to us, for which you only need to fill in the specifics. These code snippets are conveniently stored as files with the .snippet extension. They contain XML that describes the code snippets, and allow you to fill in certain key fields with the IDE.

Snippet Screenshot

The snippet files are stored in a “Snippets” folder beneath the folder where you installed PowerGUI. This is typically %PROGRAMFILES%\PowerGUI\Snippets (Windows 32-bit) or %PROGRAMFILES(x86)%\PowerGUI\Snippets (Windows 64-bit). Because these are simply XML documents—which are nothing more than plain text, really—you can open them in an editor such as Notepad++ or Microsoft’s XML Notepad 2007.

Customizing Snippets

Code snippets can be customized by making edits to the various fields, or code, and saving the file. You’ll need to launch your text or XML editor with your administrative credentials (if you have User Account Control (UAC) on) in order to modify these files, because they are write-restricted from standard users. Once you’ve opened a snippet file, you’ll see a couple of different sections that you can customize. The \CodeSnippets\CodeSnippet\Header section contains some metadata about the code snippet, including: it’s title, the author, a brief description, and the shortcut you can use in the IDE to reference it (rather than digging through the snippet list). If you check out the \CodeSnippets\CodeSnippet\Snippet\Code section, you’ll find the actual PowerShell code that’s embedded in your script when you select the code snippet.

image

By making some simple edits to this section, you can tweak the code that’s inserted into your script from this snippet.

One example of an edit I made, is to comment out the New-Alias, and subsequent Export-ModuleMember section from this snippet: function (module, public, advanced).snippet. Since I’m not generally interested in creating aliases for my advanced functions, I don’t need these lines. I may want them later on though, so rather than remove them, I simply comment them out in the .snippet file.

Conclusion

This article has been a brief demonstration of PowerShell code snippets in Quest’s PowerGUI Script Editor. You can also create your own snippets by copying the structure of any of the code snippets included with the latest version of the software. If you do create any code snippets that you think would be helpful to the community, please be sure to visit http://powergui.org and share your code snippets with the PowerShell community.

As an aside, if you haven’t already gotten involved, there is a great community on the PowerGUI discussion forums! If you are having trouble with a script, or simply want to help out by answering someone else’s question, community participation is always encouraged and welcomed.

Happy PowerShell Scripting!

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

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 »

PowerShell Module: Enable Wake for Devices

Posted by Trevor Sullivan on 2010/09/23


So in my last post, I shared a PowerShell script that enables you to enable devices to wake up computers. This script relies solely on a WMI interface, but despite the remote nature of WMI, I had provided no method of entering a remote computer name. That changes with the release of my first ever formal PowerShell module! I’ve taken the code from the “enable device wake” script and adapted it to a PowerShell advanced function. I also added the cmdlet binding attribute to it, which makes it an official script cmdlet.

This command more or less replaces the functionality that powercfg.exe -DeviceEnableWake offers.

It has full support for:

  • Script example documentation
  • Named and positional parameters
  • Supports -WhatIf and -Confirm common parameters
  • Configuring remote computers

Download Set-DeviceWake v1.0

Output

Here is an example screenshot of the script’s execution. Please let me know if you have any feedback in the comments or at pcgeek86@gmail.com! As I said before, this is the first PowerShell module that I’ve shared, and I want to make sure it’s done right!

Running on Multiple Computers

(Updated on 2010-09-28)

So, you might be wondering how you can deploy this to multiple computers. The ComputerName parameter only takes a single computer name, rather than an array. You basically have three options here:

  1. Run from management workstation: Wrap the Set-DeviceWake function in a foreach loop, and pipe a text file with a bunch of computer names into the ForEach-Object
  2. Run from management workstation: Wrap the Set-DeviceWake function with Start-Job and a list of computer names
  3. Run on each PC individually: Deploy the script to target workstations via GPO (if they’re Windows 7), or deploy via systems management software, such as ConfigMgr

I don’t have examples handy just yet, but just thought I’d share this information at least!

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