// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Globalization;
using Microsoft.Management.Infrastructure.Options;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
#region CimSessionWrapper
internal class CimSessionWrapper
{
#region members
///
/// Id of the cimsession.
///
public uint SessionId
{
get
{
return this.sessionId;
}
}
private uint sessionId;
///
/// InstanceId of the cimsession.
///
public Guid InstanceId
{
get
{
return this.instanceId;
}
}
private Guid instanceId;
///
/// Name of the cimsession.
///
public string Name
{
get
{
return this.name;
}
}
private string name;
///
/// Computer name of the cimsession.
///
public string ComputerName
{
get
{
return this.computerName;
}
}
private string computerName;
///
/// Wrapped cimsession object.
///
public CimSession CimSession
{
get
{
return this.cimSession;
}
}
private CimSession cimSession;
///
/// Computer name of the cimsession.
///
public string Protocol
{
get
{
switch (protocol)
{
case ProtocolType.Dcom:
return "DCOM";
case ProtocolType.Default:
case ProtocolType.Wsman:
default:
return "WSMAN";
}
}
}
internal ProtocolType GetProtocolType()
{
return protocol;
}
private ProtocolType protocol;
///
/// PSObject that wrapped the cimSession.
///
private PSObject psObject;
#endregion
internal CimSessionWrapper(
uint theSessionId,
Guid theInstanceId,
string theName,
string theComputerName,
CimSession theCimSession,
ProtocolType theProtocol)
{
this.sessionId = theSessionId;
this.instanceId = theInstanceId;
this.name = theName;
this.computerName = theComputerName;
this.cimSession = theCimSession;
this.psObject = null;
this.protocol = theProtocol;
}
internal PSObject GetPSObject()
{
if (psObject == null)
{
psObject = new PSObject(this.cimSession);
psObject.Properties.Add(new PSNoteProperty(CimSessionState.idPropName, this.sessionId));
psObject.Properties.Add(new PSNoteProperty(CimSessionState.namePropName, this.name));
psObject.Properties.Add(new PSNoteProperty(CimSessionState.instanceidPropName, this.instanceId));
psObject.Properties.Add(new PSNoteProperty(CimSessionState.computernamePropName, this.ComputerName));
psObject.Properties.Add(new PSNoteProperty(CimSessionState.protocolPropName, this.Protocol));
}
else
{
psObject.Properties[CimSessionState.idPropName].Value = this.SessionId;
psObject.Properties[CimSessionState.namePropName].Value = this.name;
psObject.Properties[CimSessionState.instanceidPropName].Value = this.instanceId;
psObject.Properties[CimSessionState.computernamePropName].Value = this.ComputerName;
psObject.Properties[CimSessionState.protocolPropName].Value = this.Protocol;
}
return psObject;
}
}
#endregion
#region CimSessionState
///
///
/// Class used to hold all cimsession related status data related to a runspace.
/// Including the CimSession cache, session counters for generating session name.
///
///
internal class CimSessionState : IDisposable
{
#region private members
///
/// Default session name.
/// If a name is not passed, then the session is given the name CimSession,
/// where is the next available session number.
/// For example, CimSession1, CimSession2, etc...
///
internal static string CimSessionClassName = "CimSession";
///
/// CimSession object name.
///
internal static string CimSessionObject = "{CimSession Object}";
///
///
/// CimSession object path, which is identifying a cimsession object
///
///
internal static string SessionObjectPath = @"CimSession id = {0}, name = {2}, ComputerName = {3}, instance id = {1}";
///
/// Id property name of cimsession wrapper object.
///
internal static string idPropName = "Id";
///
/// Instanceid property name of cimsession wrapper object.
///
internal static string instanceidPropName = "InstanceId";
///
/// Name property name of cimsession wrapper object.
///
internal static string namePropName = "Name";
///
/// Computer name property name of cimsession object.
///
internal static string computernamePropName = "ComputerName";
///
/// Protocol name property name of cimsession object.
///
internal static string protocolPropName = "Protocol";
///
///
/// session counter bound to current runspace.
///
///
private UInt32 sessionNameCounter;
///
///
/// Dictionary used to holds all CimSessions in current runspace by session name.
///
///
private Dictionary> curCimSessionsByName;
///
///
/// Dictionary used to holds all CimSessions in current runspace by computer name.
///
///
private Dictionary> curCimSessionsByComputerName;
///
///
/// Dictionary used to holds all CimSessions in current runspace by instance ID.
///
///
private Dictionary curCimSessionsByInstanceId;
///
///
/// Dictionary used to holds all CimSessions in current runspace by session id.
///
///
private Dictionary curCimSessionsById;
///
///
/// Dictionary used to link CimSession object with PSObject.
///
///
private Dictionary curCimSessionWrapper;
#endregion
///
///
/// constructor
///
///
internal CimSessionState()
{
sessionNameCounter = 1;
curCimSessionsByName = new Dictionary>(
StringComparer.OrdinalIgnoreCase);
curCimSessionsByComputerName = new Dictionary>(
StringComparer.OrdinalIgnoreCase);
curCimSessionsByInstanceId = new Dictionary();
curCimSessionsById = new Dictionary();
curCimSessionWrapper = new Dictionary();
}
///
///
/// Get sessions count.
///
///
/// The count of session objects in current runspace.
internal int GetSessionsCount()
{
return this.curCimSessionsById.Count;
}
///
///
/// Generates an unique session id.
///
///
/// Unique session id under current runspace.
internal UInt32 GenerateSessionId()
{
return this.sessionNameCounter++;
}
#region IDisposable
///
///
/// Indicates whether this object was disposed or not
///
///
private bool _disposed;
///
///
/// Dispose() calls Dispose(true).
/// Implement IDisposable. Do not make this method virtual.
/// A derived class should not be able to override this method.
///
///
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SuppressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
///
///
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
///
///
/// Whether it is directly called.
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// free managed resources
Cleanup();
this._disposed = true;
}
// free native resources if there are any
}
}
///
///
/// Performs application-defined tasks associated with freeing, releasing, or
/// resetting unmanaged resources.
///
///
public void Cleanup()
{
foreach (CimSession session in curCimSessionWrapper.Keys)
{
session.Dispose();
}
curCimSessionWrapper.Clear();
curCimSessionsByName.Clear();
curCimSessionsByComputerName.Clear();
curCimSessionsByInstanceId.Clear();
curCimSessionsById.Clear();
sessionNameCounter = 1;
}
#endregion
#region Add CimSession to/remove CimSession from cache
///
///
/// Add new CimSession object to cache
///
///
///
///
///
///
///
internal PSObject AddObjectToCache(
CimSession session,
UInt32 sessionId,
Guid instanceId,
string name,
string computerName,
ProtocolType protocol)
{
CimSessionWrapper wrapper = new CimSessionWrapper(
sessionId, instanceId, name, computerName, session, protocol);
HashSet objects;
if (!this.curCimSessionsByComputerName.TryGetValue(computerName, out objects))
{
objects = new HashSet();
this.curCimSessionsByComputerName.Add(computerName, objects);
}
objects.Add(wrapper);
if (!this.curCimSessionsByName.TryGetValue(name, out objects))
{
objects = new HashSet();
this.curCimSessionsByName.Add(name, objects);
}
objects.Add(wrapper);
this.curCimSessionsByInstanceId.Add(instanceId, wrapper);
this.curCimSessionsById.Add(sessionId, wrapper);
this.curCimSessionWrapper.Add(session, wrapper);
return wrapper.GetPSObject();
}
///
///
/// Generates remove session message by given wrapper object.
///
///
///
internal string GetRemoveSessionObjectTarget(PSObject psObject)
{
string message = string.Empty;
if (psObject.BaseObject is CimSession)
{
UInt32 id = 0x0;
Guid instanceId = Guid.Empty;
string name = string.Empty;
string computerName = string.Empty;
if (psObject.Properties[idPropName].Value is UInt32)
{
id = Convert.ToUInt32(psObject.Properties[idPropName].Value, null);
}
if (psObject.Properties[instanceidPropName].Value is Guid)
{
instanceId = (Guid)psObject.Properties[instanceidPropName].Value;
}
if (psObject.Properties[namePropName].Value is string)
{
name = (string)psObject.Properties[namePropName].Value;
}
if (psObject.Properties[computernamePropName].Value is string)
{
computerName = (string)psObject.Properties[computernamePropName].Value;
}
message = string.Format(CultureInfo.CurrentUICulture, SessionObjectPath, id, instanceId, name, computerName);
}
return message;
}
///
///
/// Remove given object from cache
///
///
///
internal void RemoveOneSessionObjectFromCache(PSObject psObject)
{
DebugHelper.WriteLogEx();
if (psObject.BaseObject is CimSession)
{
RemoveOneSessionObjectFromCache(psObject.BaseObject as CimSession);
}
}
///
///
/// Remove given object from cache
///
///
///
internal void RemoveOneSessionObjectFromCache(CimSession session)
{
DebugHelper.WriteLogEx();
if (!this.curCimSessionWrapper.ContainsKey(session))
{
return;
}
CimSessionWrapper wrapper = this.curCimSessionWrapper[session];
string name = wrapper.Name;
string computerName = wrapper.ComputerName;
DebugHelper.WriteLog("name {0}, computername {1}, id {2}, instanceId {3}", 1, name, computerName, wrapper.SessionId, wrapper.InstanceId);
HashSet objects;
if (this.curCimSessionsByComputerName.TryGetValue(computerName, out objects))
{
objects.Remove(wrapper);
}
if (this.curCimSessionsByName.TryGetValue(name, out objects))
{
objects.Remove(wrapper);
}
RemoveSessionInternal(session, wrapper);
}
///
///
/// Remove given object from partial of the cache only.
///
///
///
///
private void RemoveSessionInternal(CimSession session, CimSessionWrapper wrapper)
{
DebugHelper.WriteLogEx();
this.curCimSessionsByInstanceId.Remove(wrapper.InstanceId);
this.curCimSessionsById.Remove(wrapper.SessionId);
this.curCimSessionWrapper.Remove(session);
session.Dispose();
}
#endregion
#region Query CimSession from cache
///
///
/// Add ErrorRecord to list.
///
///
///
///
///
private void AddErrorRecord(
ref List errRecords,
string propertyName,
object propertyValue)
{
errRecords.Add(
new ErrorRecord(
new CimException(string.Format(CultureInfo.CurrentUICulture, Strings.CouldNotFindCimsessionObject, propertyName, propertyValue)),
string.Empty,
ErrorCategory.ObjectNotFound,
null));
}
///
/// Query session list by given id array.
///
///
/// List of session wrapper objects.
internal IEnumerable QuerySession(IEnumerable ids,
out IEnumerable errorRecords)
{
HashSet sessions = new HashSet();
HashSet sessionIds = new HashSet();
List errRecords = new List();
errorRecords = errRecords;
// NOTES: use template function to implement this will save duplicate code
foreach (UInt32 id in ids)
{
if (this.curCimSessionsById.ContainsKey(id))
{
if (!sessionIds.Contains(id))
{
sessionIds.Add(id);
sessions.Add(this.curCimSessionsById[id].GetPSObject());
}
}
else
{
AddErrorRecord(ref errRecords, idPropName, id);
}
}
return sessions;
}
///
/// Query session list by given instance id array.
///
///
/// List of session wrapper objects.
internal IEnumerable QuerySession(IEnumerable instanceIds,
out IEnumerable errorRecords)
{
HashSet sessions = new HashSet();
HashSet sessionIds = new HashSet();
List errRecords = new List();
errorRecords = errRecords;
foreach (Guid instanceid in instanceIds)
{
if (this.curCimSessionsByInstanceId.ContainsKey(instanceid))
{
CimSessionWrapper wrapper = this.curCimSessionsByInstanceId[instanceid];
if (!sessionIds.Contains(wrapper.SessionId))
{
sessionIds.Add(wrapper.SessionId);
sessions.Add(wrapper.GetPSObject());
}
}
else
{
AddErrorRecord(ref errRecords, instanceidPropName, instanceid);
}
}
return sessions;
}
///
/// Query session list by given name array.
///
///
/// List of session wrapper objects.
internal IEnumerable QuerySession(IEnumerable nameArray,
out IEnumerable errorRecords)
{
HashSet sessions = new HashSet();
HashSet sessionIds = new HashSet();
List errRecords = new List();
errorRecords = errRecords;
foreach (string name in nameArray)
{
bool foundSession = false;
WildcardPattern pattern = new WildcardPattern(name, WildcardOptions.IgnoreCase);
foreach (KeyValuePair> kvp in this.curCimSessionsByName)
{
if (pattern.IsMatch(kvp.Key))
{
HashSet wrappers = kvp.Value;
foundSession = (wrappers.Count > 0);
foreach (CimSessionWrapper wrapper in wrappers)
{
if (!sessionIds.Contains(wrapper.SessionId))
{
sessionIds.Add(wrapper.SessionId);
sessions.Add(wrapper.GetPSObject());
}
}
}
}
if (!foundSession && !WildcardPattern.ContainsWildcardCharacters(name))
{
AddErrorRecord(ref errRecords, namePropName, name);
}
}
return sessions;
}
///
/// Query session list by given computer name array.
///
///
/// List of session wrapper objects.
internal IEnumerable QuerySessionByComputerName(
IEnumerable computernameArray,
out IEnumerable errorRecords)
{
HashSet sessions = new HashSet();
HashSet sessionIds = new HashSet();
List errRecords = new List();
errorRecords = errRecords;
foreach (string computername in computernameArray)
{
bool foundSession = false;
if (this.curCimSessionsByComputerName.ContainsKey(computername))
{
HashSet wrappers = this.curCimSessionsByComputerName[computername];
foundSession = (wrappers.Count > 0);
foreach (CimSessionWrapper wrapper in wrappers)
{
if (!sessionIds.Contains(wrapper.SessionId))
{
sessionIds.Add(wrapper.SessionId);
sessions.Add(wrapper.GetPSObject());
}
}
}
if (!foundSession)
{
AddErrorRecord(ref errRecords, computernamePropName, computername);
}
}
return sessions;
}
///
/// Query session list by given session objects array.
///
///
/// List of session wrapper objects.
internal IEnumerable QuerySession(IEnumerable cimsessions,
out IEnumerable errorRecords)
{
HashSet sessions = new HashSet();
HashSet sessionIds = new HashSet();
List errRecords = new List();
errorRecords = errRecords;
foreach (CimSession cimsession in cimsessions)
{
if (this.curCimSessionWrapper.ContainsKey(cimsession))
{
CimSessionWrapper wrapper = this.curCimSessionWrapper[cimsession];
if (!sessionIds.Contains(wrapper.SessionId))
{
sessionIds.Add(wrapper.SessionId);
sessions.Add(wrapper.GetPSObject());
}
}
else
{
AddErrorRecord(ref errRecords, CimSessionClassName, CimSessionObject);
}
}
return sessions;
}
///
/// Query session wrapper object.
///
///
/// Session wrapper.
internal CimSessionWrapper QuerySession(CimSession cimsession)
{
CimSessionWrapper wrapper;
this.curCimSessionWrapper.TryGetValue(cimsession, out wrapper);
return wrapper;
}
///
/// Query session object with given CimSessionInstanceID.
///
///
/// CimSession object.
internal CimSession QuerySession(Guid cimSessionInstanceId)
{
if (this.curCimSessionsByInstanceId.ContainsKey(cimSessionInstanceId))
{
CimSessionWrapper wrapper = this.curCimSessionsByInstanceId[cimSessionInstanceId];
return wrapper.CimSession;
}
return null;
}
#endregion
}
#endregion
#region CimSessionBase
///
///
/// Base class of all session operation classes.
/// All sessions created will be held in a ConcurrentDictionary:cimSessions.
/// It manages the lifecycle of the sessions being created for each
/// runspace according to the state of the runspace.
///
///
internal class CimSessionBase
{
#region constructor
///
/// Constructor.
///
public CimSessionBase()
{
this.sessionState = cimSessions.GetOrAdd(
CurrentRunspaceId,
delegate (Guid instanceId)
{
if (Runspace.DefaultRunspace != null)
{
Runspace.DefaultRunspace.StateChanged += DefaultRunspace_StateChanged;
}
return new CimSessionState();
});
}
#endregion
#region members
///
///
/// Thread safe static dictionary to store session objects associated
/// with each runspace, which is identified by a GUID. NOTE: cmdlet
/// can running parallelly under more than one runspace(s).
///
///
internal static ConcurrentDictionary cimSessions
= new ConcurrentDictionary();
///
///
/// Default runspace id
///
///
internal static Guid defaultRunspaceId = Guid.Empty;
///
///
/// Object used to hold all CimSessions and status data bound
/// to current runspace.
///
///
internal CimSessionState sessionState;
///
/// Get current runspace id.
///
private static Guid CurrentRunspaceId
{
get
{
if (Runspace.DefaultRunspace != null)
{
return Runspace.DefaultRunspace.InstanceId;
}
else
{
return CimSessionBase.defaultRunspaceId;
}
}
}
#endregion
public static CimSessionState GetCimSessionState()
{
CimSessionState state = null;
cimSessions.TryGetValue(CurrentRunspaceId, out state);
return state;
}
///
///
/// clean up the dictionaries if the runspace is closed or broken.
///
///
/// Runspace.
/// Event args.
private static void DefaultRunspace_StateChanged(object sender, RunspaceStateEventArgs e)
{
Runspace runspace = (Runspace)sender;
switch (e.RunspaceStateInfo.State)
{
case RunspaceState.Broken:
case RunspaceState.Closed:
CimSessionState state;
if (cimSessions.TryRemove(runspace.InstanceId, out state))
{
DebugHelper.WriteLog(string.Format(CultureInfo.CurrentUICulture, DebugHelper.runspaceStateChanged, runspace.InstanceId, e.RunspaceStateInfo.State));
state.Dispose();
}
runspace.StateChanged -= DefaultRunspace_StateChanged;
break;
default:
break;
}
}
}
#endregion
#region CimTestConnection
#endregion
#region CimNewSession
///
///
/// CimNewSession is the class to create cimSession
/// based on given NewCimSessionCommand.
///
///
internal class CimNewSession : CimSessionBase, IDisposable
{
///
/// CimTestCimSessionContext.
///
internal class CimTestCimSessionContext : XOperationContextBase
{
///
///
/// Constructor
///
///
///
///
internal CimTestCimSessionContext(
CimSessionProxy theProxy,
CimSessionWrapper wrapper)
{
this.proxy = theProxy;
this.cimSessionWrapper = wrapper;
this.nameSpace = null;
}
///
/// namespace
///
internal CimSessionWrapper CimSessionWrapper
{
get
{
return this.cimSessionWrapper;
}
}
private CimSessionWrapper cimSessionWrapper;
}
///
///
/// constructor
///
///
internal CimNewSession() : base()
{
this.cimTestSession = new CimTestSession();
this._disposed = false;
}
///
/// Create a new base on given cmdlet
/// and its parameter.
///
///
///
///
internal void NewCimSession(NewCimSessionCommand cmdlet,
CimSessionOptions sessionOptions,
CimCredential credential)
{
DebugHelper.WriteLogEx();
IEnumerable computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName);
foreach (string computerName in computerNames)
{
CimSessionProxy proxy;
if (sessionOptions == null)
{
DebugHelper.WriteLog("Create CimSessionOption due to NewCimSessionCommand has null sessionoption", 1);
sessionOptions = CimSessionProxy.CreateCimSessionOption(computerName,
cmdlet.OperationTimeoutSec, credential);
}
proxy = new CimSessionProxyTestConnection(computerName, sessionOptions);
string computerNameValue = (computerName == ConstValue.NullComputerName) ? ConstValue.LocalhostComputerName : computerName;
CimSessionWrapper wrapper = new CimSessionWrapper(0, Guid.Empty, cmdlet.Name, computerNameValue, proxy.CimSession, proxy.Protocol);
CimTestCimSessionContext context = new CimTestCimSessionContext(proxy, wrapper);
proxy.ContextObject = context;
// Skip test the connection if user intend to
if (cmdlet.SkipTestConnection.IsPresent)
{
AddSessionToCache(proxy.CimSession, context, new CmdletOperationBase(cmdlet));
}
else
{
// CimSession will be returned as part of TestConnection
this.cimTestSession.TestCimSession(computerName, proxy);
}
}
}
///
///
/// Add session to global cache
///
///
///
///
///
internal void AddSessionToCache(CimSession cimSession, XOperationContextBase context, CmdletOperationBase cmdlet)
{
DebugHelper.WriteLogEx();
CimTestCimSessionContext testCimSessionContext = context as CimTestCimSessionContext;
UInt32 sessionId = this.sessionState.GenerateSessionId();
string originalSessionName = testCimSessionContext.CimSessionWrapper.Name;
string sessionName = (originalSessionName != null) ? originalSessionName : string.Format(CultureInfo.CurrentUICulture, @"{0}{1}", CimSessionState.CimSessionClassName, sessionId);
// detach CimSession from the proxy object
CimSession createdCimSession = testCimSessionContext.Proxy.Detach();
PSObject psObject = this.sessionState.AddObjectToCache(
createdCimSession,
sessionId,
createdCimSession.InstanceId,
sessionName,
testCimSessionContext.CimSessionWrapper.ComputerName,
testCimSessionContext.Proxy.Protocol);
cmdlet.WriteObject(psObject, null);
}
///
///
/// process all actions in the action queue
///
///
///
/// wrapper of cmdlet, for details
///
public void ProcessActions(CmdletOperationBase cmdletOperation)
{
this.cimTestSession.ProcessActions(cmdletOperation);
}
///
///
/// process remaining actions until all operations are completed or
/// current cmdlet is terminated by user
///
///
///
/// wrapper of cmdlet, for details
///
public void ProcessRemainActions(CmdletOperationBase cmdletOperation)
{
this.cimTestSession.ProcessRemainActions(cmdletOperation);
}
#region private members
///
///
/// object.
///
///
private CimTestSession cimTestSession;
#endregion // private members
#region IDisposable
///
///
/// Indicates whether this object was disposed or not
///
///
protected bool Disposed
{
get
{
return _disposed;
}
}
private bool _disposed;
///
///
/// Dispose() calls Dispose(true).
/// Implement IDisposable. Do not make this method virtual.
/// A derived class should not be able to override this method.
///
///
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SuppressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
///
///
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
///
///
/// Whether it is directly called.
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// free managed resources
this.cimTestSession.Dispose();
this._disposed = true;
}
// free native resources if there are any
}
}
#endregion
}
#endregion
#region CimGetSession
///
///
/// Get CimSession based on given id/instanceid/computername/name
///
///
internal class CimGetSession : CimSessionBase
{
///
/// Constructor.
///
public CimGetSession() : base()
{
}
///
/// Get objects based on the given cmdlet
/// and its parameter.
///
///
public void GetCimSession(GetCimSessionCommand cmdlet)
{
DebugHelper.WriteLogEx();
IEnumerable sessionToGet = null;
IEnumerable errorRecords = null;
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.ComputerNameSet:
if (cmdlet.ComputerName == null)
{
sessionToGet = this.sessionState.QuerySession(ConstValue.DefaultSessionName, out errorRecords);
}
else
{
sessionToGet = this.sessionState.QuerySessionByComputerName(cmdlet.ComputerName, out errorRecords);
}
break;
case CimBaseCommand.SessionIdSet:
sessionToGet = this.sessionState.QuerySession(cmdlet.Id, out errorRecords);
break;
case CimBaseCommand.InstanceIdSet:
sessionToGet = this.sessionState.QuerySession(cmdlet.InstanceId, out errorRecords);
break;
case CimBaseCommand.NameSet:
sessionToGet = this.sessionState.QuerySession(cmdlet.Name, out errorRecords);
break;
default:
break;
}
if (sessionToGet != null)
{
foreach (PSObject psobject in sessionToGet)
{
cmdlet.WriteObject(psobject);
}
}
if (errorRecords != null)
{
foreach (ErrorRecord errRecord in errorRecords)
{
cmdlet.WriteError(errRecord);
}
}
}
#region helper methods
#endregion
}
#endregion
#region CimRemoveSession
///
///
/// Get CimSession based on given id/instanceid/computername/name
///
///
internal class CimRemoveSession : CimSessionBase
{
///
/// Remove session action string.
///
internal static string RemoveCimSessionActionName = "Remove CimSession";
///
/// Constructor.
///
public CimRemoveSession() : base()
{
}
///
/// Remove the objects based on given cmdlet
/// and its parameter.
///
///
public void RemoveCimSession(RemoveCimSessionCommand cmdlet)
{
DebugHelper.WriteLogEx();
IEnumerable sessionToRemove = null;
IEnumerable errorRecords = null;
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.CimSessionSet:
sessionToRemove = this.sessionState.QuerySession(cmdlet.CimSession, out errorRecords);
break;
case CimBaseCommand.ComputerNameSet:
sessionToRemove = this.sessionState.QuerySessionByComputerName(cmdlet.ComputerName, out errorRecords);
break;
case CimBaseCommand.SessionIdSet:
sessionToRemove = this.sessionState.QuerySession(cmdlet.Id, out errorRecords);
break;
case CimBaseCommand.InstanceIdSet:
sessionToRemove = this.sessionState.QuerySession(cmdlet.InstanceId, out errorRecords);
break;
case CimBaseCommand.NameSet:
sessionToRemove = this.sessionState.QuerySession(cmdlet.Name, out errorRecords);
break;
default:
break;
}
if (sessionToRemove != null)
{
foreach (PSObject psobject in sessionToRemove)
{
if (cmdlet.ShouldProcess(this.sessionState.GetRemoveSessionObjectTarget(psobject), RemoveCimSessionActionName))
{
this.sessionState.RemoveOneSessionObjectFromCache(psobject);
}
}
}
if (errorRecords != null)
{
foreach (ErrorRecord errRecord in errorRecords)
{
cmdlet.WriteError(errRecord);
}
}
}
}
#endregion
#region CimTestSession
///
/// Class , which is used to
/// test cimsession and execute async operations.
///
internal class CimTestSession : CimAsyncOperation
{
///
/// Constructor.
///
internal CimTestSession()
: base()
{
}
///
/// Test the session connection with
/// given object.
///
///
///
internal void TestCimSession(
string computerName,
CimSessionProxy proxy)
{
DebugHelper.WriteLogEx();
this.SubscribeEventAndAddProxytoCache(proxy);
proxy.TestConnectionAsync();
}
}
#endregion
}