I put this together a while back. The Get-FQDN function is specific to our environment, since our desktops are controlled by a team that doesn't want to all all our domains to our dns search suffix list. You could drop it altogether.
Function New-WSOCimSession{
<#
.Synopsis
Wrapper for New-CimSession, attempts to create a WinRM CIM session, and then a DCOM CIM session if necessary
.DESCRIPTION
The New-WSOCimSession cmdlet creates a CIM session. A CIM session is a client-side object representing a connection to a local computer or a remote computer. The CIM session contains
information about the connection, such as ComputerName, the protocol used for the connection, session ID and instance ID.
This cmdlet returns a CIM session object that can be used by all other CIM cmdlets.
.EXAMPLE
Create a CIM session to a specific computer
PS C:\> New-WSOCimSession -ComputerName Server01
.
.Outputs
Microsoft.Management.Infrastructure.CimSession
#>
[CmdletBinding()]
[OutputType([Microsoft.Management.Infrastructure.CimSession])]
Param(
# Param1 help description
[Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true,Position=0)]
[alias(“Name”,"ServerName")]
$ComputerName=$env:COMPUTERNAME,
[Parameter(Position=1)]
[System.Management.Automation.PSCredential]
$Credential
)
Begin{
Write-Verbose $MyInvocation.InvocationName
$CSO = New-CimSessionOption -Protocol Dcom
$PSDefaultParameterValues = @{ 'Get-CimInstance:Verbose'= $false }
}
Process
{
Write-Debug $PSBoundParameters | Format-Table
if ( $ComputerName.count -gt 1 ) { return }
$parm = @{
ComputerName = $ComputerName
ErrorAction = 'Stop'
OperationTimeout = 5
}
if ( $Credential ) { $parm['Credential'] = $Credential }
try{
$cim = New-CimSession @parm
}
catch{
switch ($PSItem.Exception)
{
{ $psitem -match "Cannot find the computer" -or $psitem -match "server name cannot be resolved" }
{
try
{
$parm['ComputerName'] = Get-FQDN $ComputerName -ErrorAction Stop
Write-Verbose $parm['ComputerName']
$cim = New-CimSession @parm
}
catch
{
throw $PSItem
}
}
{ $psitem -match "An unknown security error occurred" }
{}
Default
{
Write-Error $PSItem ; break
}
}
}
try{
$null = Get-CimInstance Win32_BIOS -CimSession $cim -ErrorAction Stop
}
Catch{
if($cim){ $cim | Remove-CimSession }
Write-Debug $PSItem.exception
try
{
$cim = New-CimSession @parm -SessionOption $CSO
}
Catch
{
Write-Error $PSItem
return
}
}
try {
$null = Get-CimInstance Win32_BIOS -CimSession $cim -ErrorAction Stop
}
Catch{
Write-Error $PSItem
return
}
$cim
}
End
{
}
}