Categories

CDXML–scripting creation

So far you’ve seen how to create CDXML files by hand – though you probably used cut and paste rather than typing everything from scratch.

Its time to bring a bit of automation to creating CDXML files. The XML is fairly simple and you’re only changing a couple of values so you can do this:

function new-cdxml {
[CmdletBinding()]
param (
[string]$class,
[string]$noun,
[string]$namespace = 'ROOT\cimv2',
[string]$path = "C:\Scripts\Modules\Hardware"
)

$code = @"
<?xml version='1.0' encoding='utf-8'?>
<PowerShellMetadata xmlns='http://schemas.microsoft.com/cmdlets-over-objects/2009/11'>
  <Class ClassName='$namespace\$class'>
    <Version>1.0</Version>
    <DefaultNoun>$noun</DefaultNoun>

    <InstanceCmdlets>
      <GetCmdletParameters DefaultCmdletParameterSet='DefaultSet'>
             
      </GetCmdletParameters>
    </InstanceCmdlets> 
  </Class>
 
</PowerShellMetadata>
"@

$file = Join-Path -Path $path -ChildPath "$class.cdxml"
Write-Verbose -Message  $file
Set-Content -Path $file -Value $code

}

I saved this as NewCDXML.ps1.  This will eventually  become the basis of a CDXML file creation module. I set defaults on the namespace and the path – feel free to change them if required.

The function is run as:

new-cdxml -class Win32_DiskDrive -noun PhysicalDisk

which produces this CDXML file

<?xml version='1.0' encoding='utf-8'?>
<PowerShellMetadata xmlns='http://schemas.microsoft.com/cmdlets-over-objects/2009/11'>
  <Class ClassName='ROOT\cimv2\Win32_DiskDrive'>
    <Version>1.0</Version>
    <DefaultNoun>PhysicalDisk</DefaultNoun>

    <InstanceCmdlets>
      <GetCmdletParameters DefaultCmdletParameterSet='DefaultSet'>
             
      </GetCmdletParameters>
    </InstanceCmdlets> 
  </Class>
 
</PowerShellMetadata>

 

The Hardware.psd1 file needs to be altered:

# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
NestedModules = @('Win32_BIOS.cdxml',
                   'Win32_ComputerSystem.cdxml',
                   'Win32_DiskDrive.cdxml'
                    )

 

and

# Functions to export from this module
FunctionsToExport = @('Get-Bios',
                      'Get-ComputerSystem',
                      'Get-PhysicalDisk'
                      )

 

The module now looks like this:

£> Get-Command -Module Hardware

CommandType      Name
-----------                ----
Function                Get-Bios
Function                Get-ComputerSystem
Function                Get-PhysicalDisk

 

This makes creating additional components for your module much easier.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>