This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Hi,
I'm currently writing a bunch of tools that require CimSessions. I noticed that I'm creating a new CimSession in each tool, doing my thing, and removing the CimSession. The controller script runs each of those tools, resulting in slow performance due to the many CimSessions being established and removed again. So I thought it's time to separate the creation of the CimSession to it's own function, and passing the session object to my tools. Since I have a bunch of old servers in the environment, there are a few that only allow Dcom. Previously, my tools always tried to use Wsman first, and if that didn't work they tried to use Dcom. So I also built that functionality into the new tool.
Any comments on the code are welcome.
A question regarding parallelism: would it be a good idea to add parallelism to this function, or would one do that in the controller script?
Function New-MXCimSession {
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline=$True,
Mandatory=$True)]
[string[]]$ComputerName,
[ValidateSet('Wsman','Dcom')]
[string]$Protocol = "Wsman",
[System.Management.Automation.PSCredential]$Credential,
[bool]$Fallback = $True
)
BEGIN {}
PROCESS {
foreach ($computer in $ComputerName) {
if ($Protocol -eq 'Wsman') {
$option = New-CimSessionOption -Protocol Wsman
}
else {
$option = New-CimSessionOption -Protocol Dcom
}
Write-Verbose "[$computer] Using protocol $Protocol to establish CimSession"
if($PsBoundParameters.containskey('Credential')) {
$params = @{
'ComputerName' = $computer
'SessionOption' = $option
'Credential' = $Credential
'ErrorAction' = 'Stop'
}
Write-Verbose "[$computer] Using credentials of $($Credential.UserName) to establish CimSession"
}
else {
$params = @{
'ComputerName' = $computer
'SessionOption' = $option
'ErrorAction' = 'Stop'
}
Write-Verbose "[$computer] Using credentials of the current user to establish CimSession"
}
Try {
New-CimSession @params
Write-Verbose "[$computer] Established CimSession using protocol $Protocol"
}
Catch {
Write-Verbose ("[{0}] Failed to establish CimSession using protocol {1}: {2}" -f $computer, $Protocol, $_)
if ($Fallback) {
if ($Protocol -eq 'Wsman') {
$Protocol = 'Dcom'
}
else {
$Protocol = 'Wsman'
}
if($PsBoundParameters.containskey('Credential')) {
$params = @{
'ComputerName' = $computer
'Protocol' = $Protocol
'Credential' = $Credential
'Fallback' = $false
}
}
else {
$params = @{
'ComputerName' = $computer
'Protocol' = $Protocol
'Fallback' = $false
}
}
Write-Verbose "[$computer] Trying to establish CimSession with fall back protocol $Protocol"
New-MXCimSession @params
} # if fallback
} # catch
} # foreach computer
} # process
END {}
}
Subreddit
Post Details
- Posted
- 7 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/PowerShell/...