CimSession PowerShell Scripting
Last week, I was working on updates to the PSScriptTools module. I am adding new functions based on Get-CimClass
. As I was working, I ended up diving deeper into how the CIM cmdlets work and realized I could write more efficient functions with the results of my research and testing.
Normally, whenever I write a PowerShell function that wraps around Get-CimInstance
, I always try to have parameter sets so that the user can specify a computer name or an existing CIMSession.
Function Get-CimOS {
[CmdletBinding(DefaultParameterSetName = 'ClassNameComputerSet')]
Param(
[Parameter(
Position = 0,
ParameterSetName = 'CimInstanceSessionSet',
Mandatory,
ValueFromPipeline
)]
[Microsoft.Management.Infrastructure.CimSession[]]$CimSession,
[Parameter(
Position = 0,
ParameterSetName = 'ClassNameComputerSet',
ValueFromPipeline
)]
[Alias('CN', 'ServerName')]
[string[]]$ComputerName = $env:Computername,
[Alias('OT')]
[uint32]$OperationTimeoutSec
)
Begin {
Write-Verbose "Starting $($MyInvocation.MyCommand)"
$PSBoundParameters.Add('Namespace', 'Root\CimV2')
$PSBoundParameters.Add('ClassName', 'Win32_OperatingSystem')
$PSBoundParameters.Add('ErrorAction', 'Stop')
$PSBoundParameters.Add('Property', @('CSName','Caption','Version','BuildNumber','InstallDate','OSArchitecture'))
Write-Verbose ($PSBoundParameters | Out-String)
} #begin
Process {
Write-Verbose "Using parameter set $($PSCmdlet.ParameterSetName)"
Try {
Get-CimInstance @PSBoundParameters |
Select-Object @{Name = 'Computername'; Expression = { $_.CSName } },
@{Name = 'Name'; Expression = { $_.Caption } },
Version, BuildNumber,InstallDate, OSArchitecture
}
Catch {
Write-Warning $_.Exception.Message
}
} #process
End {
Write-Verbose "Ending $($MyInvocation.MyCommand)"
} #end
} #end function Get-CimOS
I like having the flexibility.
Want to read the full issue?