Copy cs files from [SD:717473]

commit 96877403a6a2eb9dcbee0f71bbc6dfb6e61dd9a3

- Microsoft.WSMan.Runtime
- Microsoft.WSMan.Management
- Microsoft.Management.Infrastructure.CimCmdlets
This commit is contained in:
PowerShell Team authored and Sergei Vorobev committed 2016-07-14 13:46:29 -07:00
1 parent 132d98e3c7
commit bc6990f46b
53 files changed
+29751

No files matched your search

@@ -0,0 +1,201 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Management.Automation;
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
public abstract class BinaryMiLogBase : PSCmdlet
{
internal const string Noun = "BinaryMiLog";
internal BinaryMiLogBase()
{
}
[Parameter(Mandatory = true, Position = 0)]
[ValidateNotNullOrEmpty]
public string Path { get; set; }
#region Path utilities copied from internal admin/monad/src/utils/PathUtils.cs
/* command.Context.ProviderNames.FileSystem is internal */
private const string FileSystemProviderName = "FileSystem";
private static string ResolveFilePath(string filePath, PSCmdlet command, bool isLiteralPath)
{
string path = null;
try
{
ProviderInfo provider = null;
PSDriveInfo drive = null;
List<string> filePaths = new List<string>();
if (isLiteralPath)
{
filePaths.Add(command.SessionState.Path.GetUnresolvedProviderPathFromPSPath(filePath, out provider, out drive));
}
else
{
filePaths.AddRange(command.SessionState.Path.GetResolvedProviderPathFromPSPath(filePath, out provider));
}
/* command.Context.ProviderNames.FileSystem is internal */
if (!provider.Name.Equals(FileSystemProviderName, StringComparison.OrdinalIgnoreCase))
{
ReportWrongProviderType(command, provider.Name);
}
if (filePaths.Count > 1)
{
ReportMultipleFilesNotSupported(command);
}
if (filePaths.Count == 0)
{
ReportWildcardingFailure(command, filePath);
}
path = filePaths[0];
}
catch (ItemNotFoundException)
{
if (!isLiteralPath)
{
return ResolveFilePath(filePath, command, isLiteralPath: true);
}
else
{
throw;
}
}
return path;
}
internal string GetVerifiedFilePath(FileAccess fileAccess)
{
string resolvedPath = ResolveFilePath(this.Path, this, isLiteralPath: false);
try
{
FileMode fileMode;
FileShare fileShare;
switch (fileAccess)
{
case FileAccess.Read:
fileMode = FileMode.Open;
fileShare = FileShare.Read;
break;
case FileAccess.Write:
fileMode = FileMode.Create;
fileShare = FileShare.None;
break;
default:
throw new ArgumentOutOfRangeException("fileAccess");
}
using (new FileStream(resolvedPath, fileMode, fileAccess, fileShare))
{
/* open and immediately close the file - to get exception in PowerShell style;
* obviously there is a race here - we can still get error from mibincodec.dll later on */
}
}
catch (ArgumentException e)
{
// NOTE: this call will throw
ReportFileOpenFailure(this, resolvedPath, e);
}
catch (IOException e)
{
// NOTE: this call will throw
ReportFileOpenFailure(this, resolvedPath, e);
}
catch (UnauthorizedAccessException e)
{
// NOTE: this call will throw
ReportFileOpenFailure(this, resolvedPath, e);
}
catch (NotSupportedException e)
{
// NOTE: this call will throw
ReportFileOpenFailure(this, resolvedPath, e);
}
catch (System.Security.SecurityException e)
{
// NOTE: this call will throw
ReportFileOpenFailure(this, resolvedPath, e);
}
return resolvedPath;
}
private static void ReportFileOpenFailure(Cmdlet cmdlet, string filePath, Exception e)
{
ErrorRecord errorRecord = new ErrorRecord(
e,
"FileOpenFailure",
ErrorCategory.OpenError,
null);
cmdlet.ThrowTerminatingError(errorRecord);
}
internal static void ReportWrongProviderType(Cmdlet cmdlet, string providerId)
{
string msg = string.Format(
CultureInfo.InvariantCulture, /* providerId is culture invariant */
Strings.ReadWriteFileNotFileSystemProvider,
providerId);
var errorRecord = new ErrorRecord (
new InvalidOperationException(msg),
"ReadWriteFileNotFileSystemProvider",
ErrorCategory.InvalidArgument,
null);
errorRecord.ErrorDetails = new ErrorDetails(msg);
cmdlet.ThrowTerminatingError(errorRecord);
}
internal static void ReportMultipleFilesNotSupported(Cmdlet cmdlet)
{
string msg = Strings.MultipleFilesNotSupported;
var errorRecord = new ErrorRecord (
new InvalidOperationException(msg),
"ReadWriteMultipleFilesNotSupported",
ErrorCategory.InvalidArgument,
null);
errorRecord.ErrorDetails = new ErrorDetails(msg);
cmdlet.ThrowTerminatingError(errorRecord);
}
internal static void ReportWildcardingFailure(Cmdlet cmdlet, string filePath)
{
string msg = string.Format(
CultureInfo.InvariantCulture, /* filePath is culture invariant */
Strings.DidNotResolveFile,
filePath);
var errorRecord = new ErrorRecord (
new FileNotFoundException(msg),
"FileOpenFailure",
ErrorCategory.OpenError,
filePath);
errorRecord.ErrorDetails = new ErrorDetails(msg);
cmdlet.ThrowTerminatingError(errorRecord);
}
#endregion
}
}
@@ -0,0 +1,589 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Management.Automation;
using System.Threading;
using System.Globalization;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Async operation base class, it will issue async operation through
/// 1...* CimSession object(s), processing the async results, extended
/// pssemantics operations, and manage the lifecycle of created
/// CimSession object(s).
/// </para>
/// </summary>
internal abstract class CimAsyncOperation : IDisposable
{
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public CimAsyncOperation()
{
this.moreActionEvent = new ManualResetEventSlim(false);
this.actionQueue = new ConcurrentQueue<CimBaseAction>();
this._disposed = 0;
this.operationCount = 0;
}
#endregion
#region Event handler
/// <summary>
/// <para>
/// Handler used to handle new action event from
/// <seealso cref="CimSessionProxy"/> object.
/// </para>
/// </summary>
/// <param name="cimSession">
/// <seealso cref="CimSession"/> object raised the event
/// </param>
/// <param name="actionArgs">event argument</param>
protected void NewCmdletActionHandler(object cimSession, CmdletActionEventArgs actionArgs)
{
DebugHelper.WriteLogEx("Disposed {0}, action type = {1}", 0, this._disposed, actionArgs.Action);
if (this.Disposed)
{
if (actionArgs.Action is CimSyncAction)
{
// unblock the thread waiting for response
(actionArgs.Action as CimSyncAction).OnComplete();
}
return;
}
bool isEmpty = this.actionQueue.IsEmpty;
this.actionQueue.Enqueue(actionArgs.Action);
if (isEmpty)
{
this.moreActionEvent.Set();
}
}
/// <summary>
/// <para>
/// Handler used to handle new operation event from
/// <seealso cref="CimSessionProxy"/> object.
/// </para>
/// </summary>
/// <param name="cimSession">
/// <seealso cref="CimSession"/> object raised the event
/// </param>
/// <param name="actionArgs">event argument</param>
protected void OperationCreatedHandler(object cimSession, OperationEventArgs actionArgs)
{
DebugHelper.WriteLogEx();
lock (this.myLock)
{
this.operationCount++;
}
}
/// <summary>
/// <para>
/// Handler used to handle operation deletion event from
/// <seealso cref="CimSessionProxy"/> object.
/// </para>
/// </summary>
/// <param name="cimSession">
/// <seealso cref="CimSession"/> object raised the event
/// </param>
/// <param name="actionArgs">event argument</param>
protected void OperationDeletedHandler(object cimSession, OperationEventArgs actionArgs)
{
DebugHelper.WriteLogEx();
lock (this.myLock)
{
this.operationCount--;
if (this.operationCount == 0)
{
this.moreActionEvent.Set();
}
}
}
#endregion
/// <summary>
/// <para>
/// process all actions in the action queue
/// </para>
/// </summary>
/// <param name="cmdletOperation">
/// wrapper of cmdlet, <seealso cref="CmdletOperationBase"/> for details
/// </param>
public void ProcessActions(CmdletOperationBase cmdletOperation)
{
if (!this.actionQueue.IsEmpty)
{
CimBaseAction action;
while (GetActionAndRemove(out action))
{
action.Execute(cmdletOperation);
if (this.Disposed)
{
break;
}
}
}
}
/// <summary>
/// <para>
/// process remaining actions until all operations are completed or
/// current cmdlet is terminated by user
/// </para>
/// </summary>
/// <param name="cmdletOperation">
/// wrapper of cmdlet, <seealso cref="CmdletOperationBase"/> for details
/// </param>
public void ProcessRemainActions(CmdletOperationBase cmdletOperation)
{
DebugHelper.WriteLogEx();
while (true)
{
ProcessActions(cmdletOperation);
if (!this.IsActive())
{
DebugHelper.WriteLogEx("Either disposed or all operations completed.", 2);
break;
}
try
{
this.moreActionEvent.Wait();
this.moreActionEvent.Reset();
}
catch (ObjectDisposedException ex)
{
// This might happen if this object is being disposed,
// while another thread is processing the remaining actions
DebugHelper.WriteLogEx("moreActionEvent was disposed: {0}.", 2, ex);
break;
}
}
ProcessActions(cmdletOperation);
}
#region helper methods
/// <summary>
/// <para>
/// Get action object from action queue
/// </para>
/// </summary>
/// <param name="action">next action to execute</param>
/// <returns>true indicates there is an valid action, otherwise false</returns>
protected bool GetActionAndRemove(out CimBaseAction action)
{
return this.actionQueue.TryDequeue(out action);
}
/// <summary>
/// <para>
/// Add temporary <seealso cref="CimSessionProxy"/> object to cache.
/// </para>
/// </summary>
/// <param name="computerName">Computer name of the cimsession</param>
/// <param name="sessionproxy">cimsession wrapper object</param>
protected void AddCimSessionProxy(CimSessionProxy sessionproxy)
{
lock (cimSessionProxyCacheLock)
{
if (this.cimSessionProxyCache == null)
{
this.cimSessionProxyCache = new List<CimSessionProxy>();
}
if (!this.cimSessionProxyCache.Contains(sessionproxy))
{
this.cimSessionProxyCache.Add(sessionproxy);
}
}
}
/// <summary>
/// <para>
/// Are there active operations?
/// </para>
/// </summary>
/// <returns>true for having active operations, otherwise false.</returns>
protected bool IsActive()
{
DebugHelper.WriteLogEx("Disposed {0}, Operation Count {1}", 2, this.Disposed, this.operationCount);
bool isActive = (!this.Disposed) && (this.operationCount > 0);
return isActive;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object.
/// </summary>
/// <param name="session"></param>
protected CimSessionProxy CreateCimSessionProxy(CimSessionProxy originalProxy)
{
CimSessionProxy proxy = new CimSessionProxy(originalProxy);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object.
/// </summary>
/// <param name="session"></param>
protected CimSessionProxy CreateCimSessionProxy(CimSessionProxy originalProxy, bool passThru)
{
CimSessionProxy proxy = new CimSessionProxySetCimInstance(originalProxy, passThru);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object.
/// </summary>
/// <param name="session"></param>
protected CimSessionProxy CreateCimSessionProxy(CimSession session)
{
CimSessionProxy proxy = new CimSessionProxy(session);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object.
/// </summary>
/// <param name="session"></param>
protected CimSessionProxy CreateCimSessionProxy(CimSession session, bool passThru)
{
CimSessionProxy proxy = new CimSessionProxySetCimInstance(session, passThru);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object, and
/// add the proxy into cache.
/// </summary>
/// <param name="computerName"></param>
protected CimSessionProxy CreateCimSessionProxy(string computerName)
{
CimSessionProxy proxy = new CimSessionProxy(computerName);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object, and
/// add the proxy into cache.
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <returns></returns>
protected CimSessionProxy CreateCimSessionProxy(string computerName,
CimInstance cimInstance)
{
CimSessionProxy proxy = new CimSessionProxy(computerName, cimInstance);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object, and
/// add the proxy into cache.
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <param name="passThru"></param>
protected CimSessionProxy CreateCimSessionProxy(string computerName, CimInstance cimInstance, bool passThru)
{
CimSessionProxy proxy = new CimSessionProxySetCimInstance(computerName, cimInstance, passThru);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Subscribe event from proxy and add proxy to cache
/// </summary>
/// <param name="proxy"></param>
protected void SubscribeEventAndAddProxytoCache(CimSessionProxy proxy)
{
this.AddCimSessionProxy(proxy);
SubscribeToCimSessionProxyEvent(proxy);
}
/// <summary>
/// <para>
/// Subscribe to the events issued by <see cref="CimSessionProxy"/>.
/// </para>
/// </summary>
/// <param name="proxy"></param>
protected virtual void SubscribeToCimSessionProxyEvent(CimSessionProxy proxy)
{
DebugHelper.WriteLogEx();
proxy.OnNewCmdletAction += this.NewCmdletActionHandler;
proxy.OnOperationCreated += this.OperationCreatedHandler;
proxy.OnOperationDeleted += this.OperationDeletedHandler;
}
/// <summary>
/// Retrieve the base object out if wrapped in psobject
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
protected object GetBaseObject(object value)
{
PSObject psObject = value as PSObject;
if (psObject == null)
{
return value;
}
else
{
object baseObject = psObject.BaseObject;
var arrayObject = baseObject as object[];
if (arrayObject == null)
{
return baseObject;
}
else
{
object[] arraybaseObject = new object[arrayObject.Length];
for (int i = 0; i < arrayObject.Length; i++)
{
arraybaseObject[i] = GetBaseObject(arrayObject[i]);
}
return arraybaseObject;
}
}
}
/// <summary>
/// Retrieve the reference object or reference array object.
/// The returned object has to be either CimInstance or CImInstance[] type,
/// if not thrown exception.
/// </summary>
/// <param name="value"></param>
/// <param name="referenceType">output the cimtype of the value, either Reference or ReferenceArray</param>
/// <returns></returns>
protected object GetReferenceOrReferenceArrayObject(object value, ref CimType referenceType)
{
PSReference cimReference = value as PSReference;
if (cimReference != null)
{
object baseObject = GetBaseObject(cimReference.Value);
CimInstance cimInstance = baseObject as CimInstance;
if (cimInstance == null)
{
return null;
}
referenceType = CimType.Reference;
return cimInstance;
}
else
{
object[] cimReferenceArray = value as object[];
if (cimReferenceArray == null)
{
return null;
}
else if (!(cimReferenceArray[0] is PSReference))
{
return null;
}
CimInstance[] cimInstanceArray = new CimInstance[cimReferenceArray.Length];
for (int i = 0; i < cimReferenceArray.Length; i++)
{
PSReference tempCimReference = cimReferenceArray[i] as PSReference;
if (tempCimReference == null)
{
return null;
}
object baseObject = GetBaseObject(tempCimReference.Value);
cimInstanceArray[i] = baseObject as CimInstance;
if (cimInstanceArray[i] == null)
{
return null;
}
}
referenceType = CimType.ReferenceArray;
return cimInstanceArray;
}
}
#endregion
#region IDisposable
/// <summary>
/// <para>
/// Indicates whether this object was disposed or not
/// </para>
/// </summary>
protected bool Disposed
{
get
{
return (Interlocked.Read(ref this._disposed) == 1);
}
}
private long _disposed;
/// <summary>
/// <para>
/// Dispose() calls Dispose(true).
/// Implement IDisposable. Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </para>
/// </summary>
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// <para>
/// 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.
/// </para>
/// </summary>
/// <param name="disposing">Whether it is directly called</param>
protected virtual void Dispose(bool disposing)
{
if (Interlocked.CompareExchange(ref this._disposed, 1, 0) == 0)
{
if (disposing)
{
// free managed resources
Cleanup();
}
// free native resources if there are any
}
}
/// <summary>
/// <para>
/// Clean up managed resources
/// </para>
/// </summary>
private void Cleanup()
{
DebugHelper.WriteLogEx();
// unblock thread that waiting for more actions
this.moreActionEvent.Set();
CimBaseAction action;
while (GetActionAndRemove(out action))
{
DebugHelper.WriteLog("Action {0}", 2, action);
if (action is CimSyncAction)
{
// unblock the thread waiting for response
(action as CimSyncAction).OnComplete();
}
}
if (this.cimSessionProxyCache != null)
{
List<CimSessionProxy> temporaryProxy;
lock (this.cimSessionProxyCache)
{
temporaryProxy = new List<CimSessionProxy>(this.cimSessionProxyCache);
this.cimSessionProxyCache.Clear();
}
// clean up all proxy objects
foreach (CimSessionProxy proxy in temporaryProxy)
{
DebugHelper.WriteLog("Dispose proxy ", 2);
proxy.Dispose();
}
}
this.moreActionEvent.Dispose();
if (this.ackedEvent != null)
{
this.ackedEvent.Dispose();
}
DebugHelper.WriteLog("Cleanup complete.", 2);
}
#endregion
#region private members
/// <summary>
/// lock object
/// </summary>
private readonly object myLock = new object();
/// <summary>
/// number of active operations
/// </summary>
private UInt32 operationCount = 0;
/// <summary>
/// Event to notify ps thread that more action is available
/// </summary>
private ManualResetEventSlim moreActionEvent;
/// <summary>
/// The following is the definition of action queue.
/// The queue holding all actions to be exected in the context of either
/// ProcessRecord or EndProcessing.
/// </summary>
private ConcurrentQueue<CimBaseAction> actionQueue;
/// <summary>
/// lock object
/// </summary>
private readonly object cimSessionProxyCacheLock = new object();
/// <summary>
/// cache all <see cref="CimSessionProxy"/> objects related to
/// the current operation.
/// </summary>
private List<CimSessionProxy> cimSessionProxyCache;
#endregion
#region protected members
/// <summary>
/// Event to notify ps thread that either a ACK message sent back
/// or a error happened. Currently only used by class
/// <see cref="CimRegisterCimIndication"/>.
/// </summary>
protected ManualResetEventSlim ackedEvent;
#endregion
#region const strings
internal const string ComputerNameArgument = @"ComputerName";
internal const string CimSessionArgument = @"CimSession";
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,201 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System.Threading;
using Microsoft.Management.Infrastructure.Options;
using System;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// Base action class, implemented to write results to pipeline.
/// </summary>
internal abstract class CimBaseAction
{
/// <summary>
/// Constructor method.
/// </summary>
public CimBaseAction()
{
}
/// <summary>
/// <para>
/// Execute the write opration to given cmdlet object
/// </para>
/// </summary>
/// <param name="cmdlet">
/// cmdlet wrapper object, to which write result.
/// <see cref="CmdletOperationBase"/> for details.
/// </param>
public virtual void Execute(CmdletOperationBase cmdlet)
{
}
/// <summary>
/// <para>
/// <see cref="XOperationContextBase"/> object that related to current action.
/// It may used by action, such as <see cref="CimWriteResultObject"/>,
/// since later on action may require namspace, and proxy object to reuse
/// <see cref="CimSession"/>, <see cref="CimOperationOptions"/> object.
/// </para>
/// </summary>
protected XOperationContextBase Context
{
get
{
return this.context;
}
set
{
this.context = value;
}
}
private XOperationContextBase context;
}//End Class
/// <summary>
/// <para>
/// Synchronous action class, implemented to write results to pipeline
/// and block current thread until the action is completed.
/// </para>
/// </summary>
internal class CimSyncAction : CimBaseAction, IDisposable
{
/// <summary>
/// Constructor
/// </summary>
public CimSyncAction()
{
this.completeEvent = new ManualResetEventSlim(false);
this.responseType = CimResponseType.None;
}
/// <summary>
/// <para>
/// Block current thread until action completed
/// </para>
/// </summary>
/// <returns>Response from user</returns>
public virtual CimResponseType GetResponse()
{
this.Block();
return responseType;
}
/// <summary>
/// <para>
/// Set response result
/// </para>
/// </summary>
internal CimResponseType ResponseType
{
set { this.responseType = value; }
}
/// <summary>
/// <para>
/// Call this method when the action is completed or
/// the operation is terminated
/// </para>
/// </summary>
internal virtual void OnComplete()
{
this.completeEvent.Set();
}
/// <summary>
/// <para>
/// block current thread.
/// </para>
/// </summary>
protected virtual void Block()
{
this.completeEvent.Wait();
this.completeEvent.Dispose();
}
#region members
/// <summary>
/// action completed event
/// </summary>
private ManualResetEventSlim completeEvent;
/// <summary>
/// response result
/// </summary>
protected CimResponseType responseType;
#endregion
#region IDisposable interface
/// <summary>
/// IDisposable interface
/// </summary>
private bool _disposed;
/// <summary>
/// <para>
/// Dispose() calls Dispose(true).
/// Implement IDisposable. Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </para>
/// </summary>
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// <para>
/// 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.
/// </para>
/// </summary>
/// <param name="disposing">Whether it is directly called</param>
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this._disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
// Dispose managed resources.
if (this.completeEvent != null)
{
this.completeEvent.Dispose();
}
}
// Call the appropriate methods to clean up
// unmanaged resources here.
// If disposing is false,
// only the following code is executed.
// Note disposing has been done.
_disposed = true;
}
}
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,116 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Initialize the cimcmdlets.
/// </para>
/// </summary>
/// <summary>
/// Provide a hook to the engine for startup initialization
/// w.r.t compiled assembly loading.
/// </summary>
public sealed class CimCmdletsAssemblyInitializer : IModuleAssemblyInitializer
{
/// <summary>
/// <para>
/// constructor
/// </para>
/// </summary>
public CimCmdletsAssemblyInitializer()
{
}
/// <summary>
/// PowerShell engine will call this method when the cimcmdlets module
/// is loaded.
/// </summary>
public void OnImport()
{
DebugHelper.WriteLogEx();
using (System.Management.Automation.PowerShell invoker = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
{
foreach (CimCmdletAliasEntry alias in Aliases)
{
invoker.AddScript(string.Format(CultureInfo.CurrentUICulture, "Set-Alias -Name {0} -Value {1} -Option {2} -ErrorAction SilentlyContinue", alias.Name, alias.Value, alias.Options));
DebugHelper.WriteLog(@"Add commands {0} of {1} with option {2} to current runspace.", 1, alias.Name, alias.Value, alias.Options);
}
System.Collections.ObjectModel.Collection<PSObject> psObjects = invoker.Invoke();
DebugHelper.WriteLog(@"Invoke results {0}.", 1, psObjects.Count);
}
}
#region readonly string
/// <summary>
/// <para>
/// CimCmdlet alias entry
/// </para>
/// </summary>
internal sealed class CimCmdletAliasEntry
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
internal CimCmdletAliasEntry(string name, string value)
{
this._name = name;
this._value = value;
}
/// <summary>
/// The string defining the name of this alias
/// </summary>
internal string Name { get { return this._name; } }
private string _name;
/// <summary>
/// The string defining realy cmdlet name
/// </summary>
internal string Value { get { return this._value; } }
private string _value = String.Empty;
/// <summary>
/// The string defining realy cmdlet name
/// </summary>
internal ScopedItemOptions Options { get { return this._options; } }
private ScopedItemOptions _options = ScopedItemOptions.AllScope | ScopedItemOptions.ReadOnly;
}
/// <summary>
/// Returns a new array of alias entries everytime it's called.
/// </summary>
internal static CimCmdletAliasEntry[] Aliases = new CimCmdletAliasEntry[] {
new CimCmdletAliasEntry("gcim", "Get-CimInstance"),
new CimCmdletAliasEntry("scim", "Set-CimInstance"),
new CimCmdletAliasEntry("ncim", "New-CimInstance "),
new CimCmdletAliasEntry("rcim", "Remove-cimInstance"),
new CimCmdletAliasEntry("icim", "Invoke-CimMethod"),
new CimCmdletAliasEntry("gcai", "Get-CimAssociatedInstance"),
new CimCmdletAliasEntry("rcie", "Register-CimIndicationEvent"),
new CimCmdletAliasEntry("ncms", "New-CimSession"),
new CimCmdletAliasEntry("rcms", "Remove-cimSession"),
new CimCmdletAliasEntry("gcms", "Get-CimSession"),
new CimCmdletAliasEntry("ncso", "New-CimSessionOption"),
new CimCmdletAliasEntry("gcls", "Get-CimClass"),
};
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,988 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Management.Automation;
using System.Net;
using System.Text;
using Microsoft.Management.Infrastructure.Options;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
#region Parameter Set Resolving Classes
/// <summary>
/// <para>
/// Define class <c>ParameterDefinitionEntry</c>.
/// </para>
/// </summary>
internal class ParameterDefinitionEntry
{
/// <summary>
/// constructor
/// </summary>
/// <param name="parameterSetName"></param>
/// <param name="mandatory"></param>
internal ParameterDefinitionEntry(string parameterSetName, bool mandatory)
{
this.mandatory = mandatory;
this.parameterSetName = parameterSetName;
}
/// <summary>
/// property ParameterSetName
/// </summary>
internal string ParameterSetName
{
get
{
return this.parameterSetName;
}
}
private readonly string parameterSetName = null;
/// <summary>
/// Whether the parameter is mandatory to the set
/// </summary>
internal bool IsMandatory
{
get
{
return this.mandatory;
}
}
private readonly bool mandatory = false;
}
/// <summary>
/// <para>
/// Define class <c>ParameterSetEntry</c>.
/// </para>
/// </summary>
internal class ParameterSetEntry
{
/// <summary>
/// constructor
/// </summary>
/// <param name="mandatoryParameterCount"></param>
internal ParameterSetEntry(UInt32 mandatoryParameterCount)
{
this.mandatoryParameterCount = mandatoryParameterCount;
this.isDefaultParameterSet = false;
reset();
}
/// <summary>
/// constructor
/// </summary>
/// <param name="toClone"></param>
internal ParameterSetEntry(ParameterSetEntry toClone)
{
this.mandatoryParameterCount = toClone.MandatoryParameterCount;
this.isDefaultParameterSet = toClone.IsDefaultParameterSet;
reset();
}
/// <summary>
/// constructor
/// </summary>
/// <param name="mandatoryParameterCount"></param>
/// <param name="mandatory"></param>
internal ParameterSetEntry(UInt32 mandatoryParameterCount, bool isDefault)
{
this.mandatoryParameterCount = mandatoryParameterCount;
this.isDefaultParameterSet = isDefault;
reset();
}
/// <summary>
/// reset the internal status
/// </summary>
internal void reset()
{
this.setMandatoryParameterCount = this.setMandatoryParameterCountAtBeginProcess;
this.isValueSet = this.isValueSetAtBeginProcess;
}
/// <summary>
/// property <c>DefaultParameterSet</c>
/// </summary>
internal bool IsDefaultParameterSet
{
get
{
return this.isDefaultParameterSet;
}
}
private readonly bool isDefaultParameterSet = false;
/// <summary>
/// property <c>MandatoryParameterCount</c>
/// </summary>
internal UInt32 MandatoryParameterCount
{
get
{
return this.mandatoryParameterCount;
}
}
private readonly UInt32 mandatoryParameterCount = 0;
/// <summary>
/// property <c>IsValueSet</c>
/// </summary>
internal bool IsValueSet
{
get
{
return this.isValueSet;
}
set
{
this.isValueSet = value;
}
}
private bool isValueSet = false;
/// <summary>
/// property <c>IsValueSetAtBeginProcess</c>
/// </summary>
internal bool IsValueSetAtBeginProcess
{
get
{
return this.isValueSetAtBeginProcess;
}
set
{
this.isValueSetAtBeginProcess = value;
}
}
private bool isValueSetAtBeginProcess = false;
/// <summary>
/// property <c>SetMandatoryParameterCount</c>
/// </summary>
internal UInt32 SetMandatoryParameterCount
{
get
{
return this.setMandatoryParameterCount;
}
set
{
this.setMandatoryParameterCount = value;
}
}
private UInt32 setMandatoryParameterCount = 0;
/// <summary>
/// property <c>SetMandatoryParameterCountAtBeginProcess</c>
/// </summary>
internal UInt32 SetMandatoryParameterCountAtBeginProcess
{
get
{
return this.setMandatoryParameterCountAtBeginProcess;
}
set
{
this.setMandatoryParameterCountAtBeginProcess = value;
}
}
private UInt32 setMandatoryParameterCountAtBeginProcess = 0;
}
/// <summary>
/// Define class <c>ParameterBinder</c>.
/// </summary>
internal class ParameterBinder
{
/// <summary>
/// constructor
/// </summary>
/// <param name="parameters"></param>
/// <param name="sets"></param>
internal ParameterBinder(
Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters,
Dictionary<string, ParameterSetEntry> sets)
{
this.CloneParameterEntries(parameters, sets);
}
#region Two dictionaryies used to determine the bound parameter set
/// <summary>
/// Define the parameter definition entries,
/// each parameter may belong a set of parameterSets, each parameter set
/// are defined by a <seealso cref="ParameterDefinitionEntry"/>.
/// </summary>
private Dictionary<string, HashSet<ParameterDefinitionEntry>> parameterDefinitionEntries;
/// <summary>
/// <para>
/// Define parameter set entries,
/// each cmdlet has a list of parameter set, each has number of mandatory parameters, etc.
/// This data structure is used to track the number of mandatory parameter has been set for
/// current parameterset, whether the parameter set was been set by user.
/// </para>
/// </summary>
private Dictionary<string, ParameterSetEntry> parameterSetEntries;
#endregion
/// <summary>
/// <para>
/// Used to remember the set of parameterset were set
/// if any conflition occurred with current parameter,
/// throw exception
/// </para>
/// </summary>
private List<string> parametersetNamesList = new List<string>();
/// <summary>
/// Parameter names list
/// </summary>
private List<string> parameterNamesList = new List<string>();
/// <summary>
/// <para>
/// Used to remember the set of parameterset were set before begin process
/// if any conflition occurred with current parameter,
/// throw exception
/// </para>
/// </summary>
private List<string> parametersetNamesListAtBeginProcess = new List<string>();
/// <summary>
/// Parameter names list befre begin process
/// </summary>
private List<string> parameterNamesListAtBeginProcess = new List<string>();
/// <summary>
/// <para>
/// Reset the status of parameter set entries
/// </para>
/// </summary>
internal void reset()
{
foreach (KeyValuePair<string, ParameterSetEntry> setEntry in parameterSetEntries)
{
setEntry.Value.reset();
}
this.parametersetNamesList.Clear();
foreach (string parametersetName in this.parametersetNamesListAtBeginProcess)
{
this.parametersetNamesList.Add(parametersetName);
}
this.parameterNamesList.Clear();
foreach (string parameterName in this.parameterNamesListAtBeginProcess)
{
this.parameterNamesList.Add(parameterName);
}
}
/// <summary>
/// <para>
/// A given parameter's value was set by cmdlet caller,
/// check and change the status of parameter set,
/// throw exception if confliction occurred
/// </para>
/// </summary>
/// <param name="parameterName"></param>
/// <exception cref="PSArgumentException">throw if conflict parameter was set</exception>
internal void SetParameter(string parameterName, bool isBeginProcess)
{
DebugHelper.WriteLogEx("ParameterName = {0}, isBeginProcess = {1}", 0, parameterName, isBeginProcess);
if (this.parameterNamesList.Contains(parameterName))
{
DebugHelper.WriteLogEx("ParameterName {0} is already bound ", 1, parameterName);
return;
}
else
{
this.parameterNamesList.Add(parameterName);
if (isBeginProcess)
{
this.parameterNamesListAtBeginProcess.Add(parameterName);
}
}
if (this.parametersetNamesList.Count == 0)
{
List<string> nameset = new List<string>();
foreach (ParameterDefinitionEntry parameterDefinitionEntry in this.parameterDefinitionEntries[parameterName])
{
DebugHelper.WriteLogEx("parameterset name = '{0}'; mandatory = '{1}'", 1, parameterDefinitionEntry.ParameterSetName, parameterDefinitionEntry.IsMandatory);
ParameterSetEntry psEntry = this.parameterSetEntries[parameterDefinitionEntry.ParameterSetName];
if (psEntry == null)
continue;
if (parameterDefinitionEntry.IsMandatory)
{
psEntry.SetMandatoryParameterCount++;
if (isBeginProcess)
{
psEntry.SetMandatoryParameterCountAtBeginProcess++;
}
DebugHelper.WriteLogEx("parameterset name = '{0}'; SetMandatoryParameterCount = '{1}'", 1, parameterDefinitionEntry.ParameterSetName, psEntry.SetMandatoryParameterCount);
}
if (!psEntry.IsValueSet)
{
psEntry.IsValueSet = true;
if (isBeginProcess)
{
psEntry.IsValueSetAtBeginProcess = true;
}
}
nameset.Add(parameterDefinitionEntry.ParameterSetName);
}
this.parametersetNamesList = nameset;
if (isBeginProcess)
{
this.parametersetNamesListAtBeginProcess = nameset;
}
}
else
{
List<string> nameset = new List<string>();
foreach (ParameterDefinitionEntry entry in this.parameterDefinitionEntries[parameterName])
{
if (this.parametersetNamesList.Contains(entry.ParameterSetName))
{
nameset.Add(entry.ParameterSetName);
if (entry.IsMandatory)
{
ParameterSetEntry psEntry = this.parameterSetEntries[entry.ParameterSetName];
psEntry.SetMandatoryParameterCount++;
if (isBeginProcess)
{
psEntry.SetMandatoryParameterCountAtBeginProcess++;
}
DebugHelper.WriteLogEx("parameterset name = '{0}'; SetMandatoryParameterCount = '{1}'",
1,
entry.ParameterSetName,
psEntry.SetMandatoryParameterCount);
}
}
}
if (nameset.Count == 0)
{
throw new PSArgumentException(Strings.UnableToResolvePareameterSetName);
}
else
{
this.parametersetNamesList = nameset;
if (isBeginProcess)
{
this.parametersetNamesListAtBeginProcess = nameset;
}
}
}
}
/// <summary>
/// Get the parameter set name based on current binding results
/// </summary>
/// <returns></returns>
internal string GetParameterSet()
{
DebugHelper.WriteLogEx();
string boundParameterSetName = null;
string defaultParameterSetName = null;
List<string> noMandatoryParameterSet = new List<string>();
// Looking for parameter set which have mandatory parameters
foreach (string parameterSetName in this.parameterSetEntries.Keys)
{
ParameterSetEntry entry = this.parameterSetEntries[parameterSetName];
DebugHelper.WriteLogEx(
"parameterset name = {0}, {1}/{2} mandatory parameters.",
1,
parameterSetName,
entry.SetMandatoryParameterCount,
entry.MandatoryParameterCount);
// Ignore the parameter set which has no mandatory parameter firstly
if (entry.MandatoryParameterCount == 0)
{
if (entry.IsDefaultParameterSet)
{
defaultParameterSetName = parameterSetName;
}
if (entry.IsValueSet)
{
noMandatoryParameterSet.Add(parameterSetName);
}
continue;
}
if ((entry.SetMandatoryParameterCount == entry.MandatoryParameterCount) &&
this.parametersetNamesList.Contains(parameterSetName))
{
if (boundParameterSetName != null)
{
throw new PSArgumentException(Strings.UnableToResolvePareameterSetName);
}
boundParameterSetName = parameterSetName;
}
}
// Looking for parameter set which has no mandatory parameters
if (boundParameterSetName == null)
{
// throw if there are > 1 parameter set
if (noMandatoryParameterSet.Count > 1)
{
throw new PSArgumentException(Strings.UnableToResolvePareameterSetName);
}
else if (noMandatoryParameterSet.Count == 1)
{
boundParameterSetName = noMandatoryParameterSet[0];
}
}
// Looking for default parameter set
if (boundParameterSetName == null)
{
boundParameterSetName = defaultParameterSetName;
}
// throw if still can not find the parameter set name
if (boundParameterSetName == null)
{
throw new PSArgumentException(Strings.UnableToResolvePareameterSetName);
}
return boundParameterSetName;
}
/// <summary>
/// Deep clone the parameter entries to member variable
/// </summary>
private void CloneParameterEntries(
Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters,
Dictionary<string, ParameterSetEntry> sets)
{
this.parameterDefinitionEntries = parameters;
this.parameterSetEntries = new Dictionary<string, ParameterSetEntry>();
foreach (KeyValuePair<string, ParameterSetEntry> parameterSet in sets)
{
this.parameterSetEntries.Add(parameterSet.Key, new ParameterSetEntry(parameterSet.Value));
}
}
}
#endregion
/// <summary>
/// Base command for all cim cmdlets
/// </summary>
public class CimBaseCommand : Cmdlet, IDisposable
{
#region resolve parameter set name
/// <summary>
/// <para>
/// Check set parameters and set ParameterSetName
/// </para>
/// <para>
/// Following are special types to be handled
/// Microsoft.Management.Infrastructure.Options.PacketEncoding
/// Microsoft.Management.Infrastructure.Options.ImpersonationType
/// UInt32
/// Authentication.None (default value)?
/// ProxyType.None
/// </para>
/// </summary>
internal void CheckParameterSet()
{
if (this.parameterBinder != null)
{
try
{
this.parameterSetName = this.parameterBinder.GetParameterSet();
}
finally
{
this.parameterBinder.reset();
}
}
DebugHelper.WriteLog("current parameterset is: " + this.parameterSetName, 4);
}
/// <summary>
/// Redirect to parameterBinder to set one parameter
/// </summary>
/// <param name="parameterName"></param>
internal void SetParameter(object value, string parameterName)
{
// Ignore the null value being set,
// Null value could be set by caller unintentionally,
// or by powershell to reset the parameter to default value
// before the next parameter binding, and ProcessRecord call
if (value == null)
{
return;
}
if (this.parameterBinder != null)
{
this.parameterBinder.SetParameter(parameterName, this.AtBeginProcess);
}
}
#endregion
#region constructors
/// <summary>
/// constructor
/// </summary>
internal CimBaseCommand()
{
this.disposed = false;
this.parameterBinder = null;
}
/// <summary>
/// constructor
/// </summary>
internal CimBaseCommand(Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters,
Dictionary<string, ParameterSetEntry> sets)
{
this.disposed = false;
this.parameterBinder = new ParameterBinder(parameters, sets);
}
#endregion
#region override functions of Cmdlet
/// <summary>
/// StopProcessing method.
/// </summary>
protected override void StopProcessing()
{
Dispose();
}//End StopProcessing()
#endregion
#region IDisposable interface
/// <summary>
/// IDisposable interface
/// </summary>
private bool disposed;
/// <summary>
/// <para>
/// Dispose() calls Dispose(true).
/// Implement IDisposable. Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </para>
/// </summary>
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// <para>
/// 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.
/// </para>
/// </summary>
/// <param name="disposing">Whether it is directly called</param>
protected void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
DisposeInternal();
}
// Call the appropriate methods to clean up
// unmanaged resources here.
// If disposing is false,
// only the following code is executed.
// Note disposing has been done.
disposed = true;
}
}
/// <summary>
/// Clean up resources
/// </summary>
protected virtual void DisposeInternal()
{
// Dispose managed resources.
if (this.operation != null)
{
this.operation.Dispose();
}
}
#endregion
#region private members
/// <summary>
/// Parameter binder used to resolve parameter set name
/// </summary>
private ParameterBinder parameterBinder;
/// <summary>
/// <para>
/// Async operation handler
/// </para>
/// </summary>
private CimAsyncOperation operation;
/// <summary>
/// lock object
/// </summary>
private readonly object myLock = new object();
/// <summary>
/// <para>
/// parameter set name
/// </para>
/// </summary>
private string parameterSetName;
/// <summary>
/// This flag is introduced to resolve the parameter set name
/// during process record
/// Whether at begin process time, false means in processrecord
/// </summary>
private bool atBeginProcess = true;
internal bool AtBeginProcess
{
get
{
return this.atBeginProcess;
}
set
{
this.atBeginProcess = value;
}
}
#endregion
#region internal properties
/// <summary>
/// <para>
/// Set <see cref="CimAsyncOperation"/> object, to which
/// current cmdlet will delegate all operations.
/// </para>
/// </summary>
internal CimAsyncOperation AsyncOperation
{
set
{
lock (this.myLock)
{
Debug.Assert(this.operation == null, "Caller should verify that operation is null");
this.operation = value;
}
}
get
{
return this.operation;
}
}
/// <summary>
/// <para>
/// Get current ParameterSetName of the cmdlet
/// </para>
/// </summary>
internal string ParameterSetName
{
get
{
return this.parameterSetName;
}
}
/// <summary>
/// Gets/Sets cmdlet operation wrapper object
/// </summary>
internal virtual CmdletOperationBase CmdletOperation
{
get;
set;
}
/// <summary>
/// <para>
/// Throw terminating error
/// </para>
/// </summary>
internal void ThrowTerminatingError(Exception exception, string operation)
{
ErrorRecord errorRecord = new ErrorRecord(exception, operation, ErrorCategory.InvalidOperation, this);
this.CmdletOperation.ThrowTerminatingError(errorRecord);
}
#endregion
#region internal const strings
/// <summary>
/// alias CN - computer name
/// </summary>
internal const string AliasCN = "CN";
/// <summary>
/// alias ServerName - computer name
/// </summary>
internal const string AliasServerName = "ServerName";
/// <summary>
/// alias OT - operation timeout
/// </summary>
internal const string AliasOT = "OT";
/// <summary>
/// session set name
/// </summary>
internal const string SessionSetName = "SessionSet";
/// <summary>
/// computer set name
/// </summary>
internal const string ComputerSetName = "ComputerSet";
/// <summary>
/// class name computer set name
/// </summary>
internal const string ClassNameComputerSet = "ClassNameComputerSet";
/// <summary>
/// resource Uri computer set name
/// </summary>
internal const string ResourceUriComputerSet = "ResourceUriComputerSet";
/// <summary>
/// <see cref="CimInstance"/> computer set name
/// </summary>
internal const string CimInstanceComputerSet = "CimInstanceComputerSet";
/// <summary>
/// query computer set name
/// </summary>
internal const string QueryComputerSet = "QueryComputerSet";
/// <summary>
/// class name session set name
/// </summary>
internal const string ClassNameSessionSet = "ClassNameSessionSet";
/// <summary>
/// resource Uri session set name
/// </summary>
internal const string ResourceUriSessionSet = "ResourceUriSessionSet";
/// <summary>
/// <see cref="CimInstance"/> session set name
/// </summary>
internal const string CimInstanceSessionSet = "CimInstanceSessionSet";
/// <summary>
/// query session set name
/// </summary>
internal const string QuerySessionSet = "QuerySessionSet";
/// <summary>
/// <see cref="CimClass"/> computer set name
/// </summary>
internal const string CimClassComputerSet = "CimClassComputerSet";
/// <summary>
/// <see cref="CimClass"/> session set name
/// </summary>
internal const string CimClassSessionSet = "CimClassSessionSet";
#region Session related parameter set name
internal const string ComputerNameSet = "ComputerNameSet";
internal const string SessionIdSet = "SessionIdSet";
internal const string InstanceIdSet = "InstanceIdSet";
internal const string NameSet = "NameSet";
internal const string CimSessionSet = "CimSessionSet";
internal const string WSManParameterSet = "WSManParameterSet";
internal const string DcomParameterSet = "DcomParameterSet";
internal const string ProtocolNameParameterSet = "ProtocolTypeSet";
#endregion
#region register cimindication parameter set name
internal const string QueryExpressionSessionSet = "QueryExpressionSessionSet";
internal const string QueryExpressionComputerSet = "QueryExpressionComputerSet";
#endregion
/// <summary>
/// credential parameter set
/// </summary>
internal const string CredentialParameterSet = "CredentialParameterSet";
/// <summary>
/// certificate parameter set
/// </summary>
internal const string CertificatePrameterSet = "CertificatePrameterSet";
/// <summary>
/// CimInstance parameter alias
/// </summary>
internal const string AliasCimInstance = "CimInstance";
#endregion
#region internal helper function
/// <summary>
/// <para>
/// Throw invalid AuthenticationType
/// </para>
/// </summary>
/// <param name="operationName"></param>
/// <param name="parameterName"></param>
/// <param name="authentication"></param>
internal void ThrowInvalidAuthenticationTypeError(
string operationName,
string parameterName,
PasswordAuthenticationMechanism authentication)
{
string message = String.Format(CultureInfo.CurrentUICulture, Strings.InvalidAuthenticationTypeWithNullCredential,
authentication,
ImpersonatedAuthenticationMechanism.None,
ImpersonatedAuthenticationMechanism.Negotiate,
ImpersonatedAuthenticationMechanism.Kerberos,
ImpersonatedAuthenticationMechanism.NtlmDomain);
PSArgumentOutOfRangeException exception = new PSArgumentOutOfRangeException(
parameterName, authentication, message);
ThrowTerminatingError(exception, operationName);
}
/// <summary>
/// Throw conflict parameter error
/// </summary>
/// <param name="operationName"></param>
/// <param name="parameterName"></param>
/// <param name="conflictParameterName"></param>
internal void ThrowConflictParameterWasSet(
string operationName,
string parameterName,
string conflictParameterName)
{
string message = String.Format(CultureInfo.CurrentUICulture,
Strings.ConflictParameterWasSet,
parameterName, conflictParameterName);
PSArgumentException exception = new PSArgumentException(message, parameterName);
ThrowTerminatingError(exception, operationName);
}
/// <summary>
/// <para>
/// Throw not found property error
/// </para>
/// </summary>
internal void ThrowInvalidProperty(
IEnumerable<string> propertiesList,
string className,
string parameterName,
string operationName,
IDictionary actualValue)
{
StringBuilder propList = new StringBuilder();
foreach (string property in propertiesList)
{
if (propList.Length > 0)
{
propList.Append(",");
}
propList.Append(property);
}
string message = String.Format(CultureInfo.CurrentUICulture, Strings.CouldNotFindPropertyFromGivenClass,
className, propList);
PSArgumentOutOfRangeException exception = new PSArgumentOutOfRangeException(
parameterName, actualValue, message);
ThrowTerminatingError(exception, operationName);
}
/// <summary>
/// Create credentials based on given authentication type and PSCredential
/// </summary>
/// <param name="psCredentials"></param>
/// <param name="passwordAuthentication"></param>
/// <returns></returns>
internal CimCredential CreateCimCredentials(PSCredential psCredentials,
PasswordAuthenticationMechanism passwordAuthentication,
string operationName,
string parameterName)
{
DebugHelper.WriteLogEx("PSCredential:{0}; PasswordAuthenticationMechanism:{1}; operationName:{2}; parameterName:{3}.", 0, psCredentials, passwordAuthentication, operationName, parameterName);
CimCredential credentials = null;
if (psCredentials != null)
{
NetworkCredential networkCredential = psCredentials.GetNetworkCredential();
DebugHelper.WriteLog("Domain:{0}; UserName:{1}; Password:{2}.", 1, networkCredential.Domain, networkCredential.UserName, psCredentials.Password);
credentials = new CimCredential(passwordAuthentication, networkCredential.Domain, networkCredential.UserName, psCredentials.Password);
}
else
{
ImpersonatedAuthenticationMechanism impersonatedAuthentication;
switch (passwordAuthentication)
{
case PasswordAuthenticationMechanism.Default:
impersonatedAuthentication = ImpersonatedAuthenticationMechanism.None;
break;
case PasswordAuthenticationMechanism.Negotiate:
impersonatedAuthentication = ImpersonatedAuthenticationMechanism.Negotiate;
break;
case PasswordAuthenticationMechanism.Kerberos:
impersonatedAuthentication = ImpersonatedAuthenticationMechanism.Kerberos;
break;
case PasswordAuthenticationMechanism.NtlmDomain:
impersonatedAuthentication = ImpersonatedAuthenticationMechanism.NtlmDomain;
break;
default:
ThrowInvalidAuthenticationTypeError(operationName, parameterName, passwordAuthentication);
return null;
}
credentials = new CimCredential(impersonatedAuthentication);
}
DebugHelper.WriteLogEx("return credential {0}", 1, credentials);
return credentials;
}
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,139 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System.Collections;
using System;
using System.Collections.Generic;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Implements operations of get-AssociatedInstance cmdlet.
/// </para>
/// </summary>
internal sealed class CimGetAssociatedInstance : CimAsyncOperation
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
public CimGetAssociatedInstance()
: base()
{
}
/// <summary>
/// <para>
/// Base on parametersetName to retrieve associated ciminstances
/// </para>
/// </summary>
/// <param name="cmdlet"><see cref="GetCimInstanceCommand"/> object</param>
public void GetCimAssociatedInstance(GetCimAssociatedInstanceCommand cmdlet)
{
IEnumerable<string> computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName);
// use the namespace from parameter
string nameSpace = cmdlet.Namespace;
if ((nameSpace == null) && (cmdlet.ResourceUri == null))
{
// try to use namespace of ciminstance, then fall back to default namespace
nameSpace = ConstValue.GetNamespace(cmdlet.CimInstance.CimSystemProperties.Namespace);
}
List<CimSessionProxy> proxys = new List<CimSessionProxy>();
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.ComputerSetName:
foreach (string computerName in computerNames)
{
CimSessionProxy proxy = CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet);
proxys.Add(proxy);
}
break;
case CimBaseCommand.SessionSetName:
foreach (CimSession session in cmdlet.CimSession)
{
CimSessionProxy proxy = CreateSessionProxy(session, cmdlet);
proxys.Add(proxy);
}
break;
default:
return;
}
foreach (CimSessionProxy proxy in proxys)
{
proxy.EnumerateAssociatedInstancesAsync(
nameSpace,
cmdlet.CimInstance,
cmdlet.Association,
cmdlet.ResultClassName,
null,
null);
}
}
#region private methods
/// <summary>
/// <para>
/// Set <see cref="CimSessionProxy"/> properties
/// </para>
/// </summary>
/// <param name="proxy"></param>
/// <param name="cmdlet"></param>
private void SetSessionProxyProperties(
ref CimSessionProxy proxy,
GetCimAssociatedInstanceCommand cmdlet)
{
proxy.OperationTimeout = cmdlet.OperationTimeoutSec;
proxy.KeyOnly = cmdlet.KeyOnly;
if (cmdlet.ResourceUri != null)
{
proxy.ResourceUri = cmdlet.ResourceUri;
}
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
string computerName,
CimInstance cimInstance,
GetCimAssociatedInstanceCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(computerName, cimInstance);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </summary>
/// <param name="session"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
CimSession session,
GetCimAssociatedInstanceCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(session);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,231 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System.Collections;
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Globalization;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// Containing all information originated from
/// the parameters of <see cref="GetCimClassCommand"/>
/// </summary>
internal class CimGetCimClassContext : XOperationContextBase
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="methodName"></param>
/// <param name="propertyName"></param>
/// <param name="qualifierName"></param>
internal CimGetCimClassContext(
string theClassName,
string theMethodName,
string thePropertyName,
string theQualifierName)
{
this.className = theClassName;
this.methodName = theMethodName;
this.propertyName = thePropertyName;
this.qualifierName = theQualifierName;
}
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ClassName".
/// </para>
/// <para>
/// Wildcard expansion should be allowed.
/// </para>
/// </summary>
public String ClassName
{
get { return className; }
set { className = value; }
}
private String className;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "MethodName",
/// Which may contains wildchar.
/// Then Filter the <see cref="CimClass"/> by given methodname
/// </para>
/// </summary>
internal String MethodName
{
get { return methodName; }
}
private String methodName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "PropertyName",
/// Which may contains wildchar.
/// Filter the <see cref="CimClass"/> by given property name.
/// </para>
/// </summary>
internal String PropertyName
{
get { return propertyName; }
}
private String propertyName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "QualifierName",
/// Which may contains wildchar.
/// Filter the <see cref="CimClass"/> by given methodname
/// </para>
/// </summary>
internal String QualifierName
{
get { return qualifierName; }
}
private String qualifierName;
}
/// <summary>
/// <para>
/// Implements operations of get-cimclass cmdlet.
/// </para>
/// </summary>
internal sealed class CimGetCimClass : CimAsyncOperation
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
public CimGetCimClass()
: base()
{
}
/// <summary>
/// <para>
/// Base on parametersetName to retrieve <see cref="CimClass"/>
/// </para>
/// </summary>
/// <param name="cmdlet"><see cref="GetCimClassCommand"/> object</param>
public void GetCimClass(GetCimClassCommand cmdlet)
{
List<CimSessionProxy> proxys = new List<CimSessionProxy>();
string nameSpace = ConstValue.GetNamespace(cmdlet.Namespace);
string className = (cmdlet.ClassName == null) ? @"*" : cmdlet.ClassName;
CimGetCimClassContext context = new CimGetCimClassContext(
cmdlet.ClassName,
cmdlet.MethodName,
cmdlet.PropertyName,
cmdlet.QualifierName);
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.ComputerSetName:
{
IEnumerable<string> computerNames = ConstValue.GetComputerNames(
cmdlet.ComputerName);
foreach (string computerName in computerNames)
{
CimSessionProxy proxy = CreateSessionProxy(computerName, cmdlet);
proxy.ContextObject = context;
proxys.Add(proxy);
}
}
break;
case CimBaseCommand.SessionSetName:
{
foreach (CimSession session in cmdlet.CimSession)
{
CimSessionProxy proxy = CreateSessionProxy(session, cmdlet);
proxy.ContextObject = context;
proxys.Add(proxy);
}
}
break;
default:
return;
}
if (WildcardPattern.ContainsWildcardCharacters(className))
{
// retrieve all classes and then filter based on
// classname, propertyname, methodname, and qualifiername
foreach (CimSessionProxy proxy in proxys)
{
proxy.EnumerateClassesAsync(nameSpace);
}
}
else
{
foreach (CimSessionProxy proxy in proxys)
{
proxy.GetClassAsync(nameSpace, className);
}
}
}
#region private methods
/// <summary>
/// <para>
/// Set <see cref="CimSessionProxy"/> properties
/// </para>
/// </summary>
/// <param name="proxy"></param>
/// <param name="cmdlet"></param>
private void SetSessionProxyProperties(
ref CimSessionProxy proxy,
GetCimClassCommand cmdlet)
{
proxy.OperationTimeout = cmdlet.OperationTimeoutSec;
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
string computerName,
GetCimClassCommand cmdlet)
{
CimSessionProxy proxy = new CimSessionProxyGetCimClass(computerName);
this.SubscribeEventAndAddProxytoCache(proxy);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </summary>
/// <param name="session"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
CimSession session,
GetCimClassCommand cmdlet)
{
CimSessionProxy proxy = new CimSessionProxyGetCimClass(session);
this.SubscribeEventAndAddProxytoCache(proxy);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,517 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation;
using System.Text;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// a class used to add pstypename to partial ciminstance
/// for <see cref="GetCimInstanceCommand"/>, if -KeyOnly
/// or -SelectProperties is been specified, then add a pstypename:
/// "Microsoft.Management.Infrastructure.CimInstance#__PartialCIMInstance"
/// </summary>
internal class FormatPartialCimInstance : IObjectPreProcess
{
/// <summary>
/// Partial ciminstance pstypename
/// </summary>
internal const string PartialPSTypeName = @"Microsoft.Management.Infrastructure.CimInstance#__PartialCIMInstance";
/// <summary>
/// Add pstypename to the resultobject if necessary
/// </summary>
/// <param name="resultObject"></param>
/// <returns></returns>
public object Process(object resultObject)
{
if (resultObject is CimInstance)
{
PSObject obj = PSObject.AsPSObject(resultObject);
obj.TypeNames.Insert(0, PartialPSTypeName);
return obj;
}
return resultObject;
}
}
/// <summary>
/// <para>
/// Implements operations of get-ciminstance cmdlet.
/// </para>
/// </summary>
internal class CimGetInstance : CimAsyncOperation
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
public CimGetInstance() : base()
{
}
/// <summary>
/// <para>
/// Base on parametersetName to retrieve ciminstances
/// </para>
/// </summary>
/// <param name="cmdlet"><see cref="GetCimInstanceCommand"/> object</param>
public void GetCimInstance(GetCimInstanceCommand cmdlet)
{
GetCimInstanceInternal(cmdlet);
}
/// <summary>
/// <para>
/// Refactory to be reused by Get-CimInstance;Remove-CimInstance;Set-CimInstance
/// </para>
/// </summary>
/// <param name="cmdlet"></param>
protected void GetCimInstanceInternal(CimBaseCommand cmdlet)
{
IEnumerable<string> computerNames = ConstValue.GetComputerNames(
GetComputerName(cmdlet));
string nameSpace;
List<CimSessionProxy> proxys = new List<CimSessionProxy>();
bool isGetCimInstanceCommand = (cmdlet is GetCimInstanceCommand);
CimInstance targetCimInstance = null;
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.CimInstanceComputerSet:
foreach (string computerName in computerNames)
{
targetCimInstance = GetCimInstanceParameter(cmdlet);
CimSessionProxy proxy = CreateSessionProxy(computerName, targetCimInstance, cmdlet);
if (isGetCimInstanceCommand)
{
this.SetPreProcess(proxy, cmdlet as GetCimInstanceCommand);
}
proxys.Add(proxy);
}
break;
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.QueryComputerSet:
case CimBaseCommand.ResourceUriComputerSet:
foreach (string computerName in computerNames)
{
CimSessionProxy proxy = CreateSessionProxy(computerName, cmdlet);
if (isGetCimInstanceCommand)
{
this.SetPreProcess(proxy, cmdlet as GetCimInstanceCommand);
}
proxys.Add(proxy);
}
break;
case CimBaseCommand.ClassNameSessionSet:
case CimBaseCommand.CimInstanceSessionSet:
case CimBaseCommand.QuerySessionSet:
case CimBaseCommand.ResourceUriSessionSet:
foreach (CimSession session in GetCimSession(cmdlet))
{
CimSessionProxy proxy = CreateSessionProxy(session, cmdlet);
if (isGetCimInstanceCommand)
{
this.SetPreProcess(proxy, cmdlet as GetCimInstanceCommand);
}
proxys.Add(proxy);
}
break;
default:
break;
}
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.ClassNameSessionSet:
nameSpace = ConstValue.GetNamespace(GetNamespace(cmdlet));
if (IsClassNameQuerySet(cmdlet))
{
string query = CreateQuery(cmdlet);
DebugHelper.WriteLogEx(@"Query = {0}", 1, query);
foreach (CimSessionProxy proxy in proxys)
{
proxy.QueryInstancesAsync(nameSpace,
ConstValue.GetQueryDialectWithDefault(GetQueryDialect(cmdlet)),
query);
}
}
else
{
foreach (CimSessionProxy proxy in proxys)
{
proxy.EnumerateInstancesAsync(nameSpace, GetClassName(cmdlet));
}
}
break;
case CimBaseCommand.CimInstanceComputerSet:
case CimBaseCommand.CimInstanceSessionSet:
{
CimInstance instance = GetCimInstanceParameter(cmdlet);
nameSpace = ConstValue.GetNamespace(instance.CimSystemProperties.Namespace);
foreach (CimSessionProxy proxy in proxys)
{
proxy.GetInstanceAsync(nameSpace, instance);
}
}
break;
case CimBaseCommand.QueryComputerSet:
case CimBaseCommand.QuerySessionSet:
nameSpace = ConstValue.GetNamespace(GetNamespace(cmdlet));
foreach (CimSessionProxy proxy in proxys)
{
proxy.QueryInstancesAsync(nameSpace,
ConstValue.GetQueryDialectWithDefault(GetQueryDialect(cmdlet)),
GetQuery(cmdlet));
}
break;
case CimBaseCommand.ResourceUriSessionSet:
case CimBaseCommand.ResourceUriComputerSet:
foreach (CimSessionProxy proxy in proxys)
{
proxy.EnumerateInstancesAsync(GetNamespace(cmdlet), GetClassName(cmdlet));
}
break;
default:
break;
}
}
#region bridge methods to read properties from cmdlet
protected static String[] GetComputerName(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).ComputerName;
}
else if (cmdlet is RemoveCimInstanceCommand)
{
return (cmdlet as RemoveCimInstanceCommand).ComputerName;
}
else if (cmdlet is SetCimInstanceCommand)
{
return (cmdlet as SetCimInstanceCommand).ComputerName;
}
return null;
}
protected static String GetNamespace(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).Namespace;
}
else if (cmdlet is RemoveCimInstanceCommand)
{
return (cmdlet as RemoveCimInstanceCommand).Namespace;
}
else if (cmdlet is SetCimInstanceCommand)
{
return (cmdlet as SetCimInstanceCommand).Namespace;
}
return null;
}
protected static CimSession[] GetCimSession(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).CimSession;
}
else if (cmdlet is RemoveCimInstanceCommand)
{
return (cmdlet as RemoveCimInstanceCommand).CimSession;
}
else if (cmdlet is SetCimInstanceCommand)
{
return (cmdlet as SetCimInstanceCommand).CimSession;
}
return null;
}
protected static String GetClassName(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).ClassName;
}
return null;
}
protected static String GetQuery(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).Query;
}
else if (cmdlet is RemoveCimInstanceCommand)
{
return (cmdlet as RemoveCimInstanceCommand).Query;
}
else if (cmdlet is SetCimInstanceCommand)
{
return (cmdlet as SetCimInstanceCommand).Query;
}
return null;
}
internal static bool IsClassNameQuerySet(CimBaseCommand cmdlet)
{
DebugHelper.WriteLogEx();
GetCimInstanceCommand cmd = cmdlet as GetCimInstanceCommand;
if (cmd != null)
{
if (cmd.QueryDialect != null || cmd.SelectProperties != null || cmd.Filter != null)
{
return true;
}
}
return false;
}
protected static String CreateQuery(CimBaseCommand cmdlet)
{
DebugHelper.WriteLogEx();
GetCimInstanceCommand cmd = cmdlet as GetCimInstanceCommand;
if (cmd != null)
{
StringBuilder propertyList = new StringBuilder();
if (cmd.SelectProperties == null)
{
propertyList.Append("*");
}
else
{
foreach (string property in cmd.SelectProperties)
{
if (propertyList.Length > 0)
{
propertyList.Append(",");
}
propertyList.Append(property);
}
}
return (cmd.Filter == null) ?
String.Format(CultureInfo.CurrentUICulture, queryWithoutWhere, propertyList, cmd.ClassName) :
String.Format(CultureInfo.CurrentUICulture, queryWithWhere, propertyList, cmd.ClassName, cmd.Filter);
}
return null;
}
protected static String GetQueryDialect(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).QueryDialect;
}
else if (cmdlet is RemoveCimInstanceCommand)
{
return (cmdlet as RemoveCimInstanceCommand).QueryDialect;
}
else if (cmdlet is SetCimInstanceCommand)
{
return (cmdlet as SetCimInstanceCommand).QueryDialect;
}
return null;
}
protected static CimInstance GetCimInstanceParameter(CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
return (cmdlet as GetCimInstanceCommand).CimInstance;
}
else if (cmdlet is RemoveCimInstanceCommand)
{
return (cmdlet as RemoveCimInstanceCommand).CimInstance;
}
else if (cmdlet is SetCimInstanceCommand)
{
return (cmdlet as SetCimInstanceCommand).CimInstance;
}
return null;
}
#endregion
#region help methods
/// <summary>
/// <para>
/// Set <see cref="CimSessionProxy"/> properties
/// </para>
/// </summary>
/// <param name="proxy"></param>
/// <param name="cmdlet"></param>
private void SetSessionProxyProperties(
ref CimSessionProxy proxy,
CimBaseCommand cmdlet)
{
if (cmdlet is GetCimInstanceCommand)
{
GetCimInstanceCommand getCimInstance = cmdlet as GetCimInstanceCommand;
proxy.KeyOnly = getCimInstance.KeyOnly;
proxy.Shallow = getCimInstance.Shallow;
proxy.OperationTimeout = getCimInstance.OperationTimeoutSec;
if(getCimInstance.ResourceUri != null )
{
proxy.ResourceUri = getCimInstance.ResourceUri;
}
}
else if (cmdlet is RemoveCimInstanceCommand)
{
RemoveCimInstanceCommand removeCimInstance = cmdlet as RemoveCimInstanceCommand;
proxy.OperationTimeout = removeCimInstance.OperationTimeoutSec;
if(removeCimInstance.ResourceUri != null )
{
proxy.ResourceUri = removeCimInstance.ResourceUri;
}
CimRemoveCimInstanceContext context = new CimRemoveCimInstanceContext(
ConstValue.GetNamespace(removeCimInstance.Namespace),
proxy);
proxy.ContextObject = context;
}
else if (cmdlet is SetCimInstanceCommand)
{
SetCimInstanceCommand setCimInstance = cmdlet as SetCimInstanceCommand;
proxy.OperationTimeout = setCimInstance.OperationTimeoutSec;
if(setCimInstance.ResourceUri != null )
{
proxy.ResourceUri = setCimInstance.ResourceUri;
}
CimSetCimInstanceContext context = new CimSetCimInstanceContext(
ConstValue.GetNamespace(setCimInstance.Namespace),
setCimInstance.Property,
proxy,
cmdlet.ParameterSetName,
setCimInstance.PassThru);
proxy.ContextObject = context;
}
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties.
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
protected CimSessionProxy CreateSessionProxy(
string computerName,
CimBaseCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(computerName);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties.
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
protected CimSessionProxy CreateSessionProxy(
string computerName,
CimInstance cimInstance,
CimBaseCommand cmdlet,
bool passThru)
{
CimSessionProxy proxy = CreateCimSessionProxy(computerName, cimInstance, passThru);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </summary>
/// <param name="session"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
protected CimSessionProxy CreateSessionProxy(
CimSession session,
CimBaseCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(session);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
protected CimSessionProxy CreateSessionProxy(
string computerName,
CimInstance cimInstance,
CimBaseCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(computerName, cimInstance);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </summary>
/// <param name="session"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
protected CimSessionProxy CreateSessionProxy(
CimSession session,
CimBaseCommand cmdlet,
bool passThru)
{
CimSessionProxy proxy = CreateCimSessionProxy(session, passThru);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// Set <see cref="IObjectPreProcess"/> object to proxy to pre-process
/// the result object if necessary
/// </summary>
/// <param name="proxy"></param>
/// <param name="cmdlet"></param>
private void SetPreProcess(CimSessionProxy proxy, GetCimInstanceCommand cmdlet)
{
if (cmdlet.KeyOnly || (cmdlet.SelectProperties != null))
{
proxy.ObjectPreProcess = new FormatPartialCimInstance();
}
}
#endregion
#region const strings
/// <summary>
/// wql query format with where clause
/// </summary>
private const string queryWithWhere = @"SELECT {0} FROM {1} WHERE {2}";
/// <summary>
/// wql query format without where clause
/// </summary>
private const string queryWithoutWhere = @"SELECT {0} FROM {1}";
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,399 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.ComponentModel;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Abstract Cimindication event args, which containing all elements related to
/// an Cimindication.
/// </para>
/// </summary>
public abstract class CimIndicationEventArgs : EventArgs
{
/// <summary>
/// <para>
/// Returns an Object value for an operation context
/// </para>
/// </summary>
public Object Context
{
get
{
return context;
}
}
internal Object context;
}
/// <summary>
/// Cimindication exception event args, which containing occurred exception
/// </summary>
public class CimIndicationEventExceptionEventArgs : CimIndicationEventArgs
{
/// <summary>
/// <para>
/// Returns an exception
/// </para>
/// </summary>
public Exception Exception
{
get
{
return exception;
}
}
private Exception exception;
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="result"></param>
public CimIndicationEventExceptionEventArgs(Exception theException)
{
context = null;
this.exception = theException;
}
}
/// <summary>
/// Cimindication event args, which containing all elements related to
/// an Cimindication.
/// </summary>
public class CimIndicationEventInstanceEventArgs : CimIndicationEventArgs
{
/// <summary>
/// Get ciminstance of the indication object
/// </summary>
public CimInstance NewEvent
{
get
{
return (result == null) ? null : result.Instance;
}
}
/// <summary>
/// Get MachineId of the indication object
/// </summary>
public string MachineId
{
get
{
return (result == null) ? null : result.MachineId;
}
}
/// <summary>
/// Get BookMark of the indication object
/// </summary>
public string Bookmark
{
get
{
return (result == null) ? null : result.Bookmark;
}
}
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="result"></param>
public CimIndicationEventInstanceEventArgs(CimSubscriptionResult result)
{
context = null;
this.result = result;
}
/// <summary>
/// <para>
/// subscription result
/// </para>
/// </summary>
private CimSubscriptionResult result;
}
/// <summary>
/// <para>
/// A public class used to start/stop the subscription to specific indication source,
/// and listen to the incoming indications, event <see cref="CimIndicationArrived"/>
/// will be raised for each cimindication.
/// </para>
/// </summary>
public class CimIndicationWatcher
{
/// <summary>
/// status of <see cref="CimIndicationWatcher"/> object.
/// </summary>
internal enum Status
{
Default,
Started,
Stopped
}
/// <summary>
/// <para>
/// CimIndication arrived event
/// </para>
/// </summary>
public event EventHandler<CimIndicationEventArgs> CimIndicationArrived;
/// <summary>
/// <para>
/// Constructor with given computerName, namespace, queryExpression and timeout
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="nameSpace"></param>
/// <param name="queryExpression"></param>
/// <param name="opreationTimeout"></param>
public CimIndicationWatcher(
string computerName,
string theNamespace,
string queryDialect,
string queryExpression,
UInt32 operationTimeout)
{
ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, queryExpressionParameterName);
computerName = ConstValue.GetComputerName(computerName);
theNamespace = ConstValue.GetNamespace(theNamespace);
Initialize(computerName, null, theNamespace, queryDialect, queryExpression, operationTimeout);
}
/// <summary>
/// <para>
/// Constructor with given cimsession, namespace, queryExpression and timeout
/// </para>
/// </summary>
/// <param name="cimSession"></param>
/// <param name="nameSpace"></param>
/// <param name="queryExpression"></param>
/// <param name="opreationTimeout"></param>
public CimIndicationWatcher(
CimSession cimSession,
string theNamespace,
string queryDialect,
string queryExpression,
UInt32 operationTimeout)
{
ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, queryExpressionParameterName);
ValidationHelper.ValidateNoNullArgument(cimSession, cimSessionParameterName);
theNamespace = ConstValue.GetNamespace(theNamespace);
Initialize(null, cimSession, theNamespace, queryDialect, queryExpression, operationTimeout);
}
/// <summary>
/// <para>
/// Initialize
/// </para>
/// </summary>
private void Initialize(
string theComputerName,
CimSession theCimSession,
string theNameSpace,
string theQueryDialect,
string theQueryExpression,
UInt32 theOpreationTimeout)
{
enableRaisingEvents = false;
status = Status.Default;
myLock = new object();
cimRegisterCimIndication = new CimRegisterCimIndication();
cimRegisterCimIndication.OnNewSubscriptionResult += NewSubscriptionResultHandler;
this.cimSession = theCimSession;
this.nameSpace = theNameSpace;
this.queryDialect = ConstValue.GetQueryDialectWithDefault(theQueryDialect);
this.queryExpression = theQueryExpression;
this.opreationTimeout = theOpreationTimeout;
this.computerName = theComputerName;
}
/// <summary>
/// <para>
/// Hanlder of new subscription result
/// </para>
/// </summary>
/// <param name="src"></param>
/// <param name="args"></param>
private void NewSubscriptionResultHandler(object src, CimSubscriptionEventArgs args)
{
EventHandler<CimIndicationEventArgs> temp = this.CimIndicationArrived;
if (temp != null)
{
// raise the event
CimSubscriptionResultEventArgs resultArgs = args as CimSubscriptionResultEventArgs;
if (resultArgs != null)
temp(this, new CimIndicationEventInstanceEventArgs(resultArgs.Result));
else
{
CimSubscriptionExceptionEventArgs exceptionArgs = args as CimSubscriptionExceptionEventArgs;
if (exceptionArgs != null)
temp(this, new CimIndicationEventExceptionEventArgs(exceptionArgs.Exception));
}
}
}
/// <summary>
/// <para>
/// Will be called by admin\monad\src\eengine\EventManager.cs:
/// PSEventManager::ProcessNewSubscriber to start to listen to the Cim Indication.
/// </para>
/// <para>
/// If set EnableRaisingEvents to false, which will be ignored
/// </para>
/// </summary>
#if !CORECLR
[BrowsableAttribute(false)]
#endif
public bool EnableRaisingEvents
{
get
{
return enableRaisingEvents;
}
set
{
DebugHelper.WriteLogEx();
if (value && !enableRaisingEvents)
{
enableRaisingEvents = value;
Start();
}
}
}
private bool enableRaisingEvents;
/// <summary>
/// <para>
/// Start the subscription
/// </para>
/// </summary>
public void Start()
{
DebugHelper.WriteLogEx();
lock(myLock)
{
if (status == Status.Default)
{
if (this.cimSession == null)
{
cimRegisterCimIndication.RegisterCimIndication(
this.computerName,
this.nameSpace,
this.queryDialect,
this.queryExpression,
this.opreationTimeout);
}
else
{
cimRegisterCimIndication.RegisterCimIndication(
this.cimSession,
this.nameSpace,
this.queryDialect,
this.queryExpression,
this.opreationTimeout);
}
status = Status.Started;
}
}
}
/// <summary>
/// <para>
/// Unsubscribe the subscription
/// </para>
/// </summary>
public void Stop()
{
DebugHelper.WriteLogEx("Status = {0}", 0, this.status);
lock (this.myLock)
{
if (status == Status.Started)
{
if (this.cimRegisterCimIndication != null)
{
DebugHelper.WriteLog("Dispose CimRegisterCimIndication object", 4);
this.cimRegisterCimIndication.Dispose();
}
status = Status.Stopped;
}
}
}
#region internal method
/// <summary>
/// Set the cmdlet object to throw ThrowTerminatingError
/// in case there is a subscription failure
/// </summary>
/// <param name="cmdlet"></param>
internal void SetCmdlet(Cmdlet cmdlet)
{
if (this.cimRegisterCimIndication != null)
{
this.cimRegisterCimIndication.Cmdlet = cmdlet;
}
}
#endregion
#region private members
/// <summary>
/// <para>
/// CimRegisterCimIndication object
/// </para>
/// </summary>
private CimRegisterCimIndication cimRegisterCimIndication;
/// <summary>
/// the status of <see cref="CimIndicationWatcher"/> object
/// </summary>
private Status status;
/// <summary>
/// lock started field
/// </summary>
private object myLock;
/// <summary>
/// CimSession parameter name
/// </summary>
private const string cimSessionParameterName = "cimSession";
/// <summary>
/// QueryExpression parameter name
/// </summary>
private const string queryExpressionParameterName = "queryExpression";
#region parameters
/// <summary>
/// <para>
/// parameters used to start the subscription
/// </para>
/// </summary>
private string computerName;
private CimSession cimSession;
private string nameSpace;
private string queryDialect;
private string queryExpression;
private UInt32 opreationTimeout;
#endregion
#endregion
}
}//End namespace
@@ -0,0 +1,458 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Implements operations of invoke-cimmethod cmdlet.
/// </para>
/// </summary>
internal sealed class CimInvokeCimMethod : CimAsyncOperation
{
/// <summary>
/// Containing all necessary information originated from
/// the parameters of <see cref="InvokeCimMethodCommand"/>
/// </summary>
internal class CimInvokeCimMethodContext : XOperationContextBase
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="theNamespace"></param>
/// <param name="theCollection"></param>
/// <param name="theProxy"></param>
internal CimInvokeCimMethodContext(string theNamespace,
string theMethodName,
CimMethodParametersCollection theCollection,
CimSessionProxy theProxy)
{
this.proxy = theProxy;
this.methodName = theMethodName;
this.collection = theCollection;
this.nameSpace = theNamespace;
}
/// <summary>
/// <para>namespce</para>
/// </summary>
internal string MethodName
{
get
{
return this.methodName;
}
}
private string methodName;
/// <summary>
/// <para>parameters collection</para>
/// </summary>
internal CimMethodParametersCollection ParametersCollection
{
get
{
return this.collection;
}
}
private CimMethodParametersCollection collection;
}
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
public CimInvokeCimMethod()
: base()
{
}
/// <summary>
/// <para>
/// Base on parametersetName to retrieve ciminstances
/// </para>
/// </summary>
/// <param name="cmdlet"><see cref="GetCimInstanceCommand"/> object</param>
public void InvokeCimMethod(InvokeCimMethodCommand cmdlet)
{
IEnumerable<string> computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName);
string nameSpace;
List<CimSessionProxy> proxys = new List<CimSessionProxy>();
string action = string.Format(CultureInfo.CurrentUICulture, actionTemplate, cmdlet.MethodName);
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.CimInstanceComputerSet:
foreach (string computerName in computerNames)
{
proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet));
}
break;
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.CimClassComputerSet:
case CimBaseCommand.ResourceUriComputerSet:
case CimBaseCommand.QueryComputerSet:
foreach (string computerName in computerNames)
{
proxys.Add(CreateSessionProxy(computerName, cmdlet));
}
break;
case CimBaseCommand.ClassNameSessionSet:
case CimBaseCommand.CimClassSessionSet:
case CimBaseCommand.QuerySessionSet:
case CimBaseCommand.CimInstanceSessionSet:
case CimBaseCommand.ResourceUriSessionSet:
foreach (CimSession session in cmdlet.CimSession)
{
CimSessionProxy proxy = CreateSessionProxy(session, cmdlet);
proxys.Add(proxy);
}
break;
default:
break;
}
CimMethodParametersCollection paramsCollection =
CreateParametersCollection(cmdlet.Arguments, cmdlet.CimClass, cmdlet.CimInstance, cmdlet.MethodName);
// Invoke methods
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.ClassNameSessionSet:
case CimBaseCommand.ResourceUriSessionSet:
case CimBaseCommand.ResourceUriComputerSet:
{
string target = string.Format(CultureInfo.CurrentUICulture, targetClass, cmdlet.ClassName);
if(cmdlet.ResourceUri != null )
{
nameSpace = cmdlet.Namespace;
}
else
{
nameSpace = ConstValue.GetNamespace(cmdlet.Namespace);
}
foreach (CimSessionProxy proxy in proxys)
{
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
proxy.InvokeMethodAsync(
nameSpace,
cmdlet.ClassName,
cmdlet.MethodName,
paramsCollection);
}
}
break;
case CimBaseCommand.CimClassComputerSet:
case CimBaseCommand.CimClassSessionSet:
{
string target = string.Format(CultureInfo.CurrentUICulture, targetClass, cmdlet.CimClass.CimSystemProperties.ClassName);
nameSpace = ConstValue.GetNamespace(cmdlet.CimClass.CimSystemProperties.Namespace);
foreach (CimSessionProxy proxy in proxys)
{
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
proxy.InvokeMethodAsync(
nameSpace,
cmdlet.CimClass.CimSystemProperties.ClassName,
cmdlet.MethodName,
paramsCollection);
}
}
break;
case CimBaseCommand.QueryComputerSet:
case CimBaseCommand.QuerySessionSet:
nameSpace = ConstValue.GetNamespace(cmdlet.Namespace);
foreach (CimSessionProxy proxy in proxys)
{
// create context object
CimInvokeCimMethodContext context = new CimInvokeCimMethodContext(
nameSpace,
cmdlet.MethodName,
paramsCollection,
proxy);
proxy.ContextObject = context;
// firstly query instance and then invoke method upon returned instances
proxy.QueryInstancesAsync(nameSpace, ConstValue.GetQueryDialectWithDefault(cmdlet.QueryDialect), cmdlet.Query);
}
break;
case CimBaseCommand.CimInstanceComputerSet:
case CimBaseCommand.CimInstanceSessionSet:
{
string target = cmdlet.CimInstance.ToString();
if(cmdlet.ResourceUri != null )
{
nameSpace = cmdlet.Namespace;
}
else
{
nameSpace = ConstValue.GetNamespace(cmdlet.CimInstance.CimSystemProperties.Namespace);
}
foreach (CimSessionProxy proxy in proxys)
{
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
proxy.InvokeMethodAsync(
nameSpace,
cmdlet.CimInstance,
cmdlet.MethodName,
paramsCollection);
}
}
break;
default:
break;
}
}
/// <summary>
/// <para>
/// Invoke cimmethod on given <see cref="CimInstance"/>
/// </para>
/// </summary>
/// <param name="cimInstance"></param>
public void InvokeCimMethodOnCimInstance(CimInstance cimInstance, XOperationContextBase context, CmdletOperationBase operation)
{
DebugHelper.WriteLogEx();
CimInvokeCimMethodContext cimInvokeCimMethodContext = context as CimInvokeCimMethodContext;
Debug.Assert(cimInvokeCimMethodContext != null, "CimInvokeCimMethod::InvokeCimMethodOnCimInstance should has CimInvokeCimMethodContext != NULL.");
string action = string.Format(CultureInfo.CurrentUICulture, actionTemplate, cimInvokeCimMethodContext.MethodName);
if (!operation.ShouldProcess(cimInstance.ToString(), action))
{
return;
}
CimSessionProxy proxy = CreateCimSessionProxy(cimInvokeCimMethodContext.Proxy);
proxy.InvokeMethodAsync(
cimInvokeCimMethodContext.Namespace,
cimInstance,
cimInvokeCimMethodContext.MethodName,
cimInvokeCimMethodContext.ParametersCollection);
}
#region private methods
/// <summary>
/// <para>
/// Set <see cref="CimSessionProxy"/> properties
/// </para>
/// </summary>
/// <param name="proxy"></param>
/// <param name="cmdlet"></param>
private void SetSessionProxyProperties(
ref CimSessionProxy proxy,
InvokeCimMethodCommand cmdlet)
{
proxy.OperationTimeout = cmdlet.OperationTimeoutSec;
if(cmdlet.ResourceUri != null )
{
proxy.ResourceUri = cmdlet.ResourceUri;
}
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
string computerName,
InvokeCimMethodCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(computerName);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
string computerName,
CimInstance cimInstance,
InvokeCimMethodCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(computerName, cimInstance);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </summary>
/// <param name="session"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
CimSession session,
InvokeCimMethodCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(session);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// <para>
/// Create <see cref="CimMethodParametersCollection"/> with given key properties.
/// And/or <see cref="CimClass"/> object.
/// </para>
/// </summary>
/// <param name="parameters"></param>
/// <param name="cimClass"></param>
/// <param name="cimInstance"></param>
/// <param name="methodName"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">See CimProperty.Create</exception>
/// <exception cref="ArgumentException">CimProperty.Create</exception>
private CimMethodParametersCollection CreateParametersCollection(
IDictionary parameters,
CimClass cimClass,
CimInstance cimInstance,
string methodName)
{
DebugHelper.WriteLogEx();
CimMethodParametersCollection collection = null;
if (parameters == null)
{
return collection;
}
else if (parameters.Count == 0)
{
return collection;
}
collection = new CimMethodParametersCollection();
IDictionaryEnumerator enumerator = parameters.GetEnumerator();
while (enumerator.MoveNext())
{
string parameterName = enumerator.Key.ToString();
CimFlags parameterFlags = CimFlags.In;
object parameterValue = GetBaseObject(enumerator.Value);
DebugHelper.WriteLog(@"Create parameter name= {0}, value= {1}, flags= {2}.", 4,
parameterName,
parameterValue,
parameterFlags);
CimMethodParameter parameter = null;
CimMethodDeclaration declaration = null;
string className = null;
if (cimClass != null)
{
className = cimClass.CimSystemProperties.ClassName;
declaration = cimClass.CimClassMethods[methodName];
if (declaration == null)
{
throw new ArgumentException(String.Format(
CultureInfo.CurrentUICulture, Strings.InvalidMethod, methodName, className));
}
}
else if (cimInstance != null)
{
className = cimInstance.CimClass.CimSystemProperties.ClassName;
declaration = cimInstance.CimClass.CimClassMethods[methodName];
}
if (declaration != null)
{
CimMethodParameterDeclaration paramDeclaration = declaration.Parameters[parameterName];
if (paramDeclaration == null)
{
throw new ArgumentException(String.Format(
CultureInfo.CurrentUICulture, Strings.InvalidMethodParameter, parameterName, methodName, className));
}
parameter = CimMethodParameter.Create(
parameterName,
parameterValue,
paramDeclaration.CimType,
parameterFlags);
// FIXME: check in/out qualifier
// parameterFlags = paramDeclaration.Qualifiers;
}
else
{
if (parameterValue == null)
{
// try the best to get the type while value is null
parameter = CimMethodParameter.Create(
parameterName,
parameterValue,
CimType.String,
parameterFlags);
}
else
{
CimType referenceType = CimType.Unknown;
object referenceObject = GetReferenceOrReferenceArrayObject(parameterValue, ref referenceType);
if (referenceObject != null)
{
parameter = CimMethodParameter.Create(
parameterName,
referenceObject,
referenceType,
parameterFlags);
}
else
{
parameter = CimMethodParameter.Create(
parameterName,
parameterValue,
parameterFlags);
}
}
}
if (parameter != null)
collection.Add(parameter);
}
return collection;
}
#endregion
#region const strings
/// <summary>
/// operation target
/// </summary>
private const string targetClass = @"{0}";
/// <summary>
/// action
/// </summary>
private const string actionTemplate = @"Invoke-CimMethod: {0}";
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,362 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// Containing all information originated from
/// the parameters of <see cref="NewCimInstanceCommand"/>
/// </summary>
internal class CimNewCimInstanceContext : XOperationContextBase
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="methodName"></param>
/// <param name="propertyName"></param>
/// <param name="qualifierName"></param>
internal CimNewCimInstanceContext(
CimSessionProxy theProxy,
string theNamespace)
{
this.proxy = theProxy;
this.nameSpace = theNamespace;
}
}
/// <summary>
/// <para>
/// Implements operations of new-ciminstance cmdlet.
/// </para>
/// </summary>
internal sealed class CimNewCimInstance : CimAsyncOperation
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
public CimNewCimInstance()
: base()
{
}
/// <summary>
/// <para>
/// Base on parametersetName to create ciminstances,
/// either remotely or locally
/// </para>
/// </summary>
/// <param name="cmdlet"><see cref="GetCimInstanceCommand"/> object</param>
public void NewCimInstance(NewCimInstanceCommand cmdlet)
{
DebugHelper.WriteLogEx();
string nameSpace;
CimInstance cimInstance = null;
try
{
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.ClassNameSessionSet:
{
nameSpace = ConstValue.GetNamespace(cmdlet.Namespace);
cimInstance = CreateCimInstance(cmdlet.ClassName,
nameSpace,
cmdlet.Key,
cmdlet.Property,
cmdlet);
}
break;
case CimBaseCommand.ResourceUriSessionSet:
case CimBaseCommand.ResourceUriComputerSet:
{
nameSpace = cmdlet.Namespace; //passing null is ok for resourceUri set
cimInstance = CreateCimInstance("DummyClass",
nameSpace,
cmdlet.Key,
cmdlet.Property,
cmdlet);
}
break;
case CimBaseCommand.CimClassComputerSet:
case CimBaseCommand.CimClassSessionSet:
{
nameSpace = ConstValue.GetNamespace(cmdlet.CimClass.CimSystemProperties.Namespace);
cimInstance = CreateCimInstance(cmdlet.CimClass,
cmdlet.Property,
cmdlet);
}
break;
default:
return;
}
}
catch (ArgumentNullException e)
{
cmdlet.ThrowTerminatingError(e, action);
return;
}
catch (ArgumentException e)
{
cmdlet.ThrowTerminatingError(e, action);
return;
}
// return if create client only ciminstance
if (cmdlet.ClientOnly)
{
cmdlet.CmdletOperation.WriteObject(cimInstance, null);
return;
}
string target = cimInstance.ToString();
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
// create ciminstance on server
List<CimSessionProxy> proxys = new List<CimSessionProxy>();
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.CimClassComputerSet:
case CimBaseCommand.ResourceUriComputerSet:
{
IEnumerable<string> computerNames = ConstValue.GetComputerNames(
cmdlet.ComputerName);
foreach (string computerName in computerNames)
{
proxys.Add(CreateSessionProxy(computerName, cmdlet));
}
}
break;
case CimBaseCommand.CimClassSessionSet:
case CimBaseCommand.ClassNameSessionSet:
case CimBaseCommand.ResourceUriSessionSet:
foreach (CimSession session in cmdlet.CimSession)
{
proxys.Add(CreateSessionProxy(session, cmdlet));
}
break;
}
foreach (CimSessionProxy proxy in proxys)
{
proxy.ContextObject = new CimNewCimInstanceContext(proxy, nameSpace);
proxy.CreateInstanceAsync(nameSpace, cimInstance);
}
}
#region Get CimInstance after creation (on server)
/// <summary>
/// <para>
/// Get full <see cref="CimInstance"/> from server based on the key
/// </para>
/// </summary>
/// <param name="cimInstance"></param>
internal void GetCimInstance(CimInstance cimInstance, XOperationContextBase context)
{
DebugHelper.WriteLogEx();
CimNewCimInstanceContext newCimInstanceContext = context as CimNewCimInstanceContext;
if (newCimInstanceContext == null)
{
DebugHelper.WriteLog("Invalid (null) CimNewCimInstanceContext", 1);
return;
}
CimSessionProxy proxy = CreateCimSessionProxy(newCimInstanceContext.Proxy);
string nameSpace = (cimInstance.CimSystemProperties.Namespace == null) ? newCimInstanceContext.Namespace : cimInstance.CimSystemProperties.Namespace;
proxy.GetInstanceAsync(nameSpace, cimInstance);
}
#endregion
#region private methods
/// <summary>
/// <para>
/// Set <see cref="CimSessionProxy"/> properties
/// </para>
/// </summary>
/// <param name="proxy"></param>
/// <param name="cmdlet"></param>
private void SetSessionProxyProperties(
ref CimSessionProxy proxy,
NewCimInstanceCommand cmdlet)
{
proxy.OperationTimeout = cmdlet.OperationTimeoutSec;
if(cmdlet.ResourceUri != null)
{
proxy.ResourceUri = cmdlet.ResourceUri;
}
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
string computerName,
NewCimInstanceCommand cmdlet)
{
CimSessionProxy proxy = new CimSessionProxyNewCimInstance(computerName, this);
this.SubscribeEventAndAddProxytoCache(proxy);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </summary>
/// <param name="session"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
CimSession session,
NewCimInstanceCommand cmdlet)
{
CimSessionProxy proxy = new CimSessionProxyNewCimInstance(session, this);
this.SubscribeEventAndAddProxytoCache(proxy);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// <para>
/// Create <see cref="CimInstance"/> with given properties.
/// </para>
/// </summary>
/// <param name="className"></param>
/// <param name="key"></param>
/// <param name="properties"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">See CimProperty.Create</exception>
/// <exception cref="ArgumentException">CimProperty.Create</exception>
private CimInstance CreateCimInstance(
string className,
string cimNamespace,
IEnumerable<string> key,
IDictionary properties,
NewCimInstanceCommand cmdlet)
{
CimInstance cimInstance = new CimInstance(className,cimNamespace);
if (properties == null)
{
return cimInstance;
}
List<string> keys = new List<string>();
if (key != null)
{
foreach (string keyName in key)
{
keys.Add(keyName);
}
}
IDictionaryEnumerator enumerator = properties.GetEnumerator();
while (enumerator.MoveNext())
{
CimFlags flag = CimFlags.None;
string propertyName = enumerator.Key.ToString().Trim();
if (keys.Contains(propertyName, StringComparer.OrdinalIgnoreCase))
{
flag = CimFlags.Key;
}
object propertyValue = GetBaseObject(enumerator.Value);
DebugHelper.WriteLog("Create and add new property to ciminstance: name = {0}; value = {1}; flags = {2}", 5, propertyName, propertyValue, flag);
PSReference cimReference = propertyValue as PSReference;
if( cimReference != null )
{
CimProperty newProperty = CimProperty.Create(propertyName, GetBaseObject(cimReference.Value), CimType.Reference, flag);
cimInstance.CimInstanceProperties.Add(newProperty);
}
else
{
CimProperty newProperty = CimProperty.Create(
propertyName,
propertyValue,
flag);
cimInstance.CimInstanceProperties.Add(newProperty);
}
}
return cimInstance;
}
/// <summary>
/// <para>
/// Create <see cref="CimInstance"/> with given properties.
/// </para>
/// </summary>
/// <param name="cimClass"></param>
/// <param name="properties"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">See CimProperty.Create</exception>
/// <exception cref="ArgumentException">CimProperty.Create</exception>
private CimInstance CreateCimInstance(
CimClass cimClass,
IDictionary properties,
NewCimInstanceCommand cmdlet)
{
CimInstance cimInstance = new CimInstance(cimClass);
if (properties == null)
{
return cimInstance;
}
List<string> notfoundProperties = new List<string>();
foreach (string property in properties.Keys)
{
if (cimInstance.CimInstanceProperties[property] == null)
{
notfoundProperties.Add(property);
cmdlet.ThrowInvalidProperty(notfoundProperties, cmdlet.CimClass.CimSystemProperties.ClassName, @"Property", action, properties);
return null;
}
object propertyValue = GetBaseObject(properties[property]);
cimInstance.CimInstanceProperties[property].Value = propertyValue;
}
return cimInstance;
}
#endregion
#region const strings
/// <summary>
/// action
/// </summary>
private const string action = @"New-CimInstance";
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,139 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using Microsoft.Management.Infrastructure.Options;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Prompt user the message coming from provider.
/// </para>
/// <para>
/// At the same time <see cref="CimPromptUser"/> class will prepare the
/// message for -whatif parameter, while the message represents
/// what will happen if execute the operation, but not do the operation.
/// For example, Remove-CimInstance, the whatif message will like,
/// "CIM Instance: Win32_Process@{Key=1} will be deleted."
/// </para>
/// </summary>
internal sealed class CimPromptUser : CimSyncAction
{
/// <summary>
/// Constructor
/// </summary>
public CimPromptUser(string message,
CimPromptType prompt)
{
this.message = message;
this.prompt = prompt;
}
/// <summary>
/// <para>
/// Prompt user with the given message and prepared whatif message.
/// </para>
/// </summary>
/// <param name="cmdlet">
/// cmdlet wrapper object, to which write result.
/// <see cref="CmdletOperationBase"/> for details.
/// </param>
public override void Execute(CmdletOperationBase cmdlet)
{
ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet");
bool yestoall = false;
bool notoall = false;
bool result = false;
switch (this.prompt)
{
case CimPromptType.Critical:
// NOTES: prepare the whatif message and caption
try
{
result = cmdlet.ShouldContinue(message, "caption", ref yestoall, ref notoall);
if (yestoall)
{
this.responseType = CimResponseType.YesToAll;
}
else if (notoall)
{
this.responseType = CimResponseType.NoToAll;
}
else if (result)
{
this.responseType = CimResponseType.Yes;
}
else if (!result)
{
this.responseType = CimResponseType.No;
}
}
catch
{
this.responseType = CimResponseType.NoToAll;
throw;
}
finally
{
// unblocking the waiting thread
this.OnComplete();
}
break;
case CimPromptType.Normal:
try
{
result = cmdlet.ShouldProcess(message);
if (result)
{
this.responseType = CimResponseType.Yes;
}
else if (!result)
{
this.responseType = CimResponseType.No;
}
}
catch
{
this.responseType = CimResponseType.NoToAll;
throw;
}
finally
{
// unblocking the waiting thread
this.OnComplete();
}
break;
default:
break;
}
this.OnComplete();
}
#region members
/// <summary>
/// prompt message
/// </summary>
public string Message
{
get
{
return message;
}
}
private string message;
/// <summary>
/// prompt type -Normal or Critical
/// </summary>
private CimPromptType prompt;
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,374 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Globalization;
using System.Management.Automation;
using System.Threading;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Subscription result event args
/// </para>
/// </summary>
internal abstract class CimSubscriptionEventArgs : EventArgs
{
/// <summary>
/// <para>
/// Returns an Object value for an operation context
/// </para>
/// </summary>
public Object Context
{
get
{
return context;
}
}
protected Object context;
}
/// <summary>
/// <para>
/// Subscription result event args
/// </para>
/// </summary>
internal class CimSubscriptionResultEventArgs : CimSubscriptionEventArgs
{
/// <summary>
/// <para>
/// subscription result
/// </para>
/// </summary>
public CimSubscriptionResult Result
{
get
{
return result;
}
}
private CimSubscriptionResult result;
/// <summary>
/// <para>Constructor</para>
/// </summary>
/// <param name="theResult"></param>
public CimSubscriptionResultEventArgs(
CimSubscriptionResult theResult)
{
this.context = null;
this.result = theResult;
}
}
/// <summary>
/// <para>
/// Subscription result event args
/// </para>
/// </summary>
internal class CimSubscriptionExceptionEventArgs : CimSubscriptionEventArgs
{
/// <summary>
/// <para>
/// subscription result
/// </para>
/// </summary>
public Exception Exception
{
get
{
return exception;
}
}
private Exception exception;
/// <summary>
/// <para>Constructor</para>
/// </summary>
/// <param name="theResult"></param>
public CimSubscriptionExceptionEventArgs(
Exception theException)
{
this.context = null;
this.exception = theException;
}
}
/// <summary>
/// <para>
/// Implements operations of register-cimindication cmdlet.
/// </para>
/// </summary>
internal sealed class CimRegisterCimIndication : CimAsyncOperation
{
/// <summary>
/// <para>
/// New subscritpion result event
/// </para>
/// </summary>
public event EventHandler<CimSubscriptionEventArgs> OnNewSubscriptionResult;
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
public CimRegisterCimIndication()
: base()
{
this.ackedEvent = new ManualResetEventSlim(false);
}
/// <summary>
/// Start an indication subsctiption target to the given computer.
/// </summary>
/// <param name="computerName">null stands for localhost</param>
/// <param name="nameSpace"></param>
/// <param name="queryDialect"></param>
/// <param name="queryExpression"></param>
/// <param name="opreationTimeout"></param>
public void RegisterCimIndication(
string computerName,
string nameSpace,
string queryDialect,
string queryExpression,
UInt32 opreationTimeout)
{
DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression);
this.TargetComputerName = computerName;
CimSessionProxy proxy = CreateSessionProxy(computerName, opreationTimeout);
proxy.SubscribeAsync(nameSpace, queryDialect, queryExpression);
WaitForAckMessage();
}
/// <summary>
/// Start an indication subsctiption through a given <see cref="CimSession"/>.
/// </summary>
/// <param name="cimSession">Cannot be null</param>
/// <param name="nameSpace"></param>
/// <param name="queryDialect"></param>
/// <param name="queryExpression"></param>
/// <param name="opreationTimeout"></param>
/// <exception cref="ArgumentNullException">throw if cimSession is null</exception>
public void RegisterCimIndication(
CimSession cimSession,
string nameSpace,
string queryDialect,
string queryExpression,
UInt32 opreationTimeout)
{
DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression);
if (cimSession == null)
{
throw new ArgumentNullException(String.Format(CultureInfo.CurrentUICulture, Strings.NullArgument, @"cimSession"));
}
this.TargetComputerName = cimSession.ComputerName;
CimSessionProxy proxy = CreateSessionProxy(cimSession, opreationTimeout);
proxy.SubscribeAsync(nameSpace, queryDialect, queryExpression);
WaitForAckMessage();
}
#region override methods
/// <summary>
/// <para>
/// Subscribe to the events issued by <see cref="CimSessionProxy"/>.
/// </para>
/// </summary>
/// <param name="proxy"></param>
protected override void SubscribeToCimSessionProxyEvent(CimSessionProxy proxy)
{
DebugHelper.WriteLog("SubscribeToCimSessionProxyEvent", 4);
// Raise event instead of write object to ps
proxy.OnNewCmdletAction += this.CimIndicationHandler;
proxy.OnOperationCreated += this.OperationCreatedHandler;
proxy.OnOperationDeleted += this.OperationDeletedHandler;
proxy.EnableMethodResultStreaming = false;
}
/// <summary>
/// <para>
/// Handler used to handle new action event from
/// <seealso cref="CimSessionProxy"/> object.
/// </para>
/// </summary>
/// <param name="cimSession">
/// <seealso cref="CimSession"/> object raised the event
/// </param>
/// <param name="actionArgs">event argument</param>
private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actionArgs)
{
DebugHelper.WriteLogEx("action is {0}. Disposed {1}", 0, actionArgs.Action, this.Disposed);
if (this.Disposed)
{
return;
}
// NOTES: should move after this.Disposed, but need to log the exception
CimWriteError cimWriteError = actionArgs.Action as CimWriteError;
if (cimWriteError != null)
{
this.exception = cimWriteError.Exception;
if (!this.ackedEvent.IsSet)
{
// an exception happened
DebugHelper.WriteLogEx("an exception happened", 0);
this.ackedEvent.Set();
return;
}
EventHandler<CimSubscriptionEventArgs> temp = this.OnNewSubscriptionResult;
if (temp != null)
{
DebugHelper.WriteLog("Raise an exception event", 2);
temp(this, new CimSubscriptionExceptionEventArgs(this.exception));
}
DebugHelper.WriteLog("Got an exception: {0}", 2, exception);
}
CimWriteResultObject cimWriteResultObject = actionArgs.Action as CimWriteResultObject;
if (cimWriteResultObject != null)
{
CimSubscriptionResult result = cimWriteResultObject.Result as CimSubscriptionResult;
if (result != null)
{
EventHandler<CimSubscriptionEventArgs> temp = this.OnNewSubscriptionResult;
if (temp != null)
{
DebugHelper.WriteLog("Raise an result event", 2);
temp(this, new CimSubscriptionResultEventArgs(result));
}
}
else
{
if (!this.ackedEvent.IsSet)
{
// an ACK message returned
DebugHelper.WriteLogEx("an ack message happened", 0);
this.ackedEvent.Set();
return;
}
else
{
DebugHelper.WriteLogEx("an ack message should not happen here", 0);
}
}
}
}
/// <summary>
/// block the ps thread until ACK message or Error happened.
/// </summary>
private void WaitForAckMessage()
{
DebugHelper.WriteLogEx();
this.ackedEvent.Wait();
if (this.exception != null)
{
DebugHelper.WriteLogEx("error happened", 0);
if (this.Cmdlet != null)
{
DebugHelper.WriteLogEx("Throw Terminating error", 1);
// throw terminating error
ErrorRecord errorRecord = ErrorToErrorRecord.ErrorRecordFromAnyException(
new InvocationContext(this.TargetComputerName, null), this.exception, null);
this.Cmdlet.ThrowTerminatingError(errorRecord);
}
else
{
DebugHelper.WriteLogEx("Throw exception", 1);
// throw exception out
throw this.exception;
}
}
DebugHelper.WriteLogEx("ACK happened", 0);
}
#endregion
#region internal property
/// <summary>
/// The cmdlet object who issue this subscription,
/// to throw ThrowTerminatingError
/// in case there is a subscription failure
/// </summary>
/// <param name="cmdlet"></param>
internal Cmdlet Cmdlet
{
set;
get;
}
/// <summary>
/// target computername
/// </summary>
internal String TargetComputerName
{
set;
get;
}
#endregion
#region private methods
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="timeout"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
string computerName,
UInt32 timeout)
{
CimSessionProxy proxy = CreateCimSessionProxy(computerName);
proxy.OperationTimeout = timeout;
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </summary>
/// <param name="session"></param>
/// <param name="timeout"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
CimSession session,
UInt32 timeout)
{
CimSessionProxy proxy = CreateCimSessionProxy(session);
proxy.OperationTimeout = timeout;
return proxy;
}
#endregion
#region private members
/// <summary>
/// Exception occurred while start the subscription
/// </summary>
internal Exception Exception
{
get
{
return exception;
}
}
private Exception exception;
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,147 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System.Collections;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// Containing all necessary information originated from
/// the parameters of <see cref="RemoveCimInstanceCommand"/>
/// </summary>
internal class CimRemoveCimInstanceContext : XOperationContextBase
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="theNamespace"></param>
/// <param name="theProxy"></param>
internal CimRemoveCimInstanceContext(string theNamespace,
CimSessionProxy theProxy)
{
this.proxy = theProxy;
this.nameSpace = theNamespace;
}
}
/// <summary>
/// <para>
/// Implements operations of remove-ciminstance cmdlet.
/// </para>
/// </summary>
internal sealed class CimRemoveCimInstance : CimGetInstance
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
public CimRemoveCimInstance()
: base()
{
}
/// <summary>
/// <para>
/// Base on parametersetName to retrieve ciminstances
/// </para>
/// </summary>
/// <param name="cmdlet"><see cref="GetCimInstanceCommand"/> object</param>
public void RemoveCimInstance(RemoveCimInstanceCommand cmdlet)
{
DebugHelper.WriteLogEx();
IEnumerable<string> computerNames = ConstValue.GetComputerNames(
GetComputerName(cmdlet));
List<CimSessionProxy> proxys = new List<CimSessionProxy>();
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.CimInstanceComputerSet:
foreach (string computerName in computerNames)
{
proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet));
}
break;
case CimBaseCommand.CimInstanceSessionSet:
foreach (CimSession session in GetCimSession(cmdlet))
{
proxys.Add(CreateSessionProxy(session, cmdlet));
}
break;
default:
break;
}
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.CimInstanceComputerSet:
case CimBaseCommand.CimInstanceSessionSet:
string nameSpace = null;
if(cmdlet.ResourceUri != null )
{
nameSpace = GetCimInstanceParameter(cmdlet).CimSystemProperties.Namespace;
}
else
{
nameSpace = ConstValue.GetNamespace(GetCimInstanceParameter(cmdlet).CimSystemProperties.Namespace);
}
string target = cmdlet.CimInstance.ToString();
foreach (CimSessionProxy proxy in proxys)
{
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
proxy.DeleteInstanceAsync(nameSpace, cmdlet.CimInstance);
}
break;
case CimBaseCommand.QueryComputerSet:
case CimBaseCommand.QuerySessionSet:
GetCimInstanceInternal(cmdlet);
break;
default:
break;
}
}
/// <summary>
/// <para>
/// Remove <see cref="CimInstance"/> from namespace specified in cmdlet
/// </para>
/// </summary>
/// <param name="cimInstance"></param>
internal void RemoveCimInstance(CimInstance cimInstance, XOperationContextBase context, CmdletOperationBase cmdlet)
{
DebugHelper.WriteLogEx();
string target = cimInstance.ToString();
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
CimRemoveCimInstanceContext removeContext = context as CimRemoveCimInstanceContext;
Debug.Assert(removeContext != null, "CimRemoveCimInstance::RemoveCimInstance should has CimRemoveCimInstanceContext != NULL.");
CimSessionProxy proxy = CreateCimSessionProxy(removeContext.Proxy);
proxy.DeleteInstanceAsync(removeContext.Namespace, cimInstance);
}
#region const strings
/// <summary>
/// action
/// </summary>
private const string action = @"Remove-CimInstance";
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,524 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Management.Automation;
using System.Globalization;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
#region AsyncResultType
/// <summary>
/// <para>
/// Async result type
/// </para>
/// </summary>
public enum AsyncResultType
{
Result,
Exception,
Completion
}
#endregion
#region CimResultContext
/// <summary>
/// Cim Result Context
/// </summary>
internal class CimResultContext
{
/// <summary>
/// constructor
/// </summary>
/// <param name="ErrorSource"></param>
internal CimResultContext(object ErrorSource)
{
this.errorSource = ErrorSource;
}
/// <summary>
/// ErrorSource property
/// </summary>
internal object ErrorSource
{
get
{
return this.errorSource;
}
}
private object errorSource;
}
#endregion
#region AsyncResultEventArgsBase
/// <summary>
/// <para>
/// Base class of asyn result event argument
/// </para>
/// </summary>
internal abstract class AsyncResultEventArgsBase : EventArgs
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
/// <param name="resultType"></param>
public AsyncResultEventArgsBase(
CimSession session,
IObservable<object> observable,
AsyncResultType resultType)
{
this.session = session;
this.observable = observable;
this.resultType = resultType;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
/// <param name="resultType"></param>
/// <param name="context"></param>
public AsyncResultEventArgsBase(
CimSession session,
IObservable<object> observable,
AsyncResultType resultType,
CimResultContext cimResultContext)
{
this.session = session;
this.observable = observable;
this.resultType = resultType;
this.context = cimResultContext;
}
public readonly CimSession session;
public readonly IObservable<object> observable;
public readonly AsyncResultType resultType;
// property ErrorSource
public readonly CimResultContext context;
}
#endregion
#region AsyncResult*Args
/// <summary>
/// <para>
/// operation successfully completed event argument
/// </para>
/// </summary>
internal class AsyncResultCompleteEventArgs : AsyncResultEventArgsBase
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="session"><see cref="CimSession"/> object</param>
/// <param name="cancellationDisposable"></param>
public AsyncResultCompleteEventArgs(
CimSession session,
IObservable<object> observable) :
base(session, observable, AsyncResultType.Completion)
{
}
}
/// <summary>
/// <para>
/// async result argument with object
/// </para>
/// </summary>
internal class AsyncResultObjectEventArgs : AsyncResultEventArgsBase
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
/// <param name="resultObject"></param>
public AsyncResultObjectEventArgs(
CimSession session,
IObservable<object> observable,
object resultObject) :
base(session, observable, AsyncResultType.Result)
{
this.resultObject = resultObject;
}
public readonly object resultObject;
}
/// <summary>
/// <para>
/// operation completed with exception event argument
/// </para>
/// </summary>
internal class AsyncResultErrorEventArgs : AsyncResultEventArgsBase
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
/// <param name="error"></param>
public AsyncResultErrorEventArgs(
CimSession session,
IObservable<object> observable,
Exception error) :
base(session, observable, AsyncResultType.Exception)
{
this.error = error;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
/// <param name="error"></param>
/// <param name="context"></param>
public AsyncResultErrorEventArgs(
CimSession session,
IObservable<object> observable,
Exception error,
CimResultContext cimResultContext) :
base(session, observable, AsyncResultType.Exception, cimResultContext)
{
this.error = error;
}
public readonly Exception error;
}
#endregion
#region CimResultObserver
/// <summary>
/// <para>
/// Observer to consume results from asynchronous operations, such as,
/// EnumerateInstancesAsync operation of <see cref="CimSession"/> object.
/// </para>
/// <para>
/// (See http://channel9.msdn.com/posts/J.Van.Gogh/Reactive-Extensions-API-in-depth-Contract/)
/// for the IObserver/IObservable contact
/// - the only possible sequence is OnNext* (OnCompleted|OnError)?
/// - callbacks are serialized
/// - Subscribe never throws
/// </para>
/// </summary>
/// <typeparam name="T">object type</typeparam>
internal class CimResultObserver<T> : IObserver<T>
{
/// <summary>
/// Define delegate that handles new cmdlet action come from
/// the operations related to the current CimSession object.
/// </summary>
/// <param name="cimSession">cimSession object, which raised the event</param>
/// <param name="actionArgs">Event args</param>
public delegate void ResultEventHandler(
object observer,
AsyncResultEventArgsBase resultArgs);
/// <summary>
/// Define an Event based on the NewActionHandler
/// </summary>
public event ResultEventHandler OnNewResult;
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"><see cref="CimSession"/> object that issued the operation</param>
/// <param name="observable">Operation that can be observed</param>
public CimResultObserver(CimSession session, IObservable<object> observable)
{
this.session = session;
this.observable = observable;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"><see cref="CimSession"/> object that issued the operation</param>
/// <param name="observable">Operation that can be observed</param>
public CimResultObserver(CimSession session,
IObservable<object> observable,
CimResultContext cimResultContext)
{
this.session = session;
this.observable = observable;
this.context = cimResultContext;
}
/// <summary>
/// <para>
/// Operation completed successfully
/// </para>
/// </summary>
public virtual void OnCompleted()
{
// callbacks should never throw any exception to
// protocol layer, otherwise the client process will be
// terminated because of unhandled exception, same with
// OnNext, OnError
try
{
AsyncResultCompleteEventArgs completeArgs = new AsyncResultCompleteEventArgs(
this.session, this.observable);
this.OnNewResult(this, completeArgs);
}
catch (Exception ex)
{
this.OnError(ex);
DebugHelper.WriteLogEx("{0}", 0, ex);
}
}
/// <summary>
/// <para>
/// Operation completed with an error
/// </para>
/// </summary>
/// <param name="error">error object</param>
public virtual void OnError(Exception error)
{
try
{
AsyncResultErrorEventArgs errorArgs = new AsyncResultErrorEventArgs(
this.session, this.observable, error, this.context);
this.OnNewResult(this, errorArgs);
}
catch (Exception ex)
{
// !!ignore the exception
DebugHelper.WriteLogEx("{0}", 0, ex);
}
}
/// <summary>
/// Deliver the result value
/// </summary>
/// <param name="value"></param>
protected void OnNextCore(object value)
{
DebugHelper.WriteLogEx("value = {0}.", 1, value);
try
{
AsyncResultObjectEventArgs resultArgs = new AsyncResultObjectEventArgs(
this.session, this.observable, value);
this.OnNewResult(this, resultArgs);
}
catch (Exception ex)
{
this.OnError(ex);
DebugHelper.WriteLogEx("{0}", 0, ex);
}
}
/// <summary>
/// <para>
/// Operation got a new result object
/// </para>
/// </summary>
/// <param name="value">result object</param>
public virtual void OnNext(T value)
{
DebugHelper.WriteLogEx("value = {0}.", 1, value);
// do not allow null value
if (value == null)
{
return;
}
this.OnNextCore(value);
}
#region members
/// <summary>
/// Session object of the operation
/// </summary>
protected CimSession CurrentSession
{
get
{
return session;
}
}
private CimSession session;
/// <summary>
/// async operation that can be observed
/// </summary>
private IObservable<object> observable;
/// <summary>
/// <see cref="CimResultContext"/> object used during delivering result.
/// </summary>
private CimResultContext context;
#endregion
}
/// <summary>
/// CimSubscriptionResultObserver class definition
/// </summary>
internal class CimSubscriptionResultObserver : CimResultObserver<CimSubscriptionResult>
{
/// <summary>
/// constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
public CimSubscriptionResultObserver(CimSession session, IObservable<object> observable)
: base(session, observable)
{
}
/// <summary>
/// constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
public CimSubscriptionResultObserver(
CimSession session,
IObservable<object> observable,
CimResultContext context)
: base(session, observable, context)
{
}
/// <summary>
/// Override the OnNext method
/// </summary>
/// <param name="value"></param>
public override void OnNext(CimSubscriptionResult value)
{
DebugHelper.WriteLogEx();
base.OnNextCore(value);
}
}
/// <summary>
/// CimMethodResultObserver class definition
/// </summary>
internal class CimMethodResultObserver : CimResultObserver<CimMethodResultBase>
{
/// <summary>
/// constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
public CimMethodResultObserver(CimSession session, IObservable<object> observable)
: base(session, observable)
{
}
/// <summary>
/// constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
/// <param name="context"></param>
public CimMethodResultObserver(
CimSession session,
IObservable<object> observable,
CimResultContext context)
: base(session, observable, context)
{
}
/// <summary>
/// Override the OnNext method
/// </summary>
/// <param name="value"></param>
public override void OnNext(CimMethodResultBase value)
{
DebugHelper.WriteLogEx();
const string PSTypeCimMethodResult = @"Microsoft.Management.Infrastructure.CimMethodResult";
const string PSTypeCimMethodStreamedResult = @"Microsoft.Management.Infrastructure.CimMethodStreamedResult";
const string PSTypeCimMethodResultTemplate = @"{0}#{1}#{2}";
string resultObjectPSType = null;
PSObject resultObject = null;
CimMethodResult methodResult = value as CimMethodResult;
if (methodResult != null)
{
resultObjectPSType = PSTypeCimMethodResult;
resultObject = new PSObject();
foreach (CimMethodParameter param in methodResult.OutParameters)
{
resultObject.Properties.Add(new PSNoteProperty(param.Name, param.Value));
}
}
else
{
CimMethodStreamedResult methodStreamedResult = value as CimMethodStreamedResult;
if (methodStreamedResult != null)
{
resultObjectPSType = PSTypeCimMethodStreamedResult;
resultObject = new PSObject();
resultObject.Properties.Add(new PSNoteProperty(@"ParameterName", methodStreamedResult.ParameterName));
resultObject.Properties.Add(new PSNoteProperty(@"ItemType", methodStreamedResult.ItemType));
resultObject.Properties.Add(new PSNoteProperty(@"ItemValue", methodStreamedResult.ItemValue));
}
}
if (resultObject != null)
{
resultObject.Properties.Add(new PSNoteProperty(@"PSComputerName", this.CurrentSession.ComputerName));
resultObject.TypeNames.Insert(0, resultObjectPSType);
resultObject.TypeNames.Insert(0, String.Format(CultureInfo.InvariantCulture, PSTypeCimMethodResultTemplate, resultObjectPSType, ClassName, MethodName));
base.OnNextCore(resultObject);
}
}
/// <summary>
/// methodname
/// </summary>
internal String MethodName
{
get;
set;
}
/// <summary>
/// classname
/// </summary>
internal String ClassName
{
get;
set;
}
}
/// <summary>
/// IgnoreResultObserver class definition
/// </summary>
internal class IgnoreResultObserver : CimResultObserver<CimInstance>
{
/// <summary>
/// constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
public IgnoreResultObserver(CimSession session, IObservable<object> observable)
: base(session, observable)
{
}
/// <summary>
/// Override the OnNext method
/// </summary>
/// <param name="value"></param>
public override void OnNext(CimInstance value)
{
DebugHelper.WriteLogEx();
}
}
#endregion
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,309 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System.Collections;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// Containing all necessary information originated from
/// the parameters of <see cref="InvokeCimMethodCommand"/>
/// </summary>
internal class CimSetCimInstanceContext : XOperationContextBase
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="theNamespace"></param>
/// <param name="theCollection"></param>
/// <param name="theProxy"></param>
internal CimSetCimInstanceContext(string theNamespace,
IDictionary theProperty,
CimSessionProxy theProxy,
string theParameterSetName,
bool passThru)
{
this.proxy = theProxy;
this.property = theProperty;
this.nameSpace = theNamespace;
this.parameterSetName = theParameterSetName;
this.passThru = passThru;
}
/// <summary>
/// <para>property value</para>
/// </summary>
internal IDictionary Property
{
get
{
return this.property;
}
}
private IDictionary property;
/// <summary>
/// <para>prameter set name</para>
/// </summary>
internal string ParameterSetName
{
get
{
return this.parameterSetName;
}
}
private string parameterSetName;
/// <summary>
/// <para>PassThru value</para>
/// </summary>
internal bool PassThru
{
get
{
return this.passThru;
}
}
private bool passThru;
}
/// <summary>
/// <para>
/// Implements operations of set-ciminstance cmdlet.
/// </para>
/// </summary>
internal sealed class CimSetCimInstance : CimGetInstance
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
public CimSetCimInstance()
: base()
{
}
/// <summary>
/// <para>
/// Base on parametersetName to set ciminstances
/// </para>
/// </summary>
/// <param name="cmdlet"><see cref="SetCimInstanceCommand"/> object</param>
public void SetCimInstance(SetCimInstanceCommand cmdlet)
{
IEnumerable<string> computerNames = ConstValue.GetComputerNames(
GetComputerName(cmdlet));
List<CimSessionProxy> proxys = new List<CimSessionProxy>();
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.CimInstanceComputerSet:
foreach (string computerName in computerNames)
{
// create CimSessionProxySetCimInstance object internally
proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet, cmdlet.PassThru));
}
break;
case CimBaseCommand.CimInstanceSessionSet:
foreach (CimSession session in GetCimSession(cmdlet))
{
// create CimSessionProxySetCimInstance object internally
proxys.Add(CreateSessionProxy(session, cmdlet, cmdlet.PassThru));
}
break;
default:
break;
}
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.CimInstanceComputerSet:
case CimBaseCommand.CimInstanceSessionSet:
string nameSpace = ConstValue.GetNamespace(GetCimInstanceParameter(cmdlet).CimSystemProperties.Namespace);
string target = cmdlet.CimInstance.ToString();
foreach (CimSessionProxy proxy in proxys)
{
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
Exception exception = null;
CimInstance intance = cmdlet.CimInstance;
// For CimInstance parameter sets, Property is an optional parameter
if (cmdlet.Property != null)
{
if (!SetProperty(cmdlet.Property, ref intance, ref exception))
{
cmdlet.ThrowTerminatingError(exception, action);
return;
}
}
proxy.ModifyInstanceAsync(nameSpace, intance);
}
break;
case CimBaseCommand.QueryComputerSet:
case CimBaseCommand.QuerySessionSet:
GetCimInstanceInternal(cmdlet);
break;
default:
break;
}
}
/// <summary>
/// <para>
/// Set <see cref="CimInstance"/> with properties specified in cmdlet
/// </para>
/// </summary>
/// <param name="cimInstance"></param>
public void SetCimInstance(CimInstance cimInstance, CimSetCimInstanceContext context, CmdletOperationBase cmdlet)
{
DebugHelper.WriteLog("CimSetCimInstance::SetCimInstance", 4);
if (!cmdlet.ShouldProcess(cimInstance.ToString(), action))
{
return;
}
Exception exception = null;
if (!SetProperty(context.Property, ref cimInstance, ref exception))
{
cmdlet.ThrowTerminatingError(exception, action);
return;
}
CimSessionProxy proxy = CreateCimSessionProxy(context.Proxy, context.PassThru);
proxy.ModifyInstanceAsync(cimInstance.CimSystemProperties.Namespace, cimInstance);
}
#region private members
/// <summary>
/// <para>
/// Set the properties value to be modified to the given
/// <see cref="CimInstanace"/>
/// </para>
/// </summary>
/// <param name="properties"></param>
/// <param name="cimInstance"></param>
/// <param name="terminationMessage"></param>
/// <returns></returns>
private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, ref Exception exception)
{
DebugHelper.WriteLogEx();
if (properties.Count == 0)
{
// simply ignore if empty properties was provided
return true;
}
IDictionaryEnumerator enumerator = properties.GetEnumerator();
while (enumerator.MoveNext())
{
object value = GetBaseObject(enumerator.Value);
string key = enumerator.Key.ToString();
DebugHelper.WriteLog("Input property name '{0}' with value '{1}'", 1, key, value);
try
{
CimProperty property = cimInstance.CimInstanceProperties[key];
// modify existing property value if found
if (property != null)
{
if ((property.Flags & CimFlags.ReadOnly) == CimFlags.ReadOnly)
{
// can not modify ReadOnly property
exception = new CimException(String.Format(CultureInfo.CurrentUICulture,
Strings.CouldNotModifyReadonlyProperty, key, cimInstance));
return false;
}
// allow modify the key property value as long as it is not readonly,
// then the modified ciminstance is stand for a different CimInstance
DebugHelper.WriteLog("Set property name '{0}' has old value '{1}'", 4, key, property.Value);
property.Value = value;
}
else // For dynamic instance, it is valid to add a new property
{
CimProperty newProperty;
if( value == null )
{
newProperty = CimProperty.Create(
key,
value,
CimType.String,
CimFlags.Property);
}
else
{
CimType referenceType = CimType.Unknown;
object referenceObject = GetReferenceOrReferenceArrayObject(value, ref referenceType);
if (referenceObject != null)
{
newProperty = CimProperty.Create(
key,
referenceObject,
referenceType,
CimFlags.Property);
}
else
{
newProperty = CimProperty.Create(
key,
value,
CimFlags.Property);
}
}
try
{
cimInstance.CimInstanceProperties.Add(newProperty);
}
catch (CimException e)
{
if (e.NativeErrorCode == NativeErrorCode.Failed)
{
string errorMessage = String.Format(CultureInfo.CurrentUICulture,
Strings.UnableToAddPropertyToInstance,
newProperty.Name,
cimInstance);
exception = new CimException(errorMessage, e);
}
else
{
exception = e;
}
return false;
}
DebugHelper.WriteLog("Add non-key property name '{0}' with value '{1}'.", 3, key, value);
}
}
catch (Exception e)
{
DebugHelper.WriteLog("Exception {0}", 4, e);
exception = e;
return false;
}
}
return true;
}
#endregion
#region const strings
/// <summary>
/// action
/// </summary>
private const string action = @"Set-CimInstance";
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,435 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Diagnostics;
using System.Globalization;
using System.Management.Automation;
using Microsoft.Management.Infrastructure.Options;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
#region class ErrorToErrorRecord
/// <summary>
/// <para>
/// Convert error or exception to <see cref="System.Management.Automation.ErrorRecord"/>
/// </para>
/// </summary>
internal sealed class ErrorToErrorRecord
{
/// <summary>
/// <para>
/// Convert ErrorRecord from exception object, <see cref="Exception"/>
/// can be either <see cref="CimException"/> or general <see cref="Exception"/>.
/// </para>
/// </summary>
/// <param name="inner"></param>
/// <param name="context">the context starting the operation, which generated the error</param>
/// <param name="cimResultContext">the CimResultContext used to provide ErrorSource, etc. info.</param>
/// <returns></returns>
internal static ErrorRecord ErrorRecordFromAnyException(
InvocationContext context,
Exception inner,
CimResultContext cimResultContext)
{
Debug.Assert(inner != null, "Caller should verify inner != null");
CimException cimException = inner as CimException;
if (cimException != null)
{
return CreateFromCimException(context, cimException, cimResultContext);
}
var containsErrorRecord = inner as IContainsErrorRecord;
if (containsErrorRecord != null)
{
return InitializeErrorRecord(context,
exception : inner,
errorId: "CimCmdlet_" + containsErrorRecord.ErrorRecord.FullyQualifiedErrorId,
errorCategory: containsErrorRecord.ErrorRecord.CategoryInfo.Category,
cimResultContext: cimResultContext);
}
else
{
return InitializeErrorRecord(context,
exception :inner,
errorId: "CimCmdlet_" + inner.GetType().Name,
errorCategory: ErrorCategory.NotSpecified,
cimResultContext: cimResultContext);
}
}
#region Helper functions
/// <summary>
/// Create <see cref="ErrorRecord"/> from <see cref="CimException"/> object.
/// </summary>
/// <param name="context"></param>
/// <param name="cimException"></param>
/// <param name="cimResultContext">the CimResultContext used to provide ErrorSource, etc. info.</param>
/// <returns></returns>
internal static ErrorRecord CreateFromCimException(
InvocationContext context,
CimException cimException,
CimResultContext cimResultContext)
{
Debug.Assert(cimException != null, "Caller should verify cimException != null");
return InitializeErrorRecord(context, cimException, cimResultContext);
}
/// <summary>
/// Create <see cref="ErrorRecord"/> from <see cref="Exception"/> object.
/// </summary>
/// <param name="context"></param>
/// <param name="exception"></param>
/// <param name="errorId"></param>
/// <param name="errorCategory"></param>
/// <param name="cimResultContext">the CimResultContext used to provide ErrorSource, etc. info.</param>
/// <returns></returns>
internal static ErrorRecord InitializeErrorRecord(
InvocationContext context,
Exception exception,
string errorId,
ErrorCategory errorCategory,
CimResultContext cimResultContext)
{
return InitializeErrorRecordCore(
context,
exception: exception,
errorId: errorId,
errorCategory: errorCategory,
cimResultContext: cimResultContext);
}
/// <summary>
/// Create <see cref="ErrorRecord"/> from <see cref="CimException"/> object.
/// </summary>
/// <param name="context"></param>
/// <param name="cimException"></param>
/// <param name="cimResultContext">the CimResultContext used to provide ErrorSource, etc. info.</param>
/// <returns></returns>
internal static ErrorRecord InitializeErrorRecord(
InvocationContext context,
CimException cimException,
CimResultContext cimResultContext)
{
ErrorRecord errorRecord = InitializeErrorRecordCore(
context,
exception: cimException,
errorId: cimException.MessageId ?? "MiClientApiError_" + cimException.NativeErrorCode,
errorCategory: ConvertCimExceptionToErrorCategory(cimException),
cimResultContext: cimResultContext);
if (cimException.ErrorData != null)
{
errorRecord.CategoryInfo.TargetName = cimException.ErrorSource;
}
return errorRecord;
}
/// <summary>
/// Create <see cref="ErrorRecord"/> from <see cref="Exception"/> object.
/// </summary>
/// <param name="context"></param>
/// <param name="exception"></param>
/// <param name="errorId"></param>
/// <param name="errorCategory"></param>
/// <param name="cimResultContext">the CimResultContext used to provide ErrorSource, etc. info.</param>
/// <returns></returns>
internal static ErrorRecord InitializeErrorRecordCore(
InvocationContext context,
Exception exception,
string errorId,
ErrorCategory errorCategory,
CimResultContext cimResultContext)
{
object theTargetObject = null;
if (cimResultContext != null)
{
theTargetObject = cimResultContext.ErrorSource;
}
if (theTargetObject == null)
{
if (context != null)
{
if (context.TargetCimInstance != null)
{
theTargetObject = context.TargetCimInstance;
}
}
}
ErrorRecord coreErrorRecord = new ErrorRecord(
exception: exception,
errorId: errorId,
errorCategory: errorCategory,
targetObject: theTargetObject);
if (context == null)
{
return coreErrorRecord;
}
System.Management.Automation.Remoting.OriginInfo originInfo = new System.Management.Automation.Remoting.OriginInfo(
context.ComputerName,
Guid.Empty);
ErrorRecord errorRecord = new System.Management.Automation.Runspaces.RemotingErrorRecord(
coreErrorRecord,
originInfo);
DebugHelper.WriteLogEx("Created RemotingErrorRecord.", 0);
// errorRecord.SetInvocationInfo(jobContext.CmdletInvocationInfo);
// errorRecord.PreserveInvocationInfoOnce = true;
return errorRecord;
}
/// <summary>
/// Convert <see cref="CimException"/> to <see cref="ErrorCategory"/>.
/// </summary>
/// <param name="cimException"></param>
/// <returns></returns>
internal static ErrorCategory ConvertCimExceptionToErrorCategory(CimException cimException)
{
ErrorCategory result = ErrorCategory.NotSpecified;
if (cimException.ErrorData != null)
{
result = ConvertCimErrorToErrorCategory(cimException.ErrorData);
}
if (result == ErrorCategory.NotSpecified)
{
result = ConvertCimNativeErrorCodeToErrorCategory(cimException.NativeErrorCode);
}
return result;
}
/// <summary>
/// Convert <see cref="NativeErrorCode"/> to <see cref="ErrorCategory"/>.
/// </summary>
/// <param name="nativeErrorCode"></param>
/// <returns></returns>
internal static ErrorCategory ConvertCimNativeErrorCodeToErrorCategory(NativeErrorCode nativeErrorCode)
{
switch (nativeErrorCode)
{
case NativeErrorCode.Failed:
return ErrorCategory.NotSpecified;
case NativeErrorCode.AccessDenied:
return ErrorCategory.PermissionDenied;
case NativeErrorCode.InvalidNamespace:
return ErrorCategory.MetadataError;
case NativeErrorCode.InvalidParameter:
return ErrorCategory.InvalidArgument;
case NativeErrorCode.InvalidClass:
return ErrorCategory.MetadataError;
case NativeErrorCode.NotFound:
return ErrorCategory.ObjectNotFound;
case NativeErrorCode.NotSupported:
return ErrorCategory.NotImplemented;
case NativeErrorCode.ClassHasChildren:
return ErrorCategory.MetadataError;
case NativeErrorCode.ClassHasInstances:
return ErrorCategory.MetadataError;
case NativeErrorCode.InvalidSuperClass:
return ErrorCategory.MetadataError;
case NativeErrorCode.AlreadyExists:
return ErrorCategory.ResourceExists;
case NativeErrorCode.NoSuchProperty:
return ErrorCategory.MetadataError;
case NativeErrorCode.TypeMismatch:
return ErrorCategory.InvalidType;
case NativeErrorCode.QueryLanguageNotSupported:
return ErrorCategory.NotImplemented;
case NativeErrorCode.InvalidQuery:
return ErrorCategory.InvalidArgument;
case NativeErrorCode.MethodNotAvailable:
return ErrorCategory.MetadataError;
case NativeErrorCode.MethodNotFound:
return ErrorCategory.MetadataError;
case NativeErrorCode.NamespaceNotEmpty:
return ErrorCategory.MetadataError;
case NativeErrorCode.InvalidEnumerationContext:
return ErrorCategory.MetadataError;
case NativeErrorCode.InvalidOperationTimeout:
return ErrorCategory.InvalidArgument;
case NativeErrorCode.PullHasBeenAbandoned:
return ErrorCategory.OperationStopped;
case NativeErrorCode.PullCannotBeAbandoned:
return ErrorCategory.CloseError;
case NativeErrorCode.FilteredEnumerationNotSupported:
return ErrorCategory.NotImplemented;
case NativeErrorCode.ContinuationOnErrorNotSupported:
return ErrorCategory.NotImplemented;
case NativeErrorCode.ServerLimitsExceeded:
return ErrorCategory.ResourceBusy;
case NativeErrorCode.ServerIsShuttingDown:
return ErrorCategory.ResourceUnavailable;
default:
return ErrorCategory.NotSpecified;
}
}
/// <summary>
/// Convert <see cref="cimError"/> to <see cref="ErrorCategory"/>.
/// </summary>
/// <param name="cimError"></param>
/// <returns></returns>
internal static ErrorCategory ConvertCimErrorToErrorCategory(CimInstance cimError)
{
if (cimError == null)
{
return ErrorCategory.NotSpecified;
}
CimProperty errorCategoryProperty = cimError.CimInstanceProperties[@"Error_Category"];
if (errorCategoryProperty == null)
{
return ErrorCategory.NotSpecified;
}
ErrorCategory errorCategoryValue;
if (!LanguagePrimitives.TryConvertTo<ErrorCategory>(errorCategoryProperty.Value, CultureInfo.InvariantCulture, out errorCategoryValue))
{
return ErrorCategory.NotSpecified;
}
return errorCategoryValue;
}
#endregion
}
#endregion
/// <summary>
/// <para>
/// Write error to pipeline
/// </para>
/// </summary>
internal sealed class CimWriteError : CimSyncAction
{
/// <summary>
/// Constructor with an <see cref="CimInstance"/> error
/// </summary>
/// <param name="error"></param>
public CimWriteError(CimInstance error, InvocationContext context)
{
this.error = error;
this.invocationContext = context;
}
/// <summary>
/// Construct with an exception object
/// </summary>
/// <param name="exception"></param>
public CimWriteError(Exception exception, InvocationContext context, CimResultContext cimResultContext)
{
this.exception = exception;
this.invocationContext = context;
this.cimResultContext = cimResultContext;
}
/// <summary>
/// <para>
/// Write error to pipeline
/// </para>
/// </summary>
/// <param name="cmdlet"></param>
public override void Execute(CmdletOperationBase cmdlet)
{
Debug.Assert(cmdlet != null, "Caller should verify that cmdlet != null");
try
{
Exception errorException = (error != null) ? new CimException(error) : this.Exception;
// PS engine takes care of handling error action
cmdlet.WriteError(ErrorToErrorRecord.ErrorRecordFromAnyException(this.invocationContext, errorException, this.cimResultContext));
// if user wants to continue, we will get here
this.responseType = CimResponseType.Yes;
}
catch
{
this.responseType = CimResponseType.NoToAll;
throw;
}
finally
{
// unblocking the waiting thread
this.OnComplete();
}
}
#region members
/// <summary>
/// <para>
/// Error instance
/// </para>
/// </summary>
private CimInstance error;
internal CimInstance Error
{
get
{
return error;
}
}
/// <summary>
/// <para>
/// Exception object
/// </para>
/// </summary>
internal Exception Exception
{
get
{
return exception;
}
}
private Exception exception;
/// <summary>
/// <para>
/// <see cref="InvocationContext"/> object that contains
/// the information while issuing the current operation
/// </para>
/// </summary>
private InvocationContext invocationContext;
internal InvocationContext CimInvocationContext
{
get
{
return invocationContext;
}
}
/// <summary>
/// <see cref="CimResultConte"/>
/// </summary>
private CimResultContext cimResultContext;
internal CimResultContext ResultContext
{
get
{
return cimResultContext;
}
}
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,85 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using Microsoft.Management.Infrastructure.Options;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Write message to message channel
/// </para>
/// </summary>
internal sealed class CimWriteMessage : CimBaseAction
{
#region members
/// <summary>
/// channel id
/// </summary>
private UInt32 channel;
/// <summary>
/// message to write to the channel
/// </summary>
private string message;
#endregion
#region Properties
internal UInt32 Channel
{
get { return channel; }
}
internal string Message
{
get { return message; }
}
#endregion
/// <summary>
/// Constructor method.
/// </summary>
public CimWriteMessage(UInt32 channel,
string message)
{
this.channel = channel;
this.message = message;
}
/// <summary>
/// <para>
/// Write message to the target channel
/// </para>
/// </summary>
/// <param name="cmdlet"></param>
public override void Execute(CmdletOperationBase cmdlet)
{
ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet");
switch ((CimWriteMessageChannel)channel)
{
case CimWriteMessageChannel.Verbose:
cmdlet.WriteVerbose(message);
break;
case CimWriteMessageChannel.Warning:
cmdlet.WriteWarning(message);
break;
case CimWriteMessageChannel.Debug:
cmdlet.WriteDebug(message);
break;
default:
break;
}
}
}//End Class
}//End namespace
@@ -0,0 +1,155 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Write progress record of given activity
/// </para>
/// </summary>
internal sealed class CimWriteProgress : CimBaseAction
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="activity">
/// Activity identifier of the given activity
/// </param>
/// <param name="currentOperation">
/// current operation description of the given activity
/// </param>
/// <param name="statusDescription">
/// current status description of the given activity
/// </param>
/// <param name="percentageCompleted">
/// percentage completed of the given activity
/// </param>
/// <param name="secondsRemaining">
/// how many seconds remained for the given activity
/// </param>
public CimWriteProgress(
string theActivity,
int theActivityID,
string theCurrentOperation,
string theStatusDescription,
UInt32 thePercentageCompleted,
UInt32 theSecondsRemaining)
{
this.activity = theActivity;
this.activityID = theActivityID;
this.currentOperation = theCurrentOperation;
if (String.IsNullOrEmpty(theStatusDescription))
{
this.statusDescription = Strings.DefaultStatusDescription;
}
else
{
this.statusDescription = theStatusDescription;
}
this.percentageCompleted = thePercentageCompleted;
this.secondsRemaining = theSecondsRemaining;
}
/// <summary>
/// <para>
/// Write progress record to powershell
/// </para>
/// </summary>
/// <param name="cmdlet"></param>
public override void Execute(CmdletOperationBase cmdlet)
{
DebugHelper.WriteLog(
"...Activity {0}: id={1}, remain seconds ={2}, percentage completed = {3}",
4,
this.activity,
this.activityID,
this.secondsRemaining,
this.percentageCompleted);
ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet");
ProgressRecord record = new ProgressRecord(
this.activityID,
this.activity,
this.statusDescription);
record.Activity = this.activity;
record.ParentActivityId = 0;
record.SecondsRemaining = (int)this.secondsRemaining;
record.PercentComplete = (int)this.percentageCompleted;
cmdlet.WriteProgress(record);
}
#region members
/// <summary>
/// Activity of the given activity
/// </summary>
private string activity;
/// <summary>
/// Activity identifier of the given activity
/// </summary>
private int activityID;
/// <summary>
/// current operation text of the given activity
/// </summary>
private string currentOperation;
/// <summary>
/// status description of the given activity
/// </summary>
private string statusDescription;
/// <summary>
/// percentage completed of the given activity
/// </summary>
private UInt32 percentageCompleted;
/// <summary>
/// how many seconds remained for the given activity
/// </summary>
private UInt32 secondsRemaining;
internal string Activity
{
get { return activity; }
}
internal int ActivityID
{
get { return activityID; }
}
internal string CurrentOperation
{
get { return currentOperation; }
}
internal string StatusDescription
{
get { return statusDescription; }
}
internal UInt32 PercentageCompleted
{
get { return percentageCompleted; }
}
internal UInt32 SecondsRemaining
{
get { return secondsRemaining; }
}
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,55 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Write result object to ps pipeline
/// </para>
/// </summary>
internal sealed class CimWriteResultObject : CimBaseAction
{
/// <summary>
/// Constructor
/// </summary>
public CimWriteResultObject(object result, XOperationContextBase theContext)
{
this.result = result;
this.Context = theContext;
}
/// <summary>
/// <para>
/// Write result object to ps pipeline
/// </para>
/// </summary>
/// <param name="cmdlet"></param>
public override void Execute(CmdletOperationBase cmdlet)
{
ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet");
cmdlet.WriteObject(result, this.Context);
}
#region members
/// <summary>
/// result object
/// </summary>
internal object Result
{
get
{
return result;
}
}
private object result;
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,390 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System.Management.Automation;
using System;
using System.Globalization;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Wrapper of Cmdlet, forward the operation to Cmdlet directly.
/// This is for unit test purpose, unit test can derive from this class,
/// to hook up all of the cmdlet related operation and verify the correctness.
/// </para>
/// </summary>
internal class CmdletOperationBase
{
/// <summary>
/// <para>
/// Wrap the Cmdlet object.
/// </para>
/// </summary>
private readonly Cmdlet cmdlet;
/// <summary>
/// <para>
/// Wrap the Cmdlet methods, for testing purpose.
/// Test binary can define a child class of CmdletOperationBase.
/// While Execute method of <seealso cref="CimBaseAction"/> accept the
/// object of CmdletOperationBase as parameter.
/// </para>
/// </summary>
#region CMDLET methods
public virtual bool ShouldContinue(string query, string caption)
{
return cmdlet.ShouldContinue(query, caption);
}
public virtual bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll)
{
return cmdlet.ShouldContinue(query, caption, ref yesToAll, ref noToAll);
}
public virtual bool ShouldProcess(string target)
{
return cmdlet.ShouldProcess(target);
}
public virtual bool ShouldProcess(string target, string action)
{
return cmdlet.ShouldProcess(target, action);
}
public virtual bool ShouldProcess(string verboseDescription, string verboseWarning, string caption)
{
return cmdlet.ShouldProcess(verboseDescription, verboseWarning, caption);
}
public virtual bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason)
{
return cmdlet.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason);
}
public virtual void ThrowTerminatingError(ErrorRecord errorRecord)
{
cmdlet.ThrowTerminatingError(errorRecord);
}
public virtual void WriteCommandDetail(string text)
{
cmdlet.WriteCommandDetail(text);
}
public virtual void WriteDebug(string text)
{
cmdlet.WriteDebug(text);
}
public virtual void WriteError(ErrorRecord errorRecord)
{
cmdlet.WriteError(errorRecord);
}
public virtual void WriteObject(object sendToPipeline, XOperationContextBase context)
{
cmdlet.WriteObject(sendToPipeline);
}
public virtual void WriteObject(object sendToPipeline, bool enumerateCollection, XOperationContextBase context)
{
cmdlet.WriteObject(sendToPipeline, enumerateCollection);
}
public virtual void WriteProgress(ProgressRecord progressRecord)
{
cmdlet.WriteProgress(progressRecord);
}
public virtual void WriteVerbose(string text)
{
cmdlet.WriteVerbose(text);
}
public virtual void WriteWarning(string text)
{
cmdlet.WriteWarning(text);
}
/// <summary>
/// <para>
/// Throw terminating error
/// </para>
/// </summary>
internal void ThrowTerminatingError(Exception exception, string operation)
{
ErrorRecord errorRecord = new ErrorRecord(exception, operation, ErrorCategory.InvalidOperation, this);
cmdlet.ThrowTerminatingError(errorRecord);
}
#endregion
/// <summary>
/// Constructor method.
/// </summary>
public CmdletOperationBase(Cmdlet cmdlet)
{
ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet");
this.cmdlet = cmdlet;
}
}//End Class
#region Class CmdletOperationRemoveCimInstance
/// <summary>
/// <para>
/// Wrapper of Cmdlet, override WriteObject function call since
/// we need to remove <see cref="CimInstance"/>.
/// </para>
/// </summary>
internal class CmdletOperationRemoveCimInstance : CmdletOperationBase
{
/// <summary>
/// Constructor method
/// </summary>
/// <param name="cmdlet"></param>
public CmdletOperationRemoveCimInstance(Cmdlet cmdlet,
CimRemoveCimInstance cimRemoveCimInstance)
: base(cmdlet)
{
ValidationHelper.ValidateNoNullArgument(cimRemoveCimInstance, cimRemoveCimInstanceParameterName);
this.removeCimInstance = cimRemoveCimInstance;
}
/// <summary>
/// <para>
/// Object here need to be removed if it is CimInstance
/// </para>
/// </summary>
/// <param name="sendToPipeline"></param>
public override void WriteObject(object sendToPipeline, XOperationContextBase context)
{
if (sendToPipeline is CimInstance)
{
DebugHelper.WriteLog(">>>>CmdletOperationRemoveCimInstance::WriteObject", 4);
this.removeCimInstance.RemoveCimInstance(sendToPipeline as CimInstance, context, this);
}
else
{
base.WriteObject(sendToPipeline, context);
}
}
public override void WriteObject(object sendToPipeline, bool enumerateCollection, XOperationContextBase context)
{
if (sendToPipeline is CimInstance)
{
this.WriteObject(sendToPipeline, context);
}
else
{
base.WriteObject(sendToPipeline, enumerateCollection, context);
}
}
#region private methods
private CimRemoveCimInstance removeCimInstance;
private const string cimRemoveCimInstanceParameterName = @"cimRemoveCimInstance";
#endregion
}//End Class
#endregion
#region Class CmdletOperationSetCimInstance
/// <summary>
/// <para>
/// Wrapper of Cmdlet, override WriteObject function call since
/// we need to set <see cref="CimInstance"/>.
/// </para>
/// </summary>
internal class CmdletOperationSetCimInstance : CmdletOperationBase
{
/// <summary>
/// Constructor method
/// </summary>
/// <param name="cmdlet"></param>
public CmdletOperationSetCimInstance(Cmdlet cmdlet,
CimSetCimInstance theCimSetCimInstance)
: base(cmdlet)
{
ValidationHelper.ValidateNoNullArgument(theCimSetCimInstance, theCimSetCimInstanceParameterName);
this.setCimInstance = theCimSetCimInstance;
}
/// <summary>
/// <para>
/// Object here need to be removed if it is CimInstance
/// </para>
/// </summary>
/// <param name="sendToPipeline"></param>
public override void WriteObject(object sendToPipeline, XOperationContextBase context)
{
DebugHelper.WriteLogEx();
if (sendToPipeline is CimInstance)
{
CimSetCimInstanceContext setContext = context as CimSetCimInstanceContext;
if (setContext != null)
{
if ((String.Compare(setContext.ParameterSetName, CimBaseCommand.QueryComputerSet, StringComparison.OrdinalIgnoreCase) == 0) ||
(String.Compare(setContext.ParameterSetName, CimBaseCommand.QuerySessionSet, StringComparison.OrdinalIgnoreCase) == 0))
{
this.setCimInstance.SetCimInstance(sendToPipeline as CimInstance, setContext, this);
return;
}
else
{
DebugHelper.WriteLog("Write the cimInstance to pipeline since this CimInstance is returned by SetCimInstance.", 4);
}
}
else
{
DebugHelper.WriteLog("Assert. CimSetCimInstance::SetCimInstance has NULL CimSetCimInstanceContext", 4);
}
}
base.WriteObject(sendToPipeline, context);
}
public override void WriteObject(object sendToPipeline, bool enumerateCollection, XOperationContextBase context)
{
if (sendToPipeline is CimInstance)
{
this.WriteObject(sendToPipeline, context);
}
else
{
base.WriteObject(sendToPipeline, enumerateCollection, context);
}
}
#region private methods
private CimSetCimInstance setCimInstance;
private const string theCimSetCimInstanceParameterName = @"theCimSetCimInstance";
#endregion
}//End Class
#endregion
#region Class CmdletOperationInvokeCimMethod
/// <summary>
/// <para>
/// Wrapper of Cmdlet, override WriteObject function call since
/// we need to invoke cim method.
/// </para>
/// </summary>
internal class CmdletOperationInvokeCimMethod : CmdletOperationBase
{
/// <summary>
/// Constructor method
/// </summary>
/// <param name="cmdlet"></param>
public CmdletOperationInvokeCimMethod(Cmdlet cmdlet,
CimInvokeCimMethod theCimInvokeCimMethod)
: base(cmdlet)
{
ValidationHelper.ValidateNoNullArgument(theCimInvokeCimMethod, theCimInvokeCimMethodParameterName);
this.cimInvokeCimMethod = theCimInvokeCimMethod;
}
/// <summary>
/// <para>
/// Object here need to be removed if it is CimInstance
/// </para>
/// </summary>
/// <param name="sendToPipeline"></param>
public override void WriteObject(object sendToPipeline, XOperationContextBase context)
{
DebugHelper.WriteLogEx();
if (sendToPipeline is CimInstance)
{
this.cimInvokeCimMethod.InvokeCimMethodOnCimInstance(sendToPipeline as CimInstance, context, this);
}
else
{
base.WriteObject(sendToPipeline, context);
}
}
public override void WriteObject(object sendToPipeline, bool enumerateCollection, XOperationContextBase context)
{
if (sendToPipeline is CimInstance)
{
this.WriteObject(sendToPipeline, context);
}
else
{
base.WriteObject(sendToPipeline, enumerateCollection, context);
}
}
#region private methods
private CimInvokeCimMethod cimInvokeCimMethod;
private const string theCimInvokeCimMethodParameterName = @"theCimInvokeCimMethod";
#endregion
}//End Class
#endregion
#region Class CmdletOperationTestCimSession
/// <summary>
/// <para>
/// Wrapper of Cmdlet, override WriteObject function call since
/// we need to add cim session to global cache.
/// </para>
/// </summary>
internal class CmdletOperationTestCimSession : CmdletOperationBase
{
/// <summary>
/// Constructor method
/// </summary>
/// <param name="cmdlet"></param>
public CmdletOperationTestCimSession(Cmdlet cmdlet,
CimNewSession theCimNewSession)
: base(cmdlet)
{
ValidationHelper.ValidateNoNullArgument(theCimNewSession, theCimNewSessionParameterName);
this.cimNewSession = theCimNewSession;
}
/// <summary>
/// <para>
/// Add session object to cache
/// </para>
/// </summary>
/// <param name="sendToPipeline"></param>
public override void WriteObject(object sendToPipeline, XOperationContextBase context)
{
DebugHelper.WriteLogEx();
if (sendToPipeline is CimSession)
{
DebugHelper.WriteLog("Call CimNewSession::AddSessionToCache", 1);
this.cimNewSession.AddSessionToCache(sendToPipeline as CimSession, context, this);
}
else if (sendToPipeline is PSObject)
{
DebugHelper.WriteLog("Write PSObject to pipeline", 1);
base.WriteObject(sendToPipeline, context);
}
else
{
// NOTES: May need to output for warning message/verbose message
DebugHelper.WriteLog("Ignore other type object {0}", 1, sendToPipeline);
}
}
#region private methods
private CimNewSession cimNewSession;
private const string theCimNewSessionParameterName = @"theCimNewSession";
#endregion
}//End Class
#endregion
}//End namespace
@@ -0,0 +1,116 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
using System;
using System.IO;
using System.Management.Automation;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
#if CORECLR
// Use stubs for SafeHandleZeroOrMinusOneIsInvalid and ReliabilityContractAttribute
using Microsoft.PowerShell.CoreClr.Stubs;
#else
using System.Runtime.ConstrainedExecution;
#endif
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
[Cmdlet(VerbsData.Export, BinaryMiLogBase.Noun, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=301310")]
public sealed class ExportBinaryMiLogCommand : BinaryMiLogBase, IDisposable
{
[Parameter(ValueFromPipeline = true)]
[ValidateNotNull]
public CimInstance InputObject { get; set; }
private static class NativeMethods
{
internal class WriterHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private WriterHandle()
: base(true)
{
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected override bool ReleaseHandle()
{
Native.InstanceHandle errorHandle = null;
Native.MiResult result = SyncBmilWriter_Delete(this.handle, out errorHandle);
return true;
}
}
[DllImport("mpunits.dll", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
internal static extern Native.MiResult SyncBmilWriter_Create(
string filePath,
out WriterHandle writerHandle,
out Native.InstanceHandle errorHandle);
[DllImport("mpunits.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern Native.MiResult SyncBmilWriter_WriteInstance(
WriterHandle writerHandle,
Native.InstanceHandle instanceHandle,
out Native.InstanceHandle errorHandle);
[DllImport("mpunits.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern Native.MiResult SyncBmilWriter_Delete(
IntPtr writerHandle,
out Native.InstanceHandle errorHandle);
}
private sealed class Writer : IDisposable
{
private readonly NativeMethods.WriterHandle _writerHandle = null;
internal Writer(string file)
{
Native.InstanceHandle errorHandle;
Native.MiResult miResult;
miResult = NativeMethods.SyncBmilWriter_Create(file, out _writerHandle, out errorHandle);
CimException.ThrowIfMiResultFailure(miResult, errorHandle);
}
internal void WriteInstance(CimInstance cimInstance)
{
if (cimInstance == null)
{
throw new ArgumentNullException("cimInstance");
}
Native.InstanceHandle errorHandle;
Native.MiResult miResult;
miResult = NativeMethods.SyncBmilWriter_WriteInstance(_writerHandle, cimInstance.InstanceHandle, out errorHandle);
CimException.ThrowIfMiResultFailure(miResult, errorHandle);
}
public void Dispose()
{
_writerHandle.Dispose();
}
}
private Writer _writer;
protected override void BeginProcessing()
{
_writer = new Writer(this.GetVerifiedFilePath(FileAccess.Write));
}
protected override void ProcessRecord()
{
_writer.WriteInstance(InputObject);
}
public void Dispose()
{
if (_writer != null)
{
_writer.Dispose();
_writer = null;
}
}
}
}
@@ -0,0 +1,370 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Collections.Generic;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// The Cmdlet retrieves instances connected to the given instance, which
/// is called the source instance, via a given association. In an
/// association each instance has a named role, and the same instance can
/// participate in an association in different roles. Hence, the Cmdlet
/// takes SourceRole and AssciatorRole parameters in addition to the
/// Association parameter.
/// </para>
/// </summary>
[Cmdlet(VerbsCommon.Get,
GetCimAssociatedInstanceCommand.Noun,
DefaultParameterSetName = CimBaseCommand.ComputerSetName,
HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227958")]
[OutputType(typeof(CimInstance))]
public class GetCimAssociatedInstanceCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// constructor
/// </summary>
public GetCimAssociatedInstanceCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region parameters
/// <summary>
/// The following is the definition of the input parameter "Association".
/// Specifies the class name of the association to be traversed from the
/// SourceRole to AssociatorRole.
/// </summary>
[Parameter(
Position = 1,
ValueFromPipelineByPropertyName = true)]
public String Association
{
get { return association; }
set { association = value; }
}
private String association;
/// <summary>
/// The following is the definition of the input parameter "ResultClassName".
/// Specifies the class name of the result class name, which associated with
/// the given instance.
/// </summary>
[Parameter]
public String ResultClassName
{
get { return resultClassName; }
set { resultClassName = value; }
}
private String resultClassName;
/// <summary>
/// The following is the definition of the input parameter "AssociatorRole".
/// Specifies the name of the association role of the instances to be retrieved.
/// </summary>
//[Parameter(ValueFromPipelineByPropertyName = true)]
//public String AssociatorRole
//{
// get { return associatorRole; }
// set { associatorRole = value; }
//}
//private String associatorRole;
/// <summary>
/// The following is the definition of the input parameter "SourceRole".
/// Specifies the name of the association role of the source instance where the
/// association traversal should begin.
/// </summary>
//[Parameter(ValueFromPipelineByPropertyName = true)]
//public String SourceRole
//{
// get { return sourcerole; }
// set { sourcerole = value; }
//}
//private String sourcerole;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "InputObject".
/// Provides the instance from which the association traversal is to begin.
/// </para>
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true)]
[Alias(CimBaseCommand.AliasCimInstance)]
public CimInstance InputObject
{
get { return cimInstance; }
set
{
cimInstance = value;
base.SetParameter(value, nameCimInstance);
}
}
/// <summary>
/// Property for internal usage purpose
/// </summary>
internal CimInstance CimInstance
{
get { return cimInstance; }
}
private CimInstance cimInstance;
/// <summary>
/// The following is the definition of the input parameter "Namespace".
/// Identifies the Namespace in which the source class, indicated by ClassName,
/// is registered.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public String Namespace
{
get { return nameSpace; }
set { nameSpace = value; }
}
private String nameSpace;
/// <summary>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Specifies the operation timeout after which the client operation should be
/// canceled. The default is the CimSession operation timeout. If this parameter
/// is specified, then this value takes precedence over the CimSession
/// OperationTimeout.
/// </summary>
[Alias(AliasOT)]
[Parameter(ValueFromPipelineByPropertyName = true)]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout; }
set { operationTimeout = value; }
}
private UInt32 operationTimeout;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ResourceUri".
/// Define the Resource Uri for which the instances are retrieved.
/// </para>
/// </summary>
[Parameter]
public Uri ResourceUri
{
get { return resourceUri; }
set
{
this.resourceUri = value;
base.SetParameter(value, nameResourceUri);
}
}
private Uri resourceUri;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ComputerName".
/// Specifies the name of the computer where the source instance is stored and
/// where the association traversal should begin.
/// </para>
/// <para>
/// This is an optional parameter and if it is not provided, the default value
/// will be "localhost".
/// </para>
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
ParameterSetName = ComputerSetName)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] ComputerName
{
get { return computerName; }
set
{
computerName = value;
base.SetParameter(value, nameComputerName);
}
}
private String[] computerName;
/// <summary>
/// The following is the definition of the input parameter "CimSession".
/// Identifies the CimSession which is to be used to retrieve the instances.
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = SessionSetName)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Microsoft.Management.Infrastructure.CimSession[] CimSession
{
get { return cimSession; }
set
{
cimSession = value;
base.SetParameter(value, nameCimSession);
}
}
private Microsoft.Management.Infrastructure.CimSession[] cimSession;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "KeyOnly".
/// Indicates that only key properties of the retrieved instances should be
/// returned to the client.
/// </para>
/// </summary>
[Parameter]
public SwitchParameter KeyOnly
{
get { return keyOnly; }
set { keyOnly = value; }
}
private SwitchParameter keyOnly;
#endregion
#region cmdlet methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
this.CmdletOperation = new CmdletOperationBase(this);
this.AtBeginProcess = false;
}//End BeginProcessing()
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
CimGetAssociatedInstance operation = this.GetOperationAgent();
if (operation == null)
{
operation = this.CreateOperationAgent();
}
operation.GetCimAssociatedInstance(this);
operation.ProcessActions(this.CmdletOperation);
}//End ProcessRecord()
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
CimGetAssociatedInstance operation = this.GetOperationAgent();
if (operation != null)
operation.ProcessRemainActions(this.CmdletOperation);
}//End EndProcessing()
#endregion
#region helper methods
/// <summary>
/// <para>
/// Get <see cref="CimGetAssociatedInstance"/> object, which is
/// used to delegate all Get-CimAssociatedInstance operations.
/// </para>
/// </summary>
CimGetAssociatedInstance GetOperationAgent()
{
return this.AsyncOperation as CimGetAssociatedInstance;
}
/// <summary>
/// <para>
/// Create <see cref="CimGetAssociatedInstance"/> object, which is
/// used to delegate all Get-CimAssociatedInstance operations.
/// </para>
/// </summary>
/// <returns></returns>
CimGetAssociatedInstance CreateOperationAgent()
{
this.AsyncOperation = new CimGetAssociatedInstance();
return GetOperationAgent();
}
#endregion
#region internal const strings
/// <summary>
/// Noun of current cmdlet
/// </summary>
internal const string Noun = @"CimAssociatedInstance";
#endregion
#region private members
#region const string of parameter names
// internal const string nameAssociation = "Association";
internal const string nameCimInstance = "InputObject";
// internal const string nameNamespace = "Namespace";
// internal const string nameOperationTimeoutSec = "OperationTimeoutSec";
internal const string nameComputerName = "ComputerName";
internal const string nameCimSession = "CimSession";
internal const string nameResourceUri = "ResourceUri";
// internal const string nameKeyOnly = "KeyOnly";
#endregion
/// <summary>
/// static parameter definition entries
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, false),
}
},
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, true),
}
},
{
nameCimInstance, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, true),
new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, true),
}
},
{
nameResourceUri, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, false),
new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, false),
}
},
};
/// <summary>
/// static parameter set entries
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.SessionSetName, new ParameterSetEntry(2, false) },
{ CimBaseCommand.ComputerSetName, new ParameterSetEntry(1, true) },
};
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,304 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Enables the user to enumerate the list of CIM Classes under a specific
/// Namespace. If no list of classes is given, the Cmdlet returns all
/// classes in the given namespce.
/// </para>
/// <para>
/// NOTES: The class instance contains the Namespace properties
/// Should the class remember what Session it came from? No.
/// </para>
/// </summary>
[Cmdlet(VerbsCommon.Get, GetCimClassCommand.Noun, DefaultParameterSetName = ComputerSetName, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227959")]
[OutputType(typeof(CimClass))]
public class GetCimClassCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// constructor
/// </summary>
public GetCimClassCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region parameters
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ClassName".
/// </para>
/// <para>
/// Wildcard expansion should be allowed.
/// </para>
/// </summary>
[Parameter(
Position = 0,
ValueFromPipelineByPropertyName = true)]
public String ClassName
{
get { return className; }
set { className = value; }
}
private String className;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Namespace".
/// Specifies the Namespace under which to look for the specified class name.
/// If no class name is specified, the cmdlet should return all classes under
/// the specified Namespace.
/// </para>
/// <para>
/// Default namespace is root\cimv2
/// </para>
/// </summary>
[Parameter(
Position = 1,
ValueFromPipelineByPropertyName = true)]
public String Namespace
{
get { return nameSpace; }
set { nameSpace = value; }
}
private String nameSpace;
/// <summary>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Enables the user to specify the operation timeout in Seconds. This value
/// overwrites the value specified by the CimSession Operation timeout.
/// </summary>
[Alias(AliasOT)]
[Parameter(ValueFromPipelineByPropertyName = true)]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout;}
set { operationTimeout = value; }
}
private UInt32 operationTimeout;
/// <summary>
/// The following is the definition of the input parameter "Session".
/// Uses a CimSession context.
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = SessionSetName)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public CimSession[] CimSession
{
get { return cimSession;}
set
{
cimSession = value;
base.SetParameter(value, nameCimSession);
}
}
private CimSession[] cimSession;
/// <summary>
/// <para>The following is the definition of the input parameter "ComputerName".
/// Provides the name of the computer from which to retrieve the <see cref="CimClass"/>
/// </para>
/// <para>
/// If no ComputerName is specified the default value is "localhost"
/// </para>
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = ComputerSetName)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] ComputerName
{
get { return computerName; }
set
{
computerName = value;
base.SetParameter(value, nameComputerName);
}
}
private String[] computerName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "MethodName",
/// Which may contains wildchar.
/// Then Filter the <see cref="CimClass"/> by given methodname
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public String MethodName
{
get { return methodName; }
set { methodName = value; }
}
private String methodName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "PropertyName",
/// Which may contains wildchar.
/// Filter the <see cref="CimClass"/> by given property name.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public String PropertyName
{
get { return propertyName; }
set { propertyName = value; }
}
private String propertyName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "QualifierName",
/// Which may contains wildchar.
/// Filter the <see cref="CimClass"/> by given methodname
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public String QualifierName
{
get { return qualifierName; }
set { qualifierName = value; }
}
private String qualifierName;
#endregion
#region cmdlet methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
this.CmdletOperation = new CmdletOperationBase(this);
this.AtBeginProcess = false;
}//End BeginProcessing()
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
CimGetCimClass cimGetCimClass = this.GetOperationAgent();
if (cimGetCimClass == null)
{
cimGetCimClass = CreateOperationAgent();
}
cimGetCimClass.GetCimClass(this);
cimGetCimClass.ProcessActions(this.CmdletOperation);
}//End ProcessRecord()
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
CimGetCimClass cimGetCimClass = this.GetOperationAgent();
if (cimGetCimClass != null)
{
cimGetCimClass.ProcessRemainActions(this.CmdletOperation);
}
}//End EndProcessing()
#endregion
#region helper methods
/// <summary>
/// <para>
/// Get <see cref="CimNewCimInstance"/> object, which is
/// used to delegate all New-CimInstance operations.
/// </para>
/// </summary>
CimGetCimClass GetOperationAgent()
{
return (this.AsyncOperation as CimGetCimClass);
}
/// <summary>
/// <para>
/// Create <see cref="CimGetCimClass"/> object, which is
/// used to delegate all Get-CimClass operations.
/// </para>
/// </summary>
/// <returns></returns>
CimGetCimClass CreateOperationAgent()
{
CimGetCimClass cimGetCimClass = new CimGetCimClass();
this.AsyncOperation = cimGetCimClass;
return cimGetCimClass;
}
#endregion
#region internal const strings
/// <summary>
/// Noun of current cmdlet
/// </summary>
internal const string Noun = @"CimClass";
#endregion
#region private members
#region const string of parameter names
internal const string nameCimSession = "CimSession";
internal const string nameComputerName = "ComputerName";
#endregion
/// <summary>
/// static parameter definition entries
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, true),
}
},
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, false),
}
},
};
/// <summary>
/// static parameter set entries
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.SessionSetName, new ParameterSetEntry(1) },
{ CimBaseCommand.ComputerSetName, new ParameterSetEntry(0, true) },
};
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,648 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// Returns zero, one or more CIM (dynamic) instances with the properties
/// specified in the Property parameter, KeysOnly parameter or the Select clause
/// of the Query parameter.
/// </summary>
[Cmdlet(VerbsCommon.Get, "CimInstance", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227961")]
[OutputType(typeof(CimInstance))]
public class GetCimInstanceCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// constructor
/// </summary>
public GetCimInstanceCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region parameters
/// <summary>
/// <para>
/// The following is the definition of the input parameter "CimSession".
/// Identifies the CimSession which is to be used to retrieve the instances.
/// </para>
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public CimSession[] CimSession
{
get { return cimSession; }
set
{
cimSession = value;
base.SetParameter(value, nameCimSession);
}
}
private CimSession[] cimSession;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ClassName".
/// Define the class name for which the instances are retrieved.
/// </para>
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
public String ClassName
{
get { return className; }
set
{
this.className = value;
base.SetParameter(value, nameClassName);
}
}
private String className;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ResourceUri".
/// Define the Resource Uri for which the instances are retrieved.
/// </para>
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
public Uri ResourceUri
{
get { return resourceUri; }
set
{
this.resourceUri = value;
base.SetParameter(value, nameResourceUri);
}
}
private Uri resourceUri;
/// <summary>
/// <para>The following is the definition of the input parameter "ComputerName".
/// Provides the name of the computer from which to retrieve the instances. The
/// ComputerName is used to create a temporary CimSession with default parameter
/// values, which is then used to retrieve the instances.
/// </para>
/// <para>
/// If no ComputerName is specified the default value is "localhost"
/// </para>
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] ComputerName
{
get { return computerName; }
set
{
computerName = value;
base.SetParameter(value, nameComputerName);
}
}
private String[] computerName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "KeyOnly".
/// Indicates that only key properties of the retrieved instances should be
/// returned to the client.
/// </para>
/// </summary>
[Parameter(ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
public SwitchParameter KeyOnly
{
get { return keyOnly; }
set
{
keyOnly = value;
base.SetParameter(value, nameKeyOnly);
}
}
private SwitchParameter keyOnly;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Namespace".
/// Identifies the Namespace in which the class, indicated by ClassName, is
/// registered.
/// </para>
/// <para>
/// Default namespace is 'root\cimv2' if this property is not specified.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
public String Namespace
{
get { return nameSpace; }
set
{
nameSpace = value;
base.SetParameter(value, nameNamespace);
}
}
private String nameSpace;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Specifies the operation timeout after which the client operation should be
/// canceled. The default is the CimSession operation timeout. If this parameter
/// is specified, then this value takes precedence over the CimSession
/// OperationTimeout.
/// </para>
/// </summary>
[Alias(AliasOT)]
[Parameter]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout; }
set { operationTimeout = value; }
}
private UInt32 operationTimeout;
/// <summary>
/// <para>The following is the definition of the input parameter "InputObject".
/// Provides the <see cref="CimInstance"/> that containing the [Key] properties,
/// based on the key properties to retrieve the <see cref="CimInstance"/>.
/// </para>
/// <para>
/// User can call New-CimInstance to create the CimInstance with key only
/// properties, for example:
/// New-CimInstance -ClassName C -Namespace root\cimv2
/// -Property @{CreationClassName="CIM_VirtualComputerSystem";Name="VM3358"}
/// -Keys {"CreationClassName", "Name"} -Local
/// </para>
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Alias(CimBaseCommand.AliasCimInstance)]
public CimInstance InputObject
{
get { return cimInstance; }
set
{
cimInstance = value;
base.SetParameter(value, nameCimInstance);
}
}
/// <summary>
/// Property for internal usage purpose
/// </summary>
internal CimInstance CimInstance
{
get { return cimInstance; }
}
private CimInstance cimInstance;
/// <summary>
/// The following is the definition of the input parameter "Query".
/// Specifies the query string for what instances, and what properties of those
/// instances, should be retrieve.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
public String Query
{
get { return query; }
set
{
query = value;
base.SetParameter(value, nameQuery);
}
}
private String query;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "QueryDialect".
/// Specifies the dialect used by the query Engine that interprets the Query
/// string.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
public String QueryDialect
{
get { return queryDialect; }
set
{
queryDialect = value;
base.SetParameter(value, nameQueryDialect);
}
}
private String queryDialect;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Shallow".
/// If the switch is set to True, only instance of the class identified by
/// Namespace + ClassName will be returned. If the switch is not set, instances
/// of the above class and of all of its descendents will be returned (the
/// enumeration will cascade the class inheritance hierarchy).
/// </para>
/// </summary>
[Parameter(ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(ParameterSetName = CimBaseCommand.QuerySessionSet)]
public SwitchParameter Shallow
{
get { return shallow; }
set
{
shallow = value;
base.SetParameter(value, nameShallow);
}
}
private SwitchParameter shallow;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Filter".
/// Specifies the where clause of the query.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
public String Filter
{
get { return filter; }
set
{
filter = value;
base.SetParameter(value, nameFilter);
}
}
private String filter;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Property".
/// Specifies the selected properties of result instances.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[Alias("SelectProperties")]
public String[] Property
{
get { return property; }
set
{
property = value;
base.SetParameter(value, nameSelectProperties);
}
}
/// <summary>
/// Property for internal usage
/// </summary>
internal String[] SelectProperties
{
get { return property; }
}
private String[] property;
#endregion
#region cmdlet methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
this.CmdletOperation = new CmdletOperationBase(this);
this.AtBeginProcess = false;
}//End BeginProcessing()
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
this.CheckArgument();
CimGetInstance cimGetInstance = this.GetOperationAgent();
if (cimGetInstance == null)
{
cimGetInstance = CreateOperationAgent();
}
cimGetInstance.GetCimInstance(this);
cimGetInstance.ProcessActions(this.CmdletOperation);
}//End ProcessRecord()
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
CimGetInstance cimGetInstance = this.GetOperationAgent();
if (cimGetInstance != null)
{
cimGetInstance.ProcessRemainActions(this.CmdletOperation);
}
}//End EndProcessing()
#endregion
#region helper methods
/// <summary>
/// <para>
/// Get <see cref="CimGetInstance"/> object, which is
/// used to delegate all Get-CimInstance operations, such
/// as enumerate instances, get instance, query instance.
/// </para>
/// </summary>
CimGetInstance GetOperationAgent()
{
return (this.AsyncOperation as CimGetInstance);
}
/// <summary>
/// <para>
/// Create <see cref="CimGetInstance"/> object, which is
/// used to delegate all Get-CimInstance operations, such
/// as enumerate instances, get instance, query instance.
/// </para>
/// </summary>
/// <returns></returns>
CimGetInstance CreateOperationAgent()
{
CimGetInstance cimGetInstance = new CimGetInstance();
this.AsyncOperation = cimGetInstance;
return cimGetInstance;
}
/// <summary>
/// check argument value
/// </summary>
private void CheckArgument()
{
switch (this.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.ClassNameSessionSet:
// validate the classname & property
this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className);
this.property = ValidationHelper.ValidateArgumentIsValidName(nameSelectProperties, this.property);
break;
default:
break;
}
}
#endregion
#region private members
#region const string of parameter names
internal const string nameCimInstance = "InputObject";
internal const string nameCimSession = "CimSession";
internal const string nameClassName = "ClassName";
internal const string nameResourceUri = "ResourceUri";
internal const string nameComputerName = "ComputerName";
internal const string nameFilter = "Filter";
internal const string nameKeyOnly = "KeyOnly";
internal const string nameNamespace = "Namespace";
internal const string nameOperationTimeoutSec = "OperationTimeoutSec";
internal const string nameQuery = "Query";
internal const string nameQueryDialect = "QueryDialect";
internal const string nameSelectProperties = "Property";
internal const string nameShallow = "Shallow";
#endregion
/// <summary>
/// static parameter definition entries
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true),
}
},
{
nameResourceUri, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
}
},
{
nameClassName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true),
}
},
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
}
},
{
nameKeyOnly, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
}
},
{
nameNamespace, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
}
},
{
nameCimInstance, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true),
}
},
{
nameQuery, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true),
}
},
{
nameQueryDialect, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
}
},
{
nameShallow, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
}
},
{
nameFilter, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
}
},
{
nameSelectProperties, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
}
},
};
/// <summary>
/// static parameter set entries
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(1) },
{ CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) },
{ CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.QueryComputerSet, new ParameterSetEntry(1) },
{ CimBaseCommand.ResourceUriSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.ResourceUriComputerSet, new ParameterSetEntry(1) },
{ CimBaseCommand.QuerySessionSet, new ParameterSetEntry(2) }
};
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,207 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// The command returns zero, one or more CimSession objects that represent
/// connections with remote computers established from the current PS Session.
/// </summary>
[Cmdlet(VerbsCommon.Get, "CimSession", DefaultParameterSetName = ComputerNameSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227966")]
[OutputType(typeof(CimSession))]
public sealed class GetCimSessionCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// constructor
/// </summary>
public GetCimSessionCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region parameters
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ComputerName".
/// Specifies one or more connections by providing their ComputerName(s). The
/// Cmdlet then gets CimSession(s) opened with those connections. This parameter
/// is an alternative to using CimSession(s) that also identifies the remote
/// computer(s).
/// </para>
/// <para>
/// This is the only optional parameter of the Cmdlet. If not provided, the
/// Cmdlet returns all CimSession(s) live/active in the runspace.
/// </para>
/// <para>
/// If an instance of CimSession is pipelined to Get-CimSession, the
/// ComputerName property of the instance is bound by name with this parameter.
/// </para>
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ComputerNameSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] ComputerName
{
get { return computername;}
set
{
computername = value;
base.SetParameter(value, nameComputerName);
}
}
private String[] computername;
/// <summary>
/// The following is the definition of the input parameter "Id".
/// Specifies one or more numeric Id(s) for which to get CimSession(s).
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = SessionIdSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public UInt32[] Id
{
get { return id;}
set
{
id = value;
base.SetParameter(value, nameId);
}
}
private UInt32[] id;
/// <summary>
/// The following is the definition of the input parameter "InstanceID".
/// Specifies one or Session Instance IDs
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InstanceIdSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Guid[] InstanceId
{
get { return instanceid;}
set
{
instanceid = value;
base.SetParameter(value, nameInstanceId);
}
}
private Guid[] instanceid;
/// <summary>
/// The following is the definition of the input parameter "Name".
/// Specifies one or more session Name(s) for which to get CimSession(s). The
/// argument may contain wildcard characters.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = NameSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] Name
{
get { return name;}
set
{
name = value;
base.SetParameter(value, nameName);
}
}
private String[] name;
#endregion
#region cmdlet processing methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
cimGetSession = new CimGetSession();
this.AtBeginProcess = false;
}//End BeginProcessing()
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
cimGetSession.GetCimSession(this);
}//End ProcessRecord()
#endregion
#region private members
/// <summary>
/// <see cref="CimGetSession"/> object used to search CimSession from cache
/// </summary>
private CimGetSession cimGetSession;
#region const string of parameter names
internal const string nameComputerName = "ComputerName";
internal const string nameId = "Id";
internal const string nameInstanceId = "InstanceId";
internal const string nameName = "Name";
#endregion
/// <summary>
/// static parameter definition entries
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ComputerNameSet, false),
}
},
{
nameId, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.SessionIdSet, true),
}
},
{
nameInstanceId, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.InstanceIdSet, true),
}
},
{
nameName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.NameSet, true),
}
},
};
/// <summary>
/// static parameter set entries
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.ComputerNameSet, new ParameterSetEntry(0, true) },
{ CimBaseCommand.SessionIdSet, new ParameterSetEntry(1) },
{ CimBaseCommand.InstanceIdSet, new ParameterSetEntry(1) },
{ CimBaseCommand.NameSet, new ParameterSetEntry(1) },
};
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,113 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
using System;
using System.IO;
using System.Management.Automation;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
#if CORECLR
// Use stubs for SafeHandleZeroOrMinusOneIsInvalid and ReliabilityContractAttribute
using Microsoft.PowerShell.CoreClr.Stubs;
#else
using System.Runtime.ConstrainedExecution;
#endif
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
[Cmdlet(VerbsData.Import, BinaryMiLogBase.Noun, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=301309")]
public sealed class ImportBinaryMiLogCommand : BinaryMiLogBase
{
private static class NativeMethods
{
internal class ReaderHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private ReaderHandle()
: base(true)
{
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected override bool ReleaseHandle()
{
Native.InstanceHandle errorHandle = null;
Native.MiResult result = SyncBmilReader_Delete(this.handle, out errorHandle);
return true;
}
}
[DllImport("mpunits.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern Native.MiResult SyncBmilReader_Create(
string filePath,
out ReaderHandle readerHandle,
out Native.InstanceHandle errorHandle);
[DllImport("mpunits.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
internal static extern Native.MiResult SyncBmilReader_ReadInstance(
ReaderHandle readerHandle,
out Native.InstanceHandle instanceHandle,
out Native.InstanceHandle errorHandle);
[DllImport("mpunits.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern Native.MiResult SyncBmilReader_Delete(
IntPtr readerHandle,
out Native.InstanceHandle errorHandle);
}
private sealed class Reader : IDisposable
{
private readonly NativeMethods.ReaderHandle _readerHandle;
internal Reader(string file)
{
Native.InstanceHandle errorHandle;
Native.MiResult miResult;
miResult = NativeMethods.SyncBmilReader_Create(file, out _readerHandle, out errorHandle);
CimException.ThrowIfMiResultFailure(miResult, errorHandle);
}
internal CimInstance ReadInstance()
{
Native.InstanceHandle errorHandle;
Native.InstanceHandle instanceHandle;
Native.MiResult miResult;
miResult = NativeMethods.SyncBmilReader_ReadInstance(_readerHandle, out instanceHandle, out errorHandle);
CimException.ThrowIfMiResultFailure(miResult, errorHandle);
if (instanceHandle.IsInvalid)
{
return null;
}
var cimInstance = new CimInstance(instanceHandle, null);
return cimInstance;
}
public void Dispose()
{
_readerHandle.Dispose();
}
}
protected override void BeginProcessing()
{
base.BeginProcessing();
this.GetVerifiedFilePath(FileAccess.Read);
using (var reader = new Reader(this.GetVerifiedFilePath(FileAccess.Read)))
{
CimInstance cimInstance;
do
{
cimInstance = reader.ReadInstance();
if (cimInstance != null)
{
this.WriteObject(cimInstance);
}
} while (cimInstance != null);
}
}
}
}
@@ -0,0 +1,556 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// This cmdlet enables the user to invoke a static method on a CIM class using
/// the arguments passed as a list of name value pair dictionary.
/// </summary>
[Cmdlet(
"Invoke",
"CimMethod",
SupportsShouldProcess = true,
DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet,
HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227965")]
public class InvokeCimMethodCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// constructor
/// </summary>
public InvokeCimMethodCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region parameters
/// <summary>
/// The following is the definition of the input parameter "ClassName".
/// Specifies the Class Name, on which to invoke static method.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Alias("Class")]
public String ClassName
{
get { return className; }
set
{
className = value;
base.SetParameter(value, nameClassName);
}
}
private String className;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ResourceUri".
/// Define the Resource Uri for which the instances are retrieved.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
public Uri ResourceUri
{
get { return resourceUri; }
set
{
this.resourceUri = value;
base.SetParameter(value, nameResourceUri);
}
}
private Uri resourceUri;
/// <summary>
/// The following is the definition of the input parameter "CimClass".
/// Specifies the <see cref="CimClass"/> object, on which to invoke static method.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimClassComputerSet)]
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimClassSessionSet)]
public CimClass CimClass
{
get { return cimClass; }
set
{
cimClass = value;
base.SetParameter(value, nameCimClass);
}
}
private CimClass cimClass;
/// <summary>
/// The following is the definition of the input parameter "Query".
/// Specifies the <see cref="CimClass"/> object, on which to invoke static method.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
public string Query
{
get { return query; }
set
{
query = value;
base.SetParameter(value, nameQuery);
}
}
private string query;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "QueryDialect".
/// Specifies the dialect used by the query Engine that interprets the Query
/// string.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
public String QueryDialect
{
get { return queryDialect; }
set
{
queryDialect = value;
base.SetParameter(value, nameQueryDialect);
}
}
private String queryDialect;
/// <summary>
/// The following is the definition of the input parameter "InputObject".
/// Takes a CimInstance object retrieved by a Get-CimInstance call.
/// Invoke the method against the given instance
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Alias(CimBaseCommand.AliasCimInstance)]
public CimInstance InputObject
{
get { return cimInstance; }
set
{
cimInstance = value;
base.SetParameter(value, nameCimInstance);
}
}
/// <summary>
/// Property for internal usage purpose
/// </summary>
internal CimInstance CimInstance
{
get { return cimInstance; }
}
private CimInstance cimInstance;
/// <summary>
/// <para>The following is the definition of the input parameter "ComputerName".
/// Provides the name of the computer from which to invoke the method. The
/// ComputerName is used to create a temporary CimSession with default parameter
/// values, which is then used to retrieve the instances.
/// </para>
/// <para>
/// If no ComputerName is specified the default value is "localhost"
/// </para>
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.CimClassComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] ComputerName
{
get { return computerName; }
set
{
DebugHelper.WriteLogEx();
computerName = value;
base.SetParameter(value, nameComputerName);
}
}
private String[] computerName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "CimSession".
/// Identifies the CimSession which is to be used to retrieve the instances.
/// </para>
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimClassSessionSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public CimSession[] CimSession
{
get { return cimSession; }
set
{
cimSession = value;
base.SetParameter(value, nameCimSession);
}
}
private CimSession[] cimSession;
/// <summary>
/// The following is the definition of the input parameter "Arguments".
/// Specifies the parameter arguments for the static method using a name value
/// pair.
/// </summary>
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true)]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IDictionary Arguments
{
get { return arguments; }
set { arguments = value; }
}
private IDictionary arguments;
/// <summary>
/// The following is the definition of the input parameter "MethodName".
/// Name of the Static Method to use.
/// </summary>
[Parameter(Mandatory = true,
Position = 2,
ValueFromPipelineByPropertyName = true)]
[Alias("Name")]
public String MethodName
{
get { return methodName; }
set
{
methodName = value;
base.SetParameter(value, nameMethodName);
}
}
private String methodName;
/// <summary>
/// The following is the definition of the input parameter "Namespace".
/// Specifies the NameSpace in which the class or instance lives under.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
public String Namespace
{
get { return nameSpace; }
set
{
nameSpace = value;
base.SetParameter(value, nameNamespace);
}
}
private String nameSpace;
/// <summary>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Enables the user to specify the operation timeout in Seconds. This value
/// overwrites the value specified by the CimSession Operation timeout.
/// </summary>
[Alias(AliasOT)]
[Parameter]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout; }
set { operationTimeout = value; }
}
private UInt32 operationTimeout;
#endregion
#region cmdlet methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent();
if (cimInvokeMethod == null)
{
cimInvokeMethod = CreateOperationAgent();
}
this.CmdletOperation = new CmdletOperationInvokeCimMethod(this, cimInvokeMethod);
this.AtBeginProcess = false;
}//End BeginProcessing()
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
this.CheckArgument();
CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent();
cimInvokeMethod.InvokeCimMethod(this);
cimInvokeMethod.ProcessActions(this.CmdletOperation);
}//End ProcessRecord()
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent();
if (cimInvokeMethod != null)
{
cimInvokeMethod.ProcessRemainActions(this.CmdletOperation);
}
}//End EndProcessing()
#endregion
#region helper methods
/// <summary>
/// <para>
/// Get <see cref="CimInvokeCimMethod"/> object, which is
/// used to delegate all Inovke-CimMethod operations.
/// </para>
/// </summary>
CimInvokeCimMethod GetOperationAgent()
{
return this.AsyncOperation as CimInvokeCimMethod;
}
/// <summary>
/// <para>
/// Create <see cref="CimInvokeCimMethod"/> object, which is
/// used to delegate all Invoke-CimMethod operations.
/// </para>
/// </summary>
/// <returns></returns>
CimInvokeCimMethod CreateOperationAgent()
{
CimInvokeCimMethod cimInvokeMethod = new CimInvokeCimMethod();
this.AsyncOperation = cimInvokeMethod;
return cimInvokeMethod;
}
/// <summary>
/// check argument value
/// </summary>
private void CheckArgument()
{
switch (this.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.ClassNameSessionSet:
// validate the classname
this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className);
break;
default:
break;
}
}
#endregion
#region private members
#region const string of parameter names
internal const string nameClassName = "ClassName";
internal const string nameCimClass = "CimClass";
internal const string nameQuery = "Query";
internal const string nameResourceUri = "ResourceUri";
internal const string nameQueryDialect = "QueryDialect";
internal const string nameCimInstance = "InputObject";
internal const string nameComputerName = "ComputerName";
internal const string nameCimSession = "CimSession";
internal const string nameArguments = "Arguments";
internal const string nameMethodName = "MethodName";
internal const string nameNamespace = "Namespace";
#endregion
/// <summary>
/// static parameter definition entries
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameClassName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
}
},
{
nameCimClass, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true),
}
},
{
nameQuery, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true),
}
},
{
nameQueryDialect, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
}
},
{
nameCimInstance, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true),
}
},
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
}
},
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true),
}
},
{
nameMethodName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true),
}
},
{
nameNamespace, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
}
},
{
nameResourceUri, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true),
}
},
};
/// <summary>
/// static parameter set entries
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(2, true) },
{ CimBaseCommand.ResourceUriSessionSet, new ParameterSetEntry(3) },
{ CimBaseCommand.ResourceUriComputerSet, new ParameterSetEntry(2) },
{ CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(3) },
{ CimBaseCommand.QueryComputerSet, new ParameterSetEntry(2) },
{ CimBaseCommand.QuerySessionSet, new ParameterSetEntry(3) },
{ CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(2) },
{ CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(3) },
{ CimBaseCommand.CimClassComputerSet, new ParameterSetEntry(2) },
{ CimBaseCommand.CimClassSessionSet, new ParameterSetEntry(3) },
};
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,497 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// This Cmdlet creates an instance of a CIM class based on the class
/// definition, which is an instance factory
/// </para>
/// <para>
/// If -ClientOnly is not specified, New-CimInstance will create a new instance
/// on the server, otherwise just create client in-memory instance
/// </para>
/// </summary>
[Cmdlet(VerbsCommon.New, "CimInstance", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227963")]
[OutputType(typeof(CimInstance))]
public class NewCimInstanceCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// constructor
/// </summary>
public NewCimInstanceCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region parameters
/// <summary>
/// The following is the definition of the input parameter "ClassName".
/// Name of the Class to use to create Instance.
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
public String ClassName
{
get { return className; }
set
{
className = value;
base.SetParameter(value, nameClassName);
}
}
private String className;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ResourceUri".
/// Define the Resource Uri for which the instances are retrieved.
/// </para>
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
public Uri ResourceUri
{
get { return resourceUri; }
set
{
this.resourceUri = value;
base.SetParameter(value, nameResourceUri);
}
}
private Uri resourceUri;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Key".
/// Enables the user to specify list of key property name.
/// </para>
/// <para>
/// Example: -Key {"K1", "K2"}
/// </para>
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] Key
{
get { return key; }
set
{
key = value;
base.SetParameter(value, nameKey);
}
}
private String[] key;
/// <summary>
/// The following is the definition of the input parameter "CimClass".
/// The CimClass is used to create Instance.
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimClassSessionSet)]
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimClassComputerSet)]
public CimClass CimClass
{
get { return cimClass; }
set
{
cimClass = value;
base.SetParameter(value, nameCimClass);
}
}
private CimClass cimClass;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Property".
/// Enables the user to specify instances with specific property values.
/// </para>
/// <para>
/// Example: -Property @{P1="Value1";P2="Value2"}
/// </para>
/// </summary>
[Parameter(
Position = 1,
ValueFromPipelineByPropertyName = true)]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
[Alias("Arguments")]
public IDictionary Property
{
get { return property; }
set { property = value; }
}
private IDictionary property;
/// <summary>
/// The following is the definition of the input parameter "Namespace".
/// Namespace used to look for the classes under to store the instances.
/// Default namespace is 'root\cimv2'
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
public String Namespace
{
get { return nameSpace; }
set
{
nameSpace = value;
base.SetParameter(value, nameNamespace);
}
}
private String nameSpace;
/// <summary>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Operation Timeout of the cmdlet in seconds. Overrides the value in the Cim
/// Session.
/// </summary>
[Alias(AliasOT)]
[Parameter]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout; }
set { operationTimeout = value; }
}
private UInt32 operationTimeout;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "CimSession".
/// Identifies the CimSession which is to be used to create the instances.
/// </para>
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.ResourceUriSessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimClassSessionSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public CimSession[] CimSession
{
get { return cimSession; }
set
{
cimSession = value;
base.SetParameter(value, nameCimSession);
}
}
private CimSession[] cimSession;
/// <summary>
/// <para>The following is the definition of the input parameter "ComputerName".
/// Provides the name of the computer from which to create the instances.
/// </para>
/// <para>
/// If no ComputerName is specified the default value is "localhost"
/// </para>
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.ResourceUriComputerSet)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimClassComputerSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] ComputerName
{
get { return computerName; }
set
{
computerName = value;
base.SetParameter(value, nameComputerName);
}
}
private String[] computerName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ClientOnly".
/// Indicates to create a client only ciminstance object, NOT on the server.
/// </para>
/// </summary>
[Alias("Local")]
[Parameter(
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimClassComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimClassSessionSet)]
public SwitchParameter ClientOnly
{
get { return clientOnly; }
set {
clientOnly = value;
base.SetParameter(value, nameClientOnly);
}
}
private SwitchParameter clientOnly;
#endregion
#region cmdlet methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
this.CmdletOperation = new CmdletOperationBase(this);
this.AtBeginProcess = false;
}//End BeginProcessing()
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
this.CheckArgument();
if (this.ClientOnly)
{
string conflictParameterName = null;
if (null != this.ComputerName)
{
conflictParameterName = @"ComputerName";
}
else if (null != this.CimSession)
{
conflictParameterName = @"CimSession";
}
if (null != conflictParameterName)
{
ThrowConflictParameterWasSet(@"New-CimInstance", conflictParameterName, @"ClientOnly");
return;
}
}
CimNewCimInstance cimNewCimInstance = this.GetOperationAgent();
if (cimNewCimInstance == null)
{
cimNewCimInstance = CreateOperationAgent();
}
cimNewCimInstance.NewCimInstance(this);
cimNewCimInstance.ProcessActions(this.CmdletOperation);
}//End ProcessRecord()
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
CimNewCimInstance cimNewCimInstance = this.GetOperationAgent();
if (cimNewCimInstance != null)
{
cimNewCimInstance.ProcessRemainActions(this.CmdletOperation);
}
}//End EndProcessing()
#endregion
#region helper methods
/// <summary>
/// <para>
/// Get <see cref="CimNewCimInstance"/> object, which is
/// used to delegate all New-CimInstance operations.
/// </para>
/// </summary>
CimNewCimInstance GetOperationAgent()
{
return (this.AsyncOperation as CimNewCimInstance);
}
/// <summary>
/// <para>
/// Create <see cref="CimNewCimInstance"/> object, which is
/// used to delegate all New-CimInstance operations.
/// </para>
/// </summary>
/// <returns></returns>
CimNewCimInstance CreateOperationAgent()
{
CimNewCimInstance cimNewCimInstance = new CimNewCimInstance();
this.AsyncOperation = cimNewCimInstance;
return cimNewCimInstance;
}
/// <summary>
/// check argument value
/// </summary>
private void CheckArgument()
{
switch (this.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.ClassNameSessionSet:
// validate the classname
this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className);
break;
default:
break;
}
}
#endregion
#region private members
#region const string of parameter names
internal const string nameClassName = "ClassName";
internal const string nameResourceUri = "ResourceUri";
internal const string nameKey = "Key";
internal const string nameCimClass = "CimClass";
internal const string nameProperty = "Property";
internal const string nameNamespace = "Namespace";
internal const string nameCimSession = "CimSession";
internal const string nameComputerName = "ComputerName";
internal const string nameClientOnly = "ClientOnly";
#endregion
/// <summary>
/// static parameter definition entries
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameClassName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true),
}
},
{
nameResourceUri, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true),
}
},
{
nameKey, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
}
},
{
nameCimClass, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true),
}
},
{
nameNamespace, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false),
}
},
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true),
}
},
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, false),
}
},
{
nameClientOnly, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true),
}
},
};
/// <summary>
/// static parameter set entries
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) },
{ CimBaseCommand.CimClassSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.CimClassComputerSet, new ParameterSetEntry(1) },
{ CimBaseCommand.ResourceUriSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.ResourceUriComputerSet, new ParameterSetEntry(1) },
};
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,352 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Management.Automation;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Management.Infrastructure.Options;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// This Cmdlet enables the IT Pro to create a CIM Session. CIM Session object
/// is a client-side representation of the connection between the client and the
/// server.
/// The CimSession object returned by the Cmdlet is used by all other CIM
/// cmdlets.
/// </summary>
[Cmdlet(VerbsCommon.New, "CimSession", DefaultParameterSetName = CredentialParameterSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227967")]
[OutputType(typeof(CimSession))]
public sealed class NewCimSessionCommand : CimBaseCommand
{
#region cmdlet parameters
/// <summary>
/// The following is the definition of the input parameter "Authentication".
/// The following is the validation set for allowed authentication types.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CredentialParameterSet)]
public PasswordAuthenticationMechanism Authentication
{
get { return authentication;}
set
{
authentication = value;
authenticationSet = true;
}
}
private PasswordAuthenticationMechanism authentication;
private bool authenticationSet = false;
/// <summary>
/// The following is the definition of the input parameter "Credential".
/// Specifies a user account that has permission to perform this action.
/// The default is the current user.
/// </summary>
[Parameter(Position = 1, ParameterSetName = CredentialParameterSet)]
[Credential()]
public PSCredential Credential
{
get { return credential; }
set { credential = value; }
}
private PSCredential credential;
/// <summary>
/// The following is the definition of the input parameter "CertificateThumbprint".
/// This is specificly for wsman protocol.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CertificatePrameterSet)]
public String CertificateThumbprint
{
get { return certificatethumbprint; }
set { certificatethumbprint = value; }
}
private String certificatethumbprint;
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Specifies the computer on which the commands associated with this session
/// will run. The default value is LocalHost.
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
Position = 0,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] ComputerName
{
get { return computername;}
set { computername = value; }
}
private String[] computername;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Name".
/// Specifies a friendly name for the CIM Session connection.
/// </para>
/// <para>
/// If a name is not passed, then the session is given the name CimSession<int>,
/// where <int> is the next available session number. Example, CimSession1,
/// CimSession2, etc...
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public String Name
{
get { return name;}
set { name = value; }
}
private String name;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Specifies the operation timeout for all operations in session. Individual
/// operations can override this timeout.
/// </para>
/// <para>
/// The unit is Second.
/// <para>
/// </summary>
[Alias(AliasOT)]
[Parameter(ValueFromPipelineByPropertyName = true)]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout; }
set
{
operationTimeout = value;
operationTimeoutSet = true;
}
}
private UInt32 operationTimeout;
internal bool operationTimeoutSet = false;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "SkipTestConnection".
/// Specifies where test connection should be skipped
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter SkipTestConnection
{
get { return skipTestConnection; }
set
{
skipTestConnection = value;
}
}
private SwitchParameter skipTestConnection;
/// <summary>
/// The following is the definition of the input parameter "Port".
/// Specifies the port number to use, if different than the default port number.
/// This is specificly for wsman protocol.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public UInt32 Port
{
get { return port; }
set
{
port = value;
portSet = true;
}
}
private UInt32 port;
private bool portSet = false;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "SessionOption".
/// Specifies the SessionOption object that is passed to the Cmdlet as argument.
/// </para>
/// <para>
/// If the argument is not given, a default SessionOption will be created for
/// the session in .NET API layer.
/// </para>
/// If a <see cref="DCOMSessionOption"/> object is passed, then
/// connection is made using DCOM. If a <see cref="WsManSessionOption"/>
/// object is passed, then connection is made using WsMan.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public Microsoft.Management.Infrastructure.Options.CimSessionOptions SessionOption
{
get { return sessionOption; }
set { sessionOption = value; }
}
private Microsoft.Management.Infrastructure.Options.CimSessionOptions sessionOption;
#endregion
#region cmdlet processing methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
cimNewSession = new CimNewSession();
this.CmdletOperation = new CmdletOperationTestCimSession(this, this.cimNewSession);
this.AtBeginProcess = false;
}//End BeginProcessing()
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
CimSessionOptions outputOptions;
CimCredential outputCredential;
BuildSessionOptions(out outputOptions, out outputCredential);
cimNewSession.NewCimSession(this, outputOptions, outputCredential);
cimNewSession.ProcessActions(this.CmdletOperation);
}//End ProcessRecord()
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
cimNewSession.ProcessRemainActions(this.CmdletOperation);
}//End EndProcessing()
#endregion
#region helper methods
/// <summary>
/// Build a CimSessionOptions, used to create CimSession
/// </summary>
/// <returns>Null means no prefer CimSessionOptions</returns>
internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCredential outputCredential)
{
DebugHelper.WriteLogEx();
CimSessionOptions options = null;
if (this.SessionOption != null)
{
// clone the sessionOption object
if (this.SessionOption is WSManSessionOptions)
{
options = new WSManSessionOptions(this.sessionOption as WSManSessionOptions);
}
else
{
options = new DComSessionOptions(this.sessionOption as DComSessionOptions);
}
}
outputOptions = null;
outputCredential = null;
if (options != null)
{
DComSessionOptions dcomOptions = (options as DComSessionOptions);
if (dcomOptions != null)
{
bool conflict = false;
string parameterName = string.Empty;
if (this.CertificateThumbprint != null)
{
conflict = true;
parameterName = @"CertificateThumbprint";
}
if (portSet)
{
conflict = true;
parameterName = @"Port";
}
if (conflict)
{
ThrowConflictParameterWasSet(@"New-CimSession", parameterName, @"DComSessionOptions");
return;
}
}
}
if (portSet || (this.CertificateThumbprint != null))
{
WSManSessionOptions wsmanOptions = (options == null) ? new WSManSessionOptions() : options as WSManSessionOptions;
if (portSet)
{
wsmanOptions.DestinationPort = this.Port;
portSet = false;
}
if (this.CertificateThumbprint != null)
{
CimCredential credentials = new CimCredential(CertificateAuthenticationMechanism.Default, this.CertificateThumbprint);
wsmanOptions.AddDestinationCredentials(credentials);
}
options = wsmanOptions;
}
if (this.operationTimeoutSet)
{
if (options != null)
{
options.Timeout = TimeSpan.FromSeconds((double)this.OperationTimeoutSec);
}
}
if (this.authenticationSet || (this.credential != null))
{
PasswordAuthenticationMechanism authentication = this.authenticationSet ? this.Authentication : PasswordAuthenticationMechanism.Default;
if (this.authenticationSet)
{
this.authenticationSet = false;
}
CimCredential credentials = CreateCimCredentials(this.Credential, authentication, @"New-CimSession", @"Authentication");
if (credentials == null)
{
return;
}
DebugHelper.WriteLog("Credentials: {0}", 1, credentials);
outputCredential = credentials;
if (options != null)
{
DebugHelper.WriteLog("Add credentials to option: {0}", 1, options);
options.AddDestinationCredentials(credentials);
}
}
DebugHelper.WriteLogEx("Set outputOptions: {0}", 1, outputOptions);
outputOptions = options;
}
#endregion
#region private members
/// <summary>
/// <para>
/// CimNewSession object
/// </para>
/// </summary>
private CimNewSession cimNewSession;
#endregion
#region IDisposable
/// <summary>
/// Clean up resources
/// </summary>
protected override void DisposeInternal()
{
base.DisposeInternal();
// Dispose managed resources.
if (this.cimNewSession != null)
{
this.cimNewSession.Dispose();
}
}
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,765 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using Microsoft.Management.Infrastructure.Options;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// Define Protocol type.
/// </summary>
public enum ProtocolType
{
Default,
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
Dcom,
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
Wsman
};
/// <summary>
/// The Cmdlet allows the IT Pro to create a CimSessionOptions object that she/he
/// can subsequently use to crate one or more CimSession connections. The
/// options object holds the CIM Session information that is less commonly set
/// and used by the IT Pro, and most commonly defaulted.
///
/// The Cmdlet has two parameter sets, one for WMMan options and one for DCOM
/// options. Depending on the arguments the Cmdlet will return an instance of
/// DComSessionOptions or WSManSessionOptions, which derive from
/// CimSessionOptions.
/// </summary>
[Cmdlet(VerbsCommon.New, "CimSessionOption", DefaultParameterSetName = ProtocolNameParameterSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227969")]
[OutputType(typeof(CimSessionOptions))]
public sealed class NewCimSessionOptionCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// constructor
/// </summary>
public NewCimSessionOptionCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region cmdlet parameters
/// <summary>
/// The following is the definition of the input parameter "NoEncruption".
/// Switch indicating if WSMan can use no encryption in the given CimSession (there are also global client and server WSMan settings - AllowUnencrypted).
/// </summary>
[Parameter(ParameterSetName = WSManParameterSet)]
public SwitchParameter NoEncryption
{
get { return noEncryption; }
set
{
noEncryption = value;
noEncryptionSet = true;
base.SetParameter(value, nameNoEncryption);
}
}
private SwitchParameter noEncryption;
private bool noEncryptionSet = false;
/// <summary>
/// The following is the definition of the input parameter "CertificateCACheck".
/// Switch indicating if Certificate Authority should be validated
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = WSManParameterSet)]
public SwitchParameter SkipCACheck
{
get { return skipCACheck; }
set
{
skipCACheck = value;
skipCACheckSet = true;
base.SetParameter(value, nameSkipCACheck);
}
}
private SwitchParameter skipCACheck;
private bool skipCACheckSet = false;
/// <summary>
/// The following is the definition of the input parameter "CertificateCNCheck".
/// Switch indicating if Certificate Name should be validated
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = WSManParameterSet)]
public SwitchParameter SkipCNCheck
{
get { return skipCNCheck; }
set
{
skipCNCheck = value;
skipCNCheckSet = true;
base.SetParameter(value, nameSkipCNCheck);
}
}
private SwitchParameter skipCNCheck;
private bool skipCNCheckSet = false;
/// <summary>
/// The following is the definition of the input parameter "CertRevocationCheck".
/// Switch indicating if certificate should be revoked.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = WSManParameterSet)]
public SwitchParameter SkipRevocationCheck
{
get { return skipRevocationCheck; }
set
{
skipRevocationCheck = value;
skipRevocationCheckSet = true;
base.SetParameter(value, nameSkipRevocationCheck);
}
}
private SwitchParameter skipRevocationCheck;
private bool skipRevocationCheckSet = false;
/// <summary>
/// The following is the definition of the input parameter "EncodePortInServicePrincipalName".
/// Switch indicating if to encode Port In Service Principal Name
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = WSManParameterSet)]
public SwitchParameter EncodePortInServicePrincipalName
{
get { return encodeportinserviceprincipalname; }
set
{
encodeportinserviceprincipalname = value;
encodeportinserviceprincipalnameSet = true;
base.SetParameter(value, nameEncodePortInServicePrincipalName);
}
}
private SwitchParameter encodeportinserviceprincipalname;
private bool encodeportinserviceprincipalnameSet = false;
/// <summary>
/// The following is the definition of the input parameter "Encoding".
/// Defined the message encoding.
/// The allowed encodings are { Defauolt | Utf8 | Utf16 }. The default value
/// should be Utf8.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = WSManParameterSet)]
public PacketEncoding Encoding
{
get { return encoding; }
set
{
encoding = value;
encodingSet = true;
base.SetParameter(value, nameEncoding);
}
}
private PacketEncoding encoding;
private bool encodingSet = false;
/// <summary>
/// The following is the definition of the input parameter "HttpPrefix".
/// This is the HTTP URL on the server on which the WSMan service is listening.
/// In most cases it is /wsman, which is the default.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = WSManParameterSet)]
public Uri HttpPrefix
{
get { return httpprefix; }
set
{
httpprefix = value;
base.SetParameter(value, nameHttpPrefix);
}
}
private Uri httpprefix;
/// <summary>
/// The following is the definition of the input parameter "MaxEnvelopeSizeKB".
/// Sets the limit to the maximum size of the WSMan message envelope.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = WSManParameterSet)]
public UInt32 MaxEnvelopeSizeKB
{
get { return maxenvelopesizekb; }
set
{
maxenvelopesizekb = value;
maxenvelopesizekbSet = true;
base.SetParameter(value, nameMaxEnvelopeSizeKB);
}
}
private UInt32 maxenvelopesizekb;
private bool maxenvelopesizekbSet = false;
/// <summary>
/// The following is the definition of the input parameter "ProxyAuthentication".
/// Which proxy authentication types to use: Allowed set is:
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = WSManParameterSet)]
public PasswordAuthenticationMechanism ProxyAuthentication
{
get { return proxyAuthentication; }
set
{
proxyAuthentication = value;
proxyauthenticationSet = true;
base.SetParameter(value, nameProxyAuthentication);
}
}
private PasswordAuthenticationMechanism proxyAuthentication;
private bool proxyauthenticationSet = false;
/// <summary>
/// The following is the definition of the input parameter "ProxyCertificateThumbprint".
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = WSManParameterSet)]
public String ProxyCertificateThumbprint
{
get { return proxycertificatethumbprint; }
set
{
proxycertificatethumbprint = value;
base.SetParameter(value, nameProxyCertificateThumbprint);
}
}
private String proxycertificatethumbprint;
/// <summary>
/// The following is the definition of the input parameter "ProxyCredential".
/// Ps Credential used by the proxy server when required by the server.
/// </summary>
[Parameter(ParameterSetName = WSManParameterSet)]
[Credential()]
public PSCredential ProxyCredential
{
get { return proxycredential; }
set
{
proxycredential = value;
base.SetParameter(value, nameProxyCredential);
}
}
private PSCredential proxycredential;
/// <summary>
/// The following is the definition of the input parameter "ProxyType".
/// Which proxy type to use: Valid set is:
/// { InternetExplorer | WinHttp | Auto | None }
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = WSManParameterSet)]
public ProxyType ProxyType
{
get { return proxytype; }
set
{
proxytype = value;
proxytypeSet = true;
base.SetParameter(value, nameProxyType);
}
}
private ProxyType proxytype;
private bool proxytypeSet = false;
/// <summary>
/// The following is the definition of the input parameter "UseSSL".
/// Switch indicating if Secure Sockets Layer connection should be used.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = WSManParameterSet)]
public SwitchParameter UseSsl
{
get { return usessl; }
set
{
usessl = value;
usesslSet = true;
base.SetParameter(value, nameUseSsl);
}
}
private SwitchParameter usessl;
private bool usesslSet = false;
/// <summary>
/// The following is the definition of the input parameter "Impersonation".
/// Used to select if, and if so what kind of, impersonation should be used.
/// Applies only to the DCOM channel.
/// </summary>
[Parameter(ParameterSetName = DcomParameterSet)]
public ImpersonationType Impersonation
{
get { return impersonation; }
set
{
impersonation = value;
impersonationSet = true;
base.SetParameter(value, nameImpersonation);
}
}
private ImpersonationType impersonation;
private bool impersonationSet = false;
/// <summary>
/// The following is the definition of the input parameter "PacketIntegrity".
/// Switch indicating if the package integrity in DCOM connections should be
/// checked/enforced.
/// </summary>
[Parameter(ParameterSetName = DcomParameterSet)]
public SwitchParameter PacketIntegrity
{
get { return packetintegrity; }
set
{
packetintegrity = value;
packetintegritySet = true;
base.SetParameter(value, namePacketIntegrity);
}
}
private SwitchParameter packetintegrity;
private bool packetintegritySet = false;
/// <summary>
/// The following is the definition of the input parameter "PacketPrivacy".
/// Switch indicating if packet privacy of the packets in DCOM communications
/// should be checked/enforced.
/// </summary>
[Parameter(ParameterSetName = DcomParameterSet)]
public SwitchParameter PacketPrivacy
{
get { return packetprivacy; }
set
{
packetprivacy = value;
packetprivacySet = true;
base.SetParameter(value, namePacketPrivacy);
}
}
private SwitchParameter packetprivacy;
private bool packetprivacySet = false;
/// <summary>
/// The following is the definition of the input parameter "Protocol".
/// Switch indicating if to encode Port In Service Principal Name
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ProtocolNameParameterSet)]
public ProtocolType Protocol
{
get { return protocol; }
set
{
protocol = value;
base.SetParameter(value, nameProtocol);
}
}
private ProtocolType protocol;
/// <summary>
/// The following is the definition of the input parameter "UICulture".
/// Specifies the UI Culture to use. i.e. en-us, ar-sa
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public CultureInfo UICulture
{
get { return uiculture; }
set { uiculture = value; }
}
private CultureInfo uiculture;
/// <summary>
/// The following is the definition of the input parameter "Culture".
/// Specifies the culture to use. i.e. en-us, ar-sa
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public CultureInfo Culture
{
get { return culture; }
set { culture = value; }
}
private CultureInfo culture;
#endregion
#region cmdlet processing methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
this.CmdletOperation = new CmdletOperationBase(this);
this.AtBeginProcess = false;
}//End BeginProcessing()
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
CimSessionOptions options;
switch (this.ParameterSetName)
{
case WSManParameterSet:
{
options = CreateWSMANSessionOptions();
}
break;
case DcomParameterSet:
{
options = CreateDComSessionOptions();
}
break;
case ProtocolNameParameterSet:
switch (Protocol)
{
case ProtocolType.Dcom:
options = CreateDComSessionOptions();
break;
case ProtocolType.Wsman:
default:
options = CreateWSMANSessionOptions();
break;
}
break;
default:
return;
}
if (options != null)
{
if (this.Culture != null)
{
options.Culture = this.Culture;
}
if (this.UICulture != null)
{
options.UICulture = this.UICulture;
}
this.WriteObject(options);
}
}//End ProcessRecord()
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
}//End EndProcessing()
#endregion
#region helper functions
/// <summary>
/// Create DComSessionOptions
/// </summary>
/// <returns></returns>
internal DComSessionOptions CreateDComSessionOptions()
{
DComSessionOptions dcomoptions = new DComSessionOptions();
if (this.impersonationSet)
{
dcomoptions.Impersonation = this.Impersonation;
this.impersonationSet = false;
}
else
{
dcomoptions.Impersonation = ImpersonationType.Impersonate;
}
if (this.packetintegritySet)
{
dcomoptions.PacketIntegrity = this.packetintegrity;
this.packetintegritySet = false;
}
else
{
dcomoptions.PacketIntegrity = true;
}
if (this.packetprivacySet)
{
dcomoptions.PacketPrivacy = this.PacketPrivacy;
this.packetprivacySet = false;
}
else
{
dcomoptions.PacketPrivacy = true;
}
return dcomoptions;
}
/// <summary>
/// Create WSMANSessionOptions
/// </summary>
/// <returns></returns>
internal WSManSessionOptions CreateWSMANSessionOptions()
{
WSManSessionOptions wsmanoptions = new WSManSessionOptions();
if (this.noEncryptionSet)
{
wsmanoptions.NoEncryption = true;
this.noEncryptionSet = false;
}
else
{
wsmanoptions.NoEncryption = false;
}
if (this.skipCACheckSet)
{
wsmanoptions.CertCACheck = false;
this.skipCACheckSet = false;
}
else
{
wsmanoptions.CertCACheck = true;
}
if (this.skipCNCheckSet)
{
wsmanoptions.CertCNCheck = false;
this.skipCNCheckSet = false;
}
else
{
wsmanoptions.CertCNCheck = true;
}
if (this.skipRevocationCheckSet)
{
wsmanoptions.CertRevocationCheck = false;
this.skipRevocationCheckSet = false;
}
else
{
wsmanoptions.CertRevocationCheck = true;
}
if (this.encodeportinserviceprincipalnameSet)
{
wsmanoptions.EncodePortInServicePrincipalName = this.EncodePortInServicePrincipalName;
this.encodeportinserviceprincipalnameSet = false;
}
else
{
wsmanoptions.EncodePortInServicePrincipalName = false;
}
if (this.encodingSet)
{
wsmanoptions.PacketEncoding = this.Encoding;
}
else
{
wsmanoptions.PacketEncoding = PacketEncoding.Utf8;
}
if (this.HttpPrefix != null)
{
wsmanoptions.HttpUrlPrefix = this.HttpPrefix;
}
if (this.maxenvelopesizekbSet)
{
wsmanoptions.MaxEnvelopeSize = this.MaxEnvelopeSizeKB;
}
else
{
wsmanoptions.MaxEnvelopeSize = 0;
}
if (!String.IsNullOrWhiteSpace(this.ProxyCertificateThumbprint))
{
CimCredential credentials = new CimCredential(CertificateAuthenticationMechanism.Default, this.ProxyCertificateThumbprint);
wsmanoptions.AddProxyCredentials(credentials);
}
if (this.proxyauthenticationSet)
{
this.proxyauthenticationSet = false;
DebugHelper.WriteLogEx("create credential", 1);
CimCredential credentials = CreateCimCredentials(this.ProxyCredential, this.ProxyAuthentication, @"New-CimSessionOption", @"ProxyAuthentication");
if (credentials != null)
{
try
{
DebugHelper.WriteLogEx("Add proxy credential", 1);
wsmanoptions.AddProxyCredentials(credentials);
}
catch (Exception ex)
{
DebugHelper.WriteLogEx(ex.ToString(), 1);
throw ex;
}
}
}
if (this.proxytypeSet)
{
wsmanoptions.ProxyType = this.ProxyType;
this.proxytypeSet = false;
}
else
{
wsmanoptions.ProxyType = Options.ProxyType.WinHttp;
}
if (this.usesslSet)
{
wsmanoptions.UseSsl = this.UseSsl;
this.usesslSet = false;
}
else
{
wsmanoptions.UseSsl = false;
}
wsmanoptions.DestinationPort = 0;
return wsmanoptions;
}
#endregion
#region private members
#region const string of parameter names
internal const string nameNoEncryption = "NoEncryption";
internal const string nameSkipCACheck = "SkipCACheck";
internal const string nameSkipCNCheck = "SkipCNCheck";
internal const string nameSkipRevocationCheck = "SkipRevocationCheck";
internal const string nameEncodePortInServicePrincipalName = "EncodePortInServicePrincipalName";
internal const string nameEncoding = "Encoding";
internal const string nameHttpPrefix = "HttpPrefix";
internal const string nameMaxEnvelopeSizeKB = "MaxEnvelopeSizeKB";
internal const string nameProxyAuthentication = "ProxyAuthentication";
internal const string nameProxyCertificateThumbprint = "ProxyCertificateThumbprint";
internal const string nameProxyCredential = "ProxyCredential";
internal const string nameProxyType = "ProxyType";
internal const string nameUseSsl = "UseSsl";
internal const string nameImpersonation = "Impersonation";
internal const string namePacketIntegrity = "PacketIntegrity";
internal const string namePacketPrivacy = "PacketPrivacy";
internal const string nameProtocol = "Protocol";
#endregion
/// <summary>
/// static parameter definition entries
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameNoEncryption, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameSkipCACheck, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameSkipCNCheck, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameSkipRevocationCheck, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameEncodePortInServicePrincipalName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameEncoding, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameHttpPrefix, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameMaxEnvelopeSizeKB, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameProxyAuthentication, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameProxyCertificateThumbprint, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameProxyCredential, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameProxyType, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameUseSsl, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.WSManParameterSet, false),
}
},
{
nameImpersonation, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.DcomParameterSet, false),
}
},
{
namePacketIntegrity, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.DcomParameterSet, false),
}
},
{
namePacketPrivacy, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.DcomParameterSet, false),
}
},
{
nameProtocol, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ProtocolNameParameterSet, true),
}
},
};
/// <summary>
/// static parameter set entries
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.ProtocolNameParameterSet, new ParameterSetEntry(1, true) },
{ CimBaseCommand.DcomParameterSet, new ParameterSetEntry(0) },
{ CimBaseCommand.WSManParameterSet, new ParameterSetEntry(0) },
};
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,351 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation;
using Microsoft.PowerShell.Commands;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// Enables the user to subscribe to indications using Filter Expression or
/// Query Expression.
/// -SourceIdentifier is a name given to the subscription
/// The Cmdlet should return a PS EventSubscription object that can be used to
/// cancel the subscription
/// Should we have the second parameter set with a -Query?
/// </summary>
[Cmdlet(VerbsLifecycle.Register, "CimIndicationEvent", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227960")]
public class RegisterCimIndicationCommand : ObjectEventRegistrationBase
{
#region parameters
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Namespace".
/// Specifies the NameSpace under which to look for the specified class name.
/// </para>
/// <para>
/// Default value is root\cimv2
/// </para>
/// </summary>
[Parameter]
public String Namespace
{
get { return nameSpace; }
set { nameSpace = value; }
}
private String nameSpace;
/// <summary>
/// The following is the definition of the input parameter "ClassName".
/// Specifies the Class Name to register the indication on.
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
[Parameter(Mandatory = true,
Position = 0,
ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
public String ClassName
{
get { return className; }
set
{
className = value;
this.SetParameter(value, nameClassName);
}
}
private String className;
/// <summary>
/// The following is the definition of the input parameter "Query".
/// The Query Expression to pass.
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)]
[Parameter(
Mandatory = true,
Position = 0,
ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)]
public String Query
{
get { return query; }
set
{
query = value;
this.SetParameter(value, nameQuery);
}
}
private String query;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "QueryDialect".
/// Specifies the dialect used by the query Engine that interprets the Query
/// string.
/// </para>
/// </summary>
[Parameter(ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)]
[Parameter(ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)]
public String QueryDialect
{
get { return queryDialect; }
set
{
queryDialect = value;
this.SetParameter(value, nameQueryDialect);
}
}
private String queryDialect;
/// <summary>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Enables the user to specify the operation timeout in Seconds. This value
/// overwrites the value specified by the CimSession Operation timeout.
/// </summary>
[Alias(CimBaseCommand.AliasOT)]
[Parameter]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout; }
set { operationTimeout = value; }
}
private UInt32 operationTimeout;
/// <summary>
/// The following is the definition of the input parameter "Session".
/// Uses a CimSession context.
/// </summary>
[Parameter(
Mandatory = true,
ParameterSetName = CimBaseCommand.QueryExpressionSessionSet)]
[Parameter(
Mandatory = true,
ParameterSetName = CimBaseCommand.ClassNameSessionSet)]
public CimSession CimSession
{
get { return cimSession; }
set
{
cimSession = value;
this.SetParameter(value, nameCimSession);
}
}
private CimSession cimSession;
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Specifies the computer on which the commands associated with this session
/// will run. The default value is LocalHost.
/// </summary>
[Alias(CimBaseCommand.AliasCN, CimBaseCommand.AliasServerName)]
[Parameter(ParameterSetName = CimBaseCommand.QueryExpressionComputerSet)]
[Parameter(ParameterSetName = CimBaseCommand.ClassNameComputerSet)]
public String ComputerName
{
get { return computername; }
set
{
computername = value;
this.SetParameter(value, nameComputerName);
}
}
private String computername;
#endregion
/// <summary>
/// Returns the object that generates events to be monitored
/// </summary>
protected override Object GetSourceObject()
{
CimIndicationWatcher watcher = null;
string parameterSetName = null;
try
{
parameterSetName = this.parameterBinder.GetParameterSet();
}
finally
{
this.parameterBinder.reset();
}
string tempQueryExpression = string.Empty;
switch (parameterSetName)
{
case CimBaseCommand.QueryExpressionSessionSet:
case CimBaseCommand.QueryExpressionComputerSet:
tempQueryExpression = this.Query;
break;
case CimBaseCommand.ClassNameSessionSet:
case CimBaseCommand.ClassNameComputerSet:
// validate the classname
this.CheckArgument();
tempQueryExpression = String.Format(CultureInfo.CurrentCulture, "Select * from {0}", this.ClassName);
break;
}
switch (parameterSetName)
{
case CimBaseCommand.QueryExpressionSessionSet:
case CimBaseCommand.ClassNameSessionSet:
{
watcher = new CimIndicationWatcher(this.CimSession, this.Namespace, this.QueryDialect, tempQueryExpression, this.OperationTimeoutSec);
}
break;
case CimBaseCommand.QueryExpressionComputerSet:
case CimBaseCommand.ClassNameComputerSet:
{
watcher = new CimIndicationWatcher(this.ComputerName, this.Namespace, this.QueryDialect, tempQueryExpression, this.OperationTimeoutSec);
}
break;
}
if (watcher != null)
{
watcher.SetCmdlet(this);
}
return watcher;
}
/// <summary>
/// Returns the event name to be monitored on the input object
/// </summary>
protected override String GetSourceObjectEventName()
{
return "CimIndicationArrived";
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
DebugHelper.WriteLogEx();
base.EndProcessing();
// Register for the "Unsubscribed" event so that we can stop the
// Cimindication event watcher.
PSEventSubscriber newSubscriber = NewSubscriber;
if (newSubscriber != null)
{
DebugHelper.WriteLog("RegisterCimIndicationCommand::EndProcessing subscribe to Unsubscribed event", 4);
newSubscriber.Unsubscribed += new PSEventUnsubscribedEventHandler(newSubscriber_Unsubscribed);
}
}//End EndProcessing()
/// <summary>
/// <para>
/// Hanlder to handle unsubcribe event
/// </para>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void newSubscriber_Unsubscribed(
object sender, PSEventUnsubscribedEventArgs e)
{
DebugHelper.WriteLogEx();
CimIndicationWatcher watcher = sender as CimIndicationWatcher;
if (watcher != null)
{
watcher.Stop();
}
}
#region private members
/// <summary>
/// check argument value
/// </summary>
private void CheckArgument()
{
this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className);
}
/// <summary>
/// Parameter binder used to resolve parameter set name
/// </summary>
private ParameterBinder parameterBinder = new ParameterBinder(
parameters, parameterSets);
/// <summary>
/// Set the parameter
/// </summary>
/// <param name="parameterName"></param>
private void SetParameter(object value, string parameterName)
{
if (value == null)
{
return;
}
this.parameterBinder.SetParameter(parameterName, true);
}
#region const string of parameter names
internal const string nameClassName = "ClassName";
internal const string nameQuery = "Query";
internal const string nameQueryDialect = "QueryDialect";
internal const string nameCimSession = "CimSession";
internal const string nameComputerName = "ComputerName";
#endregion
/// <summary>
/// static parameter definition entries
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameClassName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true),
}
},
{
nameQuery, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, true),
}
},
{
nameQueryDialect, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, false),
}
},
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true),
}
},
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QueryExpressionComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false),
}
},
};
/// <summary>
/// static parameter set entries
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.QueryExpressionSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.QueryExpressionComputerSet, new ParameterSetEntry(1) },
{ CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) },
};
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,370 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// Enables the user to remove a CimInstance.
/// </summary>
[Cmdlet(
VerbsCommon.Remove,
"CimInstance",
SupportsShouldProcess=true,
DefaultParameterSetName = CimBaseCommand.CimInstanceComputerSet,
HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227964")]
public class RemoveCimInstanceCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// constructor
/// </summary>
public RemoveCimInstanceCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region parameters
/// <summary>
/// The following is the definition of the input parameter "Session".
/// CIM session used to remove the CIM Instance.
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public CimSession[] CimSession
{
get { return cimSession; }
set
{
cimSession = value;
base.SetParameter(value, nameCimSession);
}
}
private CimSession[] cimSession;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ResourceUri".
/// Define the Resource Uri for which the instances are retrieved.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
public Uri ResourceUri
{
get { return resourceUri; }
set
{
this.resourceUri = value;
base.SetParameter(value, nameResourceUri);
}
}
private Uri resourceUri;
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] ComputerName
{
get { return computername; }
set
{
computername = value;
base.SetParameter(value, nameComputerName);
}
}
private String[] computername;
/// <summary>
/// The following is the definition of the input parameter "Namespace".
/// The Namespace used to look for the Class instances under.
/// </summary>
[Parameter(
Position = 1,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[Parameter(
Position = 1,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
public String Namespace
{
get { return nameSpace; }
set
{
nameSpace = value;
base.SetParameter(value, nameNamespace);
}
}
private String nameSpace;
/// <summary>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Used to set the invocation operation time out. This value overrides the
/// CimSession operation timeout.
/// </summary>
[Alias(AliasOT)]
[Parameter]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout;}
set { operationTimeout = value; }
}
private UInt32 operationTimeout;
/// <summary>
/// The following is the definition of the input parameter "InputObject".
/// Used to get a CimInstance using Get-CimInstance | Remove-CimInstance.
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Alias(CimBaseCommand.AliasCimInstance)]
public CimInstance InputObject
{
get { return cimInstance; }
set
{
cimInstance = value;
base.SetParameter(value, nameCimInstance);
}
}
/// <summary>
/// Property for internal usage purpose
/// </summary>
internal CimInstance CimInstance
{
get { return cimInstance; }
}
private CimInstance cimInstance;
/// <summary>
/// The following is the definition of the input parameter "Query".
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
public String Query
{
get { return query;}
set
{
query = value;
base.SetParameter(value, nameQuery);
}
}
private String query;
/// <summary>
/// The following is the definition of the input parameter "QueryDialect".
/// Specifies the dialect used by the query Engine that interprets the Query
/// string.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
public String QueryDialect
{
get { return querydialect;}
set
{
querydialect = value;
base.SetParameter(value, nameQueryDialect);
}
}
private String querydialect;
#endregion
#region cmdlet methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
CimRemoveCimInstance cimRemoveInstance = this.GetOperationAgent();
if (cimRemoveInstance == null)
{
cimRemoveInstance = CreateOperationAgent();
}
this.CmdletOperation = new CmdletOperationRemoveCimInstance(this, cimRemoveInstance);
this.AtBeginProcess = false;
}//End BeginProcessing()
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
CimRemoveCimInstance cimRemoveInstance = this.GetOperationAgent();
cimRemoveInstance.RemoveCimInstance(this);
cimRemoveInstance.ProcessActions(this.CmdletOperation);
}//End ProcessRecord()
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
CimRemoveCimInstance cimRemoveInstance = this.GetOperationAgent();
if (cimRemoveInstance != null)
{
cimRemoveInstance.ProcessRemainActions(this.CmdletOperation);
}
}//End EndProcessing()
#endregion
#region helper methods
/// <summary>
/// <para>
/// Get <see cref="CimRemoveCimInstance"/> object, which is
/// used to delegate all Remove-CimInstance operations.
/// </para>
/// </summary>
CimRemoveCimInstance GetOperationAgent()
{
return (this.AsyncOperation as CimRemoveCimInstance);
}
/// <summary>
/// <para>
/// Create <see cref="CimRemoveCimInstance"/> object, which is
/// used to delegate all Remove-CimInstance operations.
/// </para>
/// </summary>
/// <returns></returns>
CimRemoveCimInstance CreateOperationAgent()
{
CimRemoveCimInstance cimRemoveInstance = new CimRemoveCimInstance();
this.AsyncOperation = cimRemoveInstance;
return cimRemoveInstance;
}
#endregion
#region private members
#region const string of parameter names
internal const string nameCimSession = "CimSession";
internal const string nameComputerName = "ComputerName";
internal const string nameResourceUri = "ResourceUri";
internal const string nameNamespace = "Namespace";
internal const string nameCimInstance = "InputObject";
internal const string nameQuery = "Query";
internal const string nameQueryDialect = "QueryDialect";
#endregion
/// <summary>
/// static parameter definition entries
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true),
}
},
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false),
}
},
{
nameNamespace, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
}
},
{
nameCimInstance, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true),
}
},
{
nameQuery, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true),
}
},
{
nameQueryDialect, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
}
},
{
nameResourceUri, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, false),
}
},
};
/// <summary>
/// static parameter set entries
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(1, true) },
{ CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.QueryComputerSet, new ParameterSetEntry(1) },
{ CimBaseCommand.QuerySessionSet, new ParameterSetEntry(2) },
};
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,234 @@
//
// Copyright (C) Microsoft. All rights reserved.
//
#region Using directives
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
#endregion
/******************************************************************************
* warning 28750: Banned usage of lstrlen and its variants: lstrlenW is a
* banned API for improved error handling purposes.
*****************************************************************************/
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// This Cmdlet allows the to remove, or terminate, one or more CimSession(s).
/// </summary>
[Cmdlet(VerbsCommon.Remove, "CimSession",
SupportsShouldProcess = true,
DefaultParameterSetName = CimSessionSet,
HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227968")]
public sealed class RemoveCimSessionCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// constructor
/// </summary>
public RemoveCimSessionCommand()
: base(parameters, parameterSets)
{
}
#endregion
#region parameters
/// <summary>
/// The following is the definition of the input parameter "CimSession".
/// Specifies one or more CimSession object to be removed from the local PS
/// session/runspace.
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimSessionSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public CimSession[] CimSession
{
get { return cimsession;}
set
{
cimsession = value;
base.SetParameter(value, nameCimSession);
}
}
private CimSession[] cimsession;
/// <summary>
/// <para>The following is the definition of the input parameter "ComputerName".
/// Specified one or more computer names for which all CimSession(s)
/// (connections) should be removed (terminated).</para>
/// <para>This is the only optional parameter. If no value for this parameter is
/// provided, all CimSession(s) are terminated.</para>
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ComputerNameSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] ComputerName
{
get { return computername; }
set
{
computername = value;
base.SetParameter(value, nameComputerName);
}
}
private String[] computername;
/// <summary>
/// The following is the definition of the input parameter "Id".
/// Specifies the friendly Id(s) of the CimSession(s) that should be removed
/// (terminated).
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = SessionIdSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public UInt32[] Id
{
get { return id;}
set
{
id = value;
base.SetParameter(value, nameId);
}
}
private UInt32[] id;
/// <summary>
/// The following is the definition of the input parameter "InstanceId".
/// Specifies one or more automatically generated InstanceId(s) (GUIDs) of the
/// CimSession(s) that should be removed (terminated).
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InstanceIdSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Guid[] InstanceId
{
get { return instanceid;}
set
{
instanceid = value;
base.SetParameter(value, nameInstanceId);
}
}
private Guid[] instanceid;
/// <summary>
/// The following is the definition of the input parameter "Name".
/// Specifies one or more of friendly Names of the CimSession(s) that should be
/// removed (terminated).
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = NameSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] Name
{
get { return name;}
set
{
name = value;
base.SetParameter(value, nameName);
}
}
private String[] name;
#endregion
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
this.cimRemoveSession = new CimRemoveSession();
this.AtBeginProcess = false;
}//End BeginProcessing()
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
this.cimRemoveSession.RemoveCimSession(this);
}//End ProcessRecord()
#region private members
/// <summary>
/// <see cref="CimRemoveSession"/> object used to remove the session from
/// session cache
/// </summary>
private CimRemoveSession cimRemoveSession;
#region const string of parameter names
internal const string nameCimSession = "CimSession";
internal const string nameComputerName = "ComputerName";
internal const string nameId = "Id";
internal const string nameInstanceId = "InstanceId";
internal const string nameName = "Name";
#endregion
/// <summary>
/// static parameter definition entries
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimSessionSet, true),
}
},
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ComputerNameSet, true),
}
},
{
nameId, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.SessionIdSet, true),
}
},
{
nameInstanceId, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.InstanceIdSet, true),
}
},
{
nameName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.NameSet, true),
}
},
};
/// <summary>
/// static parameter set entries
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.CimSessionSet, new ParameterSetEntry(1, true) },
{ CimBaseCommand.ComputerNameSet, new ParameterSetEntry(1) },
{ CimBaseCommand.SessionIdSet, new ParameterSetEntry(1) },
{ CimBaseCommand.InstanceIdSet, new ParameterSetEntry(1) },
{ CimBaseCommand.NameSet, new ParameterSetEntry(1) },
};
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,430 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Enables the user to Set properties and keys on a specific <see cref="CimInstance"/>
/// CimInstance must have values of all [KEY] properties.
/// </para>
/// </summary>
[Cmdlet(
VerbsCommon.Set,
"CimInstance",
SupportsShouldProcess = true,
DefaultParameterSetName = CimBaseCommand.CimInstanceComputerSet,
HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227962")]
public class SetCimInstanceCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// constructor
/// </summary>
public SetCimInstanceCommand()
: base(parameters, parameterSets)
{
}
#endregion
#region parameters
/// <summary>
/// The following is the definition of the input parameter "Session".
/// CIM session used to set the CIM Instance.
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public CimSession[] CimSession
{
get { return cimSession; }
set
{
cimSession = value;
base.SetParameter(value, nameCimSession);
}
}
private CimSession[] cimSession;
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] ComputerName
{
get { return computername; }
set
{
computername = value;
base.SetParameter(value, nameComputerName);
}
}
private String[] computername;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ResourceUri".
/// Define the Resource Uri for which the instances are retrieved.
/// </para>
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
public Uri ResourceUri
{
get { return resourceUri; }
set
{
this.resourceUri = value;
base.SetParameter(value, nameResourceUri);
}
}
private Uri resourceUri;
/// <summary>
/// The following is the definition of the input parameter "Namespace".
/// The Namespace used to look for the Class instances under.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
public String Namespace
{
get { return nameSpace; }
set
{
nameSpace = value;
base.SetParameter(value, nameNamespace);
}
}
private String nameSpace;
/// <summary>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Used to set the invocation operation time out. This value overrides the
/// CimSession operation timeout.
/// </summary>
[Alias(AliasOT)]
[Parameter]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout; }
set { operationTimeout = value; }
}
private UInt32 operationTimeout;
/// <summary>
/// The following is the definition of the input parameter "InputObject".
/// Used to get a CimInstance using Get-CimInstance | Set-CimInstance.
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Alias(CimBaseCommand.AliasCimInstance)]
public CimInstance InputObject
{
get { return cimInstance; }
set
{
cimInstance = value;
base.SetParameter(value, nameCimInstance);
}
}
/// <summary>
/// Property for internal usage purpose
/// </summary>
internal CimInstance CimInstance
{
get { return cimInstance; }
}
private CimInstance cimInstance;
/// <summary>
/// The following is the definition of the input parameter "Query".
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
public String Query
{
get { return query; }
set
{
query = value;
base.SetParameter(value, nameQuery);
}
}
private String query;
/// <summary>
/// The following is the definition of the input parameter "QueryDialect".
/// Specifies the dialect used by the query Engine that interprets the Query
/// string.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
public String QueryDialect
{
get { return querydialect; }
set
{
querydialect = value;
base.SetParameter(value, nameQueryDialect);
}
}
private String querydialect;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "Property",
/// defines the value to be changed.
/// </para>
/// <para>
/// The key properties will be ignored. Any invalid property will cause
/// termination of the cmdlet execution.
/// </para>
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QuerySessionSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.QueryComputerSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.CimInstanceSessionSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = CimBaseCommand.CimInstanceComputerSet)]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
[Alias("Arguments")]
public IDictionary Property
{
get { return property; }
set
{
property = value;
base.SetParameter(value, nameProperty);
}
}
private IDictionary property;
/// <summary>
/// The following is the definition of the input parameter "PassThru",
/// indicate whether Set-CimInstance should output modified result instance or not.
/// <para>
/// True indicates output the result instance, otherwise output nothing as by default
/// behavior.
/// </para>
/// </summary>
[Parameter]
[ValidateNotNull]
public SwitchParameter PassThru
{
set
{
this.passThru = value;
}
get
{
return this.passThru;
}
}
private SwitchParameter passThru;
#endregion
#region cmdlet methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
CimSetCimInstance cimSetCimInstance = this.GetOperationAgent();
if (cimSetCimInstance == null)
{
cimSetCimInstance = CreateOperationAgent();
}
this.CmdletOperation = new CmdletOperationSetCimInstance(this, cimSetCimInstance);
this.AtBeginProcess = false;
}//End BeginProcessing()
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
CimSetCimInstance cimSetCimInstance = this.GetOperationAgent();
cimSetCimInstance.SetCimInstance(this);
cimSetCimInstance.ProcessActions(this.CmdletOperation);
}//End ProcessRecord()
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
CimSetCimInstance cimSetCimInstance = this.GetOperationAgent();
if (cimSetCimInstance != null)
{
cimSetCimInstance.ProcessRemainActions(this.CmdletOperation);
}
}//End EndProcessing()
#endregion
#region helper methods
/// <summary>
/// <para>
/// Get <see cref="CimSetCimInstance"/> object, which is
/// used to delegate all Set-CimInstance operations.
/// </para>
/// </summary>
CimSetCimInstance GetOperationAgent()
{
return (this.AsyncOperation as CimSetCimInstance);
}
/// <summary>
/// <para>
/// Create <see cref="CimSetCimInstance"/> object, which is
/// used to delegate all Set-CimInstance operations.
/// </para>
/// </summary>
/// <returns></returns>
CimSetCimInstance CreateOperationAgent()
{
CimSetCimInstance cimSetCimInstance = new CimSetCimInstance();
this.AsyncOperation = cimSetCimInstance;
return cimSetCimInstance;
}
#endregion
#region private members
#region const string of parameter names
internal const string nameCimSession = "CimSession";
internal const string nameComputerName = "ComputerName";
internal const string nameResourceUri = "ResourceUri";
internal const string nameNamespace = "Namespace";
internal const string nameCimInstance = "InputObject";
internal const string nameQuery = "Query";
internal const string nameQueryDialect = "QueryDialect";
internal const string nameProperty = "Property";
#endregion
/// <summary>
/// static parameter definition entries
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true),
}
},
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false),
}
},
{
nameNamespace, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
}
},
{
nameCimInstance, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, true),
}
},
{
nameQuery, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true),
}
},
{
nameQueryDialect, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false),
}
},
{
nameProperty, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.QuerySessionSet, true),
new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, true),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false),
}
},
{
nameResourceUri, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceComputerSet, false),
new ParameterDefinitionEntry(CimBaseCommand.CimInstanceSessionSet, false),
}
},
};
/// <summary>
/// static parameter set entries
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.QuerySessionSet, new ParameterSetEntry(3) },
{ CimBaseCommand.QueryComputerSet, new ParameterSetEntry(2) },
{ CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(2) },
{ CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(1, true) },
};
#endregion
}//End Class
}//End namespace
@@ -0,0 +1,465 @@
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
// #define LOGENABLE // uncomment this line to enable the log,
// create c:\temp\cim.log before invoking cimcmdlets
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Text.RegularExpressions;
using System.Threading;
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Global Non-localization strings
/// </para>
/// </summary>
internal static class ConstValue
{
/// <summary>
/// <para>
/// Default computername
/// </para>
/// </summary>
internal static string[] DefaultSessionName = {@"*"};
/// <summary>
/// <para>
/// Empty computername, which will create DCOM session
/// </para>
/// </summary>
internal static string NullComputerName = null;
/// <summary>
/// <para>
/// Empty computername array, which will create DCOM session
/// </para>
/// </summary>
internal static string[] NullComputerNames = { NullComputerName };
/// <summary>
/// <para>
/// localhost computername, which will create WSMAN session
/// </para>
/// </summary>
internal static string LocalhostComputerName = @"localhost";
/// <summary>
/// <para>
/// Default namespace
/// </para>
/// </summary>
internal static string DefaultNameSpace = @"root\cimv2";
/// <summary>
/// <para>
/// Default namespace
/// </para>
/// </summary>
internal static string DefaultQueryDialect = @"WQL";
/// <summary>
/// Name of the note property that controls if "PSComputerName" column is shown
/// </summary>
internal static string ShowComputerNameNoteProperty = "PSShowComputerName";
/// <summary>
/// <para>
/// Whether given computername is either null or empty
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <returns></returns>
internal static bool IsDefaultComputerName(string computerName)
{
return String.IsNullOrEmpty(computerName);
}
/// <summary>
/// <para>
/// Get computer names, if it is null then return DCOM one
/// </para>
/// </summary>
/// <param name="computerNames"></param>
/// <returns></returns>
internal static IEnumerable<string> GetComputerNames(IEnumerable<string> computerNames)
{
return (computerNames == null) ? NullComputerNames : computerNames;
}
/// <summary>
/// Get computer name, if it is null then return default one
/// </summary>
/// <param name="computerName"></param>
/// <returns></returns>
internal static string GetComputerName(string computerName)
{
return string.IsNullOrEmpty(computerName) ? NullComputerName : computerName;
}
/// <summary>
/// <para>
/// Get namespace, if it is null then return default one
/// </para>
/// </summary>
/// <param name="nameSpace"></param>
/// <returns></returns>
internal static string GetNamespace(string nameSpace)
{
return (nameSpace == null) ? DefaultNameSpace : nameSpace;
}
/// <summary>
/// <para>
/// Get queryDialect, if it is null then return default query Dialect
/// </para>
/// </summary>
/// <param name="queryDialect"></param>
/// <returns></returns>
internal static string GetQueryDialectWithDefault(string queryDialect)
{
return (queryDialect == null) ? DefaultQueryDialect : queryDialect;
}
}
/// <summary>
/// <para>
/// Debug helper class used to dump debug message to log file
/// </para>
/// </summary>
internal static class DebugHelper
{
#region private members
/// <summary>
/// Flag used to control generating log message into file.
/// </summary>
private static bool generateLog = true;
internal static bool GenerateLog
{
get { return generateLog; }
set { generateLog = value; }
}
/// <summary>
/// Whether the log been initialized
/// </summary>
private static bool logInitialized = false;
/// <summary>
/// Flag used to control generating message into powershell
/// </summary>
private static bool genrateVerboseMessage = true;
internal static bool GenrateVerboseMessage
{
get { return genrateVerboseMessage; }
set { genrateVerboseMessage = value; }
}
/// <summary>
/// Flag used to control generating message into powershell
/// </summary>
internal static string logFile = @"c:\temp\Cim.log";
/// <summary>
/// Indent space string
/// </summary>
internal static string space = @" ";
/// <summary>
/// Indent space strings array
/// </summary>
internal static string[] spaces = {
string.Empty,
space,
space + space,
space + space + space,
space + space + space + space,
space + space + space + space + space,
};
/// <summary>
/// Lock the log file
/// </summary>
internal static object logLock = new object();
#endregion
#region internal strings
internal static string runspaceStateChanged = "Runspace {0} state changed to {1}";
internal static string classDumpInfo = @"Class type is {0}";
internal static string propertyDumpInfo = @"Property name {0} of type {1}, its value is {2}";
internal static string defaultPropertyType = @"It is a default property, default value is {0}";
internal static string propertyValueSet = @"This property value is set by user {0}";
internal static string addParameterSetName = @"Add parameter set {0} name to cache";
internal static string removeParameterSetName = @"Remove parameter set {0} name from cache";
internal static string currentParameterSetNameCount = @"Cache have {0} parameter set names";
internal static string currentParameterSetNameInCache = @"Cache have parameter set {0} valid {1}";
internal static string currentnonMadatoryParameterSetInCache = @"Cache have optional parameter set {0} valid {1}";
internal static string optionalParameterSetNameCount = @"Cache have {0} optional parameter set names";
internal static string finalParameterSetName = @"------Final parameter set name of the cmdlet is {0}";
internal static string addToOptionalParameterSet = @"Add to optional ParameterSetNames {0}";
internal static string startToResolveParameterSet = @"------Resolve ParameterSet Name";
internal static string reservedString = @"------";
#endregion
#region runtime methods
internal static string GetSourceCodeInformation(bool withFileName, int depth)
{
#if CORECLR
//return a dummy string as StackFrame won't be available on CoreCLR
return string.Format(CultureInfo.CurrentUICulture, "{0}::{1} ", "Type", "Method");
#else
StackTrace trace = new StackTrace();
StackFrame frame = trace.GetFrame(depth);
//if (withFileName)
//{
// return string.Format(CultureInfo.CurrentUICulture, "{0}#{1}:{2}:", frame.GetFileName()., frame.GetFileLineNumber(), frame.GetMethod().Name);
//}
//else
//{
// return string.Format(CultureInfo.CurrentUICulture, "{0}:", frame.GetMethod());
//}
return string.Format(CultureInfo.CurrentUICulture, "{0}::{1} ",
frame.GetMethod().DeclaringType.Name,
frame.GetMethod().Name);
#endif
}
#endregion
/// <summary>
/// Write message to log file named @logFile
/// </summary>
/// <param name="message"></param>
internal static void WriteLog(string message)
{
WriteLog(message, 0);
}
/// <summary>
/// Write blank line to log file named @logFile
/// </summary>
/// <param name="message"></param>
internal static void WriteEmptyLine()
{
WriteLog(string.Empty, 0);
}
/// <summary>
/// Write message to log file named @logFile with args
/// </summary>
/// <param name="message"></param>
internal static void WriteLog(string message, int indent, params object[] args)
{
String outMessage = String.Empty;
FormatLogMessage(ref outMessage, message, args);
WriteLog(outMessage, indent);
}
/// <summary>
/// Write message to log file w/o arguments
/// </summary>
/// <param name="message"></param>
/// <param name="indent"></param>
internal static void WriteLog(string message, int indent)
{
WriteLogInternal(message, indent, -1);
}
/// <summary>
/// Write message to log file named @logFile with args
/// </summary>
/// <param name="message"></param>
internal static void WriteLogEx(string message, int indent, params object[] args)
{
String outMessage = String.Empty;
WriteLogInternal(string.Empty, 0, -1);
FormatLogMessage(ref outMessage, message, args);
WriteLogInternal(outMessage, indent, 3);
}
/// <summary>
/// Write message to log file w/o arguments
/// </summary>
/// <param name="message"></param>
/// <param name="indent"></param>
internal static void WriteLogEx(string message, int indent)
{
WriteLogInternal(string.Empty, 0, -1);
WriteLogInternal(message, indent, 3);
}
/// <summary>
/// Write message to log file w/o arguments
/// </summary>
/// <param name="message"></param>
/// <param name="indent"></param>
internal static void WriteLogEx()
{
WriteLogInternal(string.Empty, 0, -1);
WriteLogInternal(string.Empty, 0, 3);
}
/// <summary>
/// Format the message
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
/// <returns></returns>
[Conditional("LOGENABLE")]
private static void FormatLogMessage(ref String outMessage, string message, params object[] args)
{
outMessage = String.Format(CultureInfo.CurrentCulture, message, args);
}
/// <summary>
/// Write message to log file named @logFile
/// with indent space ahead of the message.
/// </summary>
/// <param name="message"></param>
/// <param name="nIndent"></param>
[Conditional("LOGENABLE")]
private static void WriteLogInternal(string message, int indent, int depth)
{
if (!logInitialized)
{
lock (logLock)
{
if (!logInitialized)
{
DebugHelper.GenerateLog = File.Exists(logFile);
logInitialized = true;
}
}
}
if (generateLog)
{
if (indent < 0)
{
indent = 0;
}
if (indent > 5)
{
indent = 5;
}
string sourceInformation = string.Empty;
if (depth != -1)
{
sourceInformation = string.Format(
CultureInfo.InvariantCulture,
"Thread {0}#{1}:{2}:{3} {4}",
Thread.CurrentThread.ManagedThreadId,
DateTime.Now.Hour,
DateTime.Now.Minute,
DateTime.Now.Second,
GetSourceCodeInformation(true, depth));
}
lock (logLock)
{
using (FileStream fs = new FileStream(logFile,FileMode.OpenOrCreate))
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLineAsync(spaces[indent] + sourceInformation + @" " + message);
}
}
}
}
}
/// <summary>
/// <para>
/// Helper class used to validate given parameter
/// </para>
/// </summary>
internal static class ValidationHelper
{
/// <summary>
/// Validate the argument is not null
/// </summary>
/// <param name="obj"></param>
/// <param name="argumentName"></param>
public static void ValidateNoNullArgument(object obj, string argumentName)
{
if (obj == null)
{
throw new ArgumentNullException(argumentName);
}
}
/// <summary>
/// Validate the argument is not null and not whitespace
/// </summary>
/// <param name="obj"></param>
/// <param name="argumentName"></param>
public static void ValidateNoNullorWhiteSpaceArgument(string obj, string argumentName)
{
if (String.IsNullOrWhiteSpace(obj))
{
throw new ArgumentException(argumentName);
}
}
/// <summary>
/// Validate that given classname/propertyname is a valid name compliance with DMTF standard.
/// Only for verifying ClassName and PropertyName argument
/// </summary>
/// <param name="parameterName"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="ArgumentException">Throw if the given value is not a valid name (class name or property name)</exception>
public static string ValidateArgumentIsValidName(string parameterName, string value)
{
DebugHelper.WriteLogEx();
if (value != null)
{
string trimed = value.Trim();
// The first character should be contained in set: [A-Za-z_]
// Inner characters should be contained in set: [A-Za-z0-9_]
Regex regex = new Regex(@"^[a-zA-Z_][a-zA-Z0-9_]*\z");
if (regex.IsMatch(trimed))
{
DebugHelper.WriteLogEx("A valid name: {0}={1}", 0, parameterName, value);
return trimed;
}
}
DebugHelper.WriteLogEx("An invalid name: {0}={1}", 0, parameterName, value);
throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, Strings.InvalidParameterValue, value, parameterName));
}
/// <summary>
/// Validate given arry argument contains all valid name (for -SelectProperties).
/// * is valid for this case.
/// </summary>
/// <param name="parameterName"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="ArgumentException">Throw if the given value contains any invalid name (class name or property name)</exception>
public static String[] ValidateArgumentIsValidName(string parameterName, String[] value)
{
if (value != null)
{
foreach (string propertyName in value)
{
// * is wild char supported in select properties
if ((propertyName != null) && (String.Compare(propertyName.Trim(), "*", StringComparison.OrdinalIgnoreCase) == 0))
{
continue;
}
ValidationHelper.ValidateArgumentIsValidName(parameterName, propertyName);
}
}
return value;
}
}
}
@@ -0,0 +1,228 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CimOperationCompleted" xml:space="preserve">
<value>Operation '{0}' complete.</value>
<comment>{0} is a placeholder for operation name. (i.e, GetCimInstance)</comment>
</data>
<data name="CimOperationNameCreateInstance" xml:space="preserve">
<value>Create CimInstance</value>
</data>
<data name="CimOperationNameDeleteInstance" xml:space="preserve">
<value>Delete CimInstance</value>
</data>
<data name="CimOperationNameEnumerateAssociatedInstances" xml:space="preserve">
<value>Enumerate Associated CimInstances</value>
</data>
<data name="CimOperationNameEnumerateClasses" xml:space="preserve">
<value>Enumerate CimClasses</value>
</data>
<data name="CimOperationNameEnumerateInstances" xml:space="preserve">
<value>Enumerate CimInstances</value>
</data>
<data name="CimOperationNameGetClass" xml:space="preserve">
<value>Get CimClass</value>
</data>
<data name="CimOperationNameGetInstance" xml:space="preserve">
<value>Get CimInstance</value>
</data>
<data name="CimOperationNameInvokeMethod" xml:space="preserve">
<value>Invoke CimMethod</value>
</data>
<data name="CimOperationNameModifyInstance" xml:space="preserve">
<value>Modify CimInstance</value>
</data>
<data name="CimOperationNameQueryInstances" xml:space="preserve">
<value>Query CimInstances</value>
</data>
<data name="CimOperationNameSubscribeIndication" xml:space="preserve">
<value>Subscribe CimIndication</value>
</data>
<data name="CimOperationStart" xml:space="preserve">
<value>Perform operation '{0}' with following parameters, '{1}'.</value>
<comment>{0} is a placeholder for operation name; {1} is a placeholder for parameters value</comment>
</data>
<data name="ConflictParameterWasSet" xml:space="preserve">
<value>Parameter '{0}' cannot be used with the parameter '{1}'.</value>
<comment>{0} is a placeholder for parameter name; {1} is a placeholder for another parameter name;</comment>
</data>
<data name="CouldNotFindCimsessionObject" xml:space="preserve">
<value>Could not find CimSession with the given {0} = {1}</value>
<comment>{0} is a placeholder for property name; {1} is a placeholder for property value.</comment>
</data>
<data name="CouldNotFindPropertyFromGivenClass" xml:space="preserve">
<value>Could not find the following properties from the given class {0}: {1}.</value>
<comment>{0} is a placeholder for class name; {1} is a placeholder for list of property names.</comment>
</data>
<data name="CouldNotModifyReadonlyProperty" xml:space="preserve">
<value>Could not modify readonly property '{0}' of object '{1}'.</value>
<comment>{0} is a placeholder for propertyname; {1} is a placeholder for object string.</comment>
</data>
<data name="DefaultStatusDescription" xml:space="preserve">
<value>Default status description.</value>
<comment>N/A</comment>
</data>
<data name="DidNotResolveFile" xml:space="preserve">
<value>Cannot perform operation because the wildcard path {0} did not resolve to a file.</value>
<comment>{0} is a placeholder for a path</comment>
</data>
<data name="InvalidAuthenticationTypeWithNullCredential" xml:space="preserve">
<value>Authentication type '{0}' is invalid without credential. Only following authentication type are allowed without credential, '{1}', '{2}', '{3}', or '{4}'.</value>
<comment>{0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types.</comment>
</data>
<data name="InvalidMethod" xml:space="preserve">
<value>Can not find method '{0}' in class '{1}'.</value>
<comment>{0} is a placeholder for method name. {1} is a placeholders for class name.</comment>
</data>
<data name="InvalidMethodParameter" xml:space="preserve">
<value>Can not find Parameter '{0}' in method '{1}' of class '{2}'.</value>
<comment>{0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name.</comment>
</data>
<data name="InvalidOperation" xml:space="preserve">
<value>Invalid operation. Current cmdlet already have operation created.</value>
<comment>N/A</comment>
</data>
<data name="InvalidParameterValue" xml:space="preserve">
<value>Argument '{0}' contains characters that are not allowed in parameter '{1}'. Supply an argument that is valid and then try the command again.</value>
<comment>{0} stand for argument value, {1} stand for parameter name.</comment>
</data>
<data name="MultipleFilesNotSupported" xml:space="preserve">
<value>Cannot perform operation because the path resolved to more than one file. This command cannot operate on multiple files.</value>
</data>
<data name="NullArgument" xml:space="preserve">
<value>Argument '{0}' can not be null.</value>
<comment>N/A</comment>
</data>
<data name="OperationInProgress" xml:space="preserve">
<value>CimSession proxy object already have operation in progress.</value>
<comment>N/A</comment>
</data>
<data name="ReadWriteFileNotFileSystemProvider" xml:space="preserve">
<value>Cannot open file because the current provider ({0}) cannot open a file.</value>
<comment>{0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider)</comment>
</data>
<data name="UnableToAddPropertyToInstance" xml:space="preserve">
<value>Unable to add property '{0}' to input object '{1}'. The class schema does not contain the property.</value>
<comment>{0} stand for property name, {1} stand for cim instance path.</comment>
</data>
<data name="UnableToResolvePareameterSetName" xml:space="preserve">
<value>Unable to resolve the parameter set name.</value>
<comment>N/A</comment>
</data>
</root>
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,243 @@
//------------------------------------------------------------------
// <copyright file="CurrentConfigurations.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// <author email="psarda">
// Pankaj Sarda
// </author>
//
// <summary>
// Class that queries the server and gets current configurations.
// Also provides a generic way to update the configurations.
// </summary>
//
// <remarks/>
//------------------------------------------------------------------
namespace Microsoft.WSMan.Management
{
using System;
using System.Globalization;
using System.Xml;
#if CORECLR
using System.Xml.XPath;
#endif
/// <summary>
/// Class that queries the server and gets current configurations.
/// Also provides a generic way to update the configurations.
/// </summary>
internal class CurrentConfigurations
{
/// <summary>
/// Prefix used to add NameSpace of root element to namespace manager.
/// </summary>
public const string DefaultNameSpacePrefix = "defaultNameSpace";
/// <summary>
/// This holds the current configurations XML.
/// </summary>
private XmlDocument rootDocument;
/// <summary>
/// Holds the referance to the current document element.
/// </summary>
private XmlElement documentElement;
/// <summary>
/// Holds the Namespace Manager to use for XPATH queries.
/// </summary>
private XmlNamespaceManager nameSpaceManger;
/// <summary>
/// Session of the WsMan sserver.
/// </summary>
private IWSManSession serverSession;
/// <summary>
/// Gets the server session associated with the configuration.
/// </summary>
public IWSManSession ServerSession
{
get { return serverSession; }
}
/// <summary>
/// Gets the current configuration XML.
/// </summary>
public XmlDocument RootDocument
{
get { return this.rootDocument; }
}
/// <summary>
/// Gets the current configuration on the given server and for given URI.
/// This issues a GET request to the server.
/// </summary>
/// <param name="serverSession">Current server session.</param>
public CurrentConfigurations(IWSManSession serverSession)
{
if (serverSession == null)
{
throw new ArgumentNullException("serverSession");
}
this.rootDocument = new XmlDocument();
this.serverSession = serverSession;
}
/// <summary>
/// Refresh the CurrentConfiguration. This method calls GET operation for the given
/// URI on the server and update the current configuraition. It also intialize some
/// of required class members.
/// </summary>
/// <param name="responseOfGet">Plugin configuration.</param>
/// <returns>False, if operation failed.</returns>
public bool RefreshCurrentConfiguration(string responseOfGet)
{
if (String.IsNullOrEmpty(responseOfGet))
{
throw new ArgumentNullException("responseOfGet");
}
this.rootDocument.LoadXml(responseOfGet);
this.documentElement = this.rootDocument.DocumentElement;
this.nameSpaceManger = new XmlNamespaceManager(this.rootDocument.NameTable);
this.nameSpaceManger.AddNamespace(CurrentConfigurations.DefaultNameSpacePrefix, this.documentElement.NamespaceURI);
return String.IsNullOrEmpty(this.serverSession.Error);
}
/// <summary>
/// Update the server with updated XML.
/// Issues a PUT request with the ResourceUri provided.
/// </summary>
/// <param name="resourceUri">Resource URI to use.</param>
/// <returns>Fales, if operation is not succesful.</returns>
public void PutConfiguraitonOnServer(string resourceUri)
{
if (String.IsNullOrEmpty(resourceUri))
{
throw new ArgumentNullException("resourceUri");
}
this.serverSession.Put(resourceUri, this.rootDocument.InnerXml, 0);
}
/// <summary>
/// This method will remove the configuration from the XML.
/// Currently the method will only remove the attributes. But it is extensible enough to support
/// Node removals in future.
/// </summary>
/// <param name="pathToNodeFromRoot">Path with namespace to the node from Root element. Must not end with '/'.</param>
public void RemoveOneConfiguration(string pathToNodeFromRoot)
{
if (pathToNodeFromRoot == null)
{
throw new ArgumentNullException("pathToNodeFromRoot");
}
XmlNode nodeToRemove =
this.documentElement.SelectSingleNode(
pathToNodeFromRoot,
this.nameSpaceManger);
if (nodeToRemove != null)
{
if (nodeToRemove is XmlAttribute)
{
this.RemoveAttribute(nodeToRemove as XmlAttribute);
}
}
else
{
throw new ArgumentException("Node is not present in the XML, Please give valid XPath", "pathToNodeFromRoot");
}
}
/// <summary>
/// Create or Update the value of the configuration on the given Node. Currently this
/// method is supported for updating attributes, but can be easily updated for nodes.
/// Caller should call this method to add a new attribute to the Node.
/// </summary>
/// <param name="pathToNodeFromRoot">Path with namespace to the node from Root element. Must not end with '/'.</param>
/// <param name="configurationName">Name of the configuration with name space to update or create.</param>
/// <param name="configurationValue">Value of the configurations.</param>
public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurationName, string configurationValue)
{
if (pathToNodeFromRoot == null)
{
throw new ArgumentNullException("pathToNodeFromRoot");
}
if (String.IsNullOrEmpty(configurationName))
{
throw new ArgumentNullException("configurationName");
}
if (configurationValue == null)
{
throw new ArgumentNullException("configurationValue");
}
XmlNode nodeToUpdate =
this.documentElement.SelectSingleNode(
pathToNodeFromRoot,
this.nameSpaceManger);
if (nodeToUpdate != null)
{
foreach (XmlAttribute attribute in nodeToUpdate.Attributes)
{
if (attribute.Name.Equals(configurationName, StringComparison.OrdinalIgnoreCase))
{
attribute.Value = configurationValue;
return;
}
}
XmlNode attr = this.rootDocument.CreateNode(XmlNodeType.Attribute, configurationName, String.Empty);
attr.Value = configurationValue;
nodeToUpdate.Attributes.SetNamedItem(attr);
}
}
/// <summary>
/// Gets the value of the configuration on the given Node or attribute.
/// </summary>
/// <param name="pathFromRoot">Path with namespace to the node from Root element.</param>
/// <returns>Value of the Node, or Null if no node present.</returns>
public string GetOneConfiguration(string pathFromRoot)
{
if (pathFromRoot == null)
{
throw new ArgumentNullException("pathFromRoot");
}
XmlNode requiredNode =
this.documentElement.SelectSingleNode(
pathFromRoot,
this.nameSpaceManger);
if (requiredNode != null)
{
return requiredNode.Value;
}
return null;
}
/// <summary>
/// Removes the attribute from OwnerNode.
/// </summary>
/// <param name="attributeToRemove">Attribute to Remove.</param>
private void RemoveAttribute(XmlAttribute attributeToRemove)
{
XmlElement ownerElement = attributeToRemove.OwnerElement;
ownerElement.RemoveAttribute(attributeToRemove.Name);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,329 @@
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.WSMan.Management
{
/// <summary>
/// Executes action on a target object specified by RESOURCE_URI, where
/// parameters are specified by key value pairs.
/// eg., Call StartService method on the spooler service
/// Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service
/// -SelectorSet {Name=Spooler}
/// </summary>
[Cmdlet(VerbsLifecycle.Invoke, "WSManAction", DefaultParameterSetName = "URI", HelpUri = "http://go.microsoft.com/fwlink/?LinkId=141446")]
public class InvokeWSManActionCommand : AuthenticatingWSManCommand, IDisposable
{
/// <summary>
/// The following is the definition of the input parameter "Action".
/// Indicates the method which needs to be executed on the management object
/// specified by the ResourceURI and selectors
/// </summary>
[Parameter(Mandatory = true,
Position = 1)]
[ValidateNotNullOrEmpty]
public String Action
{
get { return action; }
set { action = value; }
}
private String action;
/// <summary>
/// The following is the definition of the input parameter "ApplicationName".
/// ApplicationName identifies the remote endpoint.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[ValidateNotNullOrEmpty]
public String ApplicationName
{
get { return applicationname; }
set { applicationname = value; }
}
private String applicationname = null;
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Executes the management operation on the specified computer(s). The default
/// is the local computer. Type the fully qualified domain name, NETBIOS name or
/// IP address to indicate the remote host(s)
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[Alias("cn")]
public String ComputerName
{
get { return computername; }
set
{
computername = value;
if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase)))
{
computername = "localhost";
}
}
}
private String computername = null;
/// <summary>
/// The following is the definition of the input parameter "ConnectionURI".
/// Specifies the transport, server, port, and ApplicationName of the new
/// runspace. The format of this string is:
/// transport://server:port/ApplicationName.
/// </summary>
[Parameter(ParameterSetName = "URI")]
[ValidateNotNullOrEmpty]
[Alias("CURI", "CU")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]
public Uri ConnectionURI
{
get { return connectionuri; }
set { connectionuri = value; }
}
private Uri connectionuri;
/// <summary>
/// The following is the definition of the input parameter "FilePath".
/// Updates the management resource specified by the ResourceURI and SelectorSet
/// via this input file
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public String FilePath
{
get { return filepath; }
set { filepath = value; }
}
private String filepath;
/// <summary>
/// The following is the definition of the input parameter "OptionSet".
/// OptionSet is a hashtable and is used to pass a set of switches to the
/// service to modify or refine the nature of the request.
/// </summary>
[Parameter(ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
[Alias("os")]
public Hashtable OptionSet
{
get { return optionset; }
set { optionset = value; }
}
private Hashtable optionset;
/// <summary>
/// The following is the definition of the input parameter "Port".
/// Specifies the port to be used when connecting to the ws management service.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[ValidateNotNullOrEmpty]
[ValidateRange(1, Int32.MaxValue)]
public Int32 Port
{
get { return port; }
set { port = value; }
}
private Int32 port = 0;
/// <summary>
/// The following is the definition of the input parameter "SelectorSet".
/// SelectorSet is a hash table which helps in identify an instance of the
/// management resource if there are are more than 1 instance of the resource
/// class
/// </summary>
[Parameter(Position = 2,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public Hashtable SelectorSet
{
get { return selectorset; }
set { selectorset = value; }
}
private Hashtable selectorset;
/// <summary>
/// The following is the definition of the input parameter "SessionOption".
/// Defines a set of extended options for the WSMan session. This hashtable can
/// be created using New-WSManSessionOption
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
[Alias("so")]
public SessionOption SessionOption
{
get { return sessionoption; }
set { sessionoption = value; }
}
private SessionOption sessionoption;
/// <summary>
/// The following is the definition of the input parameter "UseSSL".
/// Uses the Secure Sockets Layer (SSL) protocol to establish a connnection to
/// the remote computer. If SSL is not available on the port specified by the
/// Port parameter, the command fails.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]
public SwitchParameter UseSSL
{
get { return usessl; }
set { usessl = value; }
}
private SwitchParameter usessl;
/// <summary>
/// The following is the definition of the input parameter "ValueSet".
/// ValueSet is a hahs table which helps to modify resource represented by the
/// ResourceURI and SelectorSet.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public Hashtable ValueSet
{
get { return valueset; }
set { valueset = value; }
}
private Hashtable valueset;
/// <summary>
/// The following is the definition of the input parameter "ResourceURI".
/// URI of the resource class/instance representation
/// </summary>
[Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[Alias("ruri")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]
public Uri ResourceURI
{
get { return resourceuri; }
set { resourceuri = value; }
}
private Uri resourceuri;
private WSManHelper helper;
IWSManEx m_wsmanObject = (IWSManEx)new WSManClass();
IWSManSession m_session = null;
string connectionStr = string.Empty;
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
helper = new WSManHelper(this);
helper.WSManOp = "invoke";
//create the connection string
connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname);
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
try
{
//create the resourcelocator object
IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri);
//create the session object
m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent);
string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, action);
string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session);
string resultXml = m_session.Invoke(action, m_resource, input, 0);
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(resultXml);
WriteObject(xmldoc.DocumentElement);
}
finally
{
if (!String.IsNullOrEmpty(m_wsmanObject.Error))
{
helper.AssertError(m_wsmanObject.Error, true, resourceuri);
}
if (!String.IsNullOrEmpty(m_session.Error))
{
helper.AssertError(m_session.Error, true, resourceuri);
}
if (m_session != null)
Dispose(m_session);
}
}//End ProcessRecord()
#region IDisposable Members
/// <summary>
/// public dispose method
/// </summary>
public
void
Dispose()
{
//CleanUp();
GC.SuppressFinalize(this);
}
/// <summary>
/// public dispose method
/// </summary>
public
void
Dispose(IWSManSession sessionObject)
{
sessionObject = null;
this.Dispose();
}
#endregion IDisposable Members
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void EndProcessing()
{
// WSManHelper helper = new WSManHelper();
helper.CleanUp();
}
}//End Class
}
@@ -0,0 +1,272 @@
//
// Copyright (C) Microsoft. All rights reserved.
//
using System;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
namespace Microsoft.WSMan.Management
{
/// <summary>
/// Creates a WSMan Session option hashtable which can be passed into WSMan
/// cmdlets:
/// Get-WSManInstance
/// Set-WSManInstance
/// Invoke-WSManAction
/// Connect-WSMan
/// </summary>
[Cmdlet(VerbsCommon.New, "WSManSessionOption", HelpUri = "http://go.microsoft.com/fwlink/?LinkId=141449")]
public class NewWSManSessionOptionCommand : PSCmdlet
{
/// <summary>
///
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public ProxyAccessType ProxyAccessType
{
get
{
return _proxyacesstype;
}
set
{
_proxyacesstype = value;
}
}
private ProxyAccessType _proxyacesstype;
/// <summary>
/// The following is the definition of the input parameter "ProxyAuthentication".
/// This parameter takes a set of authentication methods the user can select
/// from. The available options should be as follows:
/// - Negotiate: Use the default authentication (ad defined by the underlying
/// protocol) for establishing a remote connection.
/// - Basic: Use basic authentication for establishing a remote connection
/// - Digest: Use Digest authentication for establishing a remote connection
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public ProxyAuthentication ProxyAuthentication
{
get { return proxyauthentication; }
set
{
proxyauthentication = value;
}
}
private ProxyAuthentication proxyauthentication;
/// <summary>
/// The following is the definition of the input parameter "ProxyCredential".
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[Credential]
public PSCredential ProxyCredential
{
get { return _proxycredential; }
set
{
_proxycredential = value;
}
}
private PSCredential _proxycredential;
/// <summary>
/// The following is the definition of the input parameter "SkipCACheck".
/// When connecting over HTTPS, the client does not validate that the server
/// certificate is signed by a trusted certificate authority (CA). Use only when
/// the remote computer is trusted by other means, for example, if the remote
/// computer is part of a network that is physically secure and isolated or the
/// remote computer is listed as a trusted host in WinRM configuration
/// </summary>
[Parameter]
public SwitchParameter SkipCACheck
{
get { return skipcacheck; }
set
{
skipcacheck = value;
}
}
private bool skipcacheck;
/// <summary>
/// The following is the definition of the input parameter "SkipCNCheck".
/// Indicates that certificate common name (CN) of the server need not match the
/// hostname of the server. Used only in remote operations using https. This
/// option should only be used for trusted machines
/// </summary>
[Parameter]
public SwitchParameter SkipCNCheck
{
get { return skipcncheck; }
set
{
skipcncheck = value;
}
}
private bool skipcncheck;
/// <summary>
/// The following is the definition of the input parameter "SkipRevocation".
/// Indicates that certificate common name (CN) of the server need not match the
/// hostname of the server. Used only in remote operations using https. This
/// option should only be used for trusted machines
/// </summary>
[Parameter]
public SwitchParameter SkipRevocationCheck
{
get { return skiprevocationcheck; }
set
{
skiprevocationcheck = value;
}
}
private bool skiprevocationcheck;
/// <summary>
/// The following is the definition of the input parameter "SPNPort".
/// Appends port number to the connection Service Principal Name SPN of the
/// remote server.
/// SPN is used when authentication mechanism is Kerberos or Negotiate
/// </summary>
[Parameter]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")]
[ValidateRange(0, Int32.MaxValue)]
public Int32 SPNPort
{
get { return spnport; }
set
{
spnport = value;
}
}
private Int32 spnport;
/// <summary>
/// The following is the definition of the input parameter "Timeout".
/// Defines the timeout in ms for the wsman operation
/// </summary>
[Parameter]
[Alias("OperationTimeoutMSec")]
[ValidateRange(0, Int32.MaxValue)]
public Int32 OperationTimeout
{
get { return operationtimeout; }
set
{
operationtimeout = value;
}
}
private Int32 operationtimeout;
/// <summary>
/// The following is the definition of the input parameter "UnEncrypted".
/// Specifies that no encryption will be used when doing remote operations over
/// http. Unencrypted traffix is not allowed by default and must be enabled in
/// the local configuration
/// </summary>
[Parameter]
public SwitchParameter NoEncryption
{
get { return noencryption; }
set
{
noencryption = value;
}
}
private bool noencryption;
/// <summary>
/// The following is the definition of the input parameter "UTF16".
/// Indicates the request is encoded in UTF16 format rather than UTF8 format;
/// UTF8 is the default.
/// </summary>
[Parameter]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")]
public SwitchParameter UseUTF16
{
get { return useutf16; }
set
{
useutf16 = value;
}
}
private bool useutf16;
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
WSManHelper helper = new WSManHelper(this);
if (proxyauthentication.Equals(ProxyAuthentication.Basic) || proxyauthentication.Equals(ProxyAuthentication.Digest))
{
if (_proxycredential == null)
{
InvalidOperationException ex = new InvalidOperationException(helper.GetResourceMsgFromResourcetext("NewWSManSessionOptionCred"));
ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, null);
WriteError(er);
return;
}
}
if ((_proxycredential != null) && (proxyauthentication == 0))
{
InvalidOperationException ex = new InvalidOperationException(helper.GetResourceMsgFromResourcetext("NewWSManSessionOptionAuth"));
ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, null);
WriteError(er);
return;
}
//Creating the Session Object
SessionOption objSessionOption = new SessionOption();
objSessionOption.SPNPort = spnport;
objSessionOption.UseUtf16 = useutf16;
objSessionOption.SkipCNCheck = skipcncheck;
objSessionOption.SkipCACheck = skipcacheck;
objSessionOption.OperationTimeout = operationtimeout;
objSessionOption.SkipRevocationCheck = skiprevocationcheck;
//Proxy Settings
objSessionOption.ProxyAccessType = _proxyacesstype;
objSessionOption.ProxyAuthentication = proxyauthentication;
if (noencryption)
{
objSessionOption.UseEncryption = false;
}
if (_proxycredential != null)
{
NetworkCredential nwCredentials = _proxycredential.GetNetworkCredential();
objSessionOption.ProxyCredential = nwCredentials;
}
WriteObject(objSessionOption);
}//End BeginProcessing()
}//End Class
}
+197
View File
@@ -0,0 +1,197 @@
//
// Copyright (C) Microsoft. All rights reserved.
//
using System;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.WSMan.Management
{
#region Test-WSMAN
/// <summary>
/// Issues an operation against the remote machine to ensure that the wsman
/// service is running
/// </summary>
[Cmdlet(VerbsDiagnostic.Test, "WSMan", HelpUri = "http://go.microsoft.com/fwlink/?LinkId=141464")]
public class TestWSManCommand : AuthenticatingWSManCommand, IDisposable
{
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Executes the management operation on the specified computer. The default is
/// the local computer. Type the fully qualified domain name, NETBIOS name or IP
/// address to indicate the remote host
/// </summary>
[Parameter(Position = 0, ValueFromPipeline = true)]
[Alias("cn")]
public String ComputerName
{
get { return computername; }
set
{
computername = value;
if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase)))
{
computername = "localhost";
}
}
}
private String computername = null;
/// <summary>
/// The following is the definition of the input parameter "Authentication".
/// This parameter takes a set of authentication methods the user can select
/// from. The available method are an enum called AuthenticationMechanism in the
/// System.Management.Automation.Runspaces namespace. The available options
/// should be as follows:
/// - Default : Use the default authentication (ad defined by the underlying
/// protocol) for establishing a remote connection.
/// - Negotiate
/// - Kerberos
/// - Basic: Use basic authentication for establishing a remote connection.
/// -CredSSP: Use CredSSP authentication for establishing a remote connection
/// which will enable the user to perform credential delegation. (i.e. second
/// hop)
/// </summary>
/// <remarks>
/// Overriding to use a different default than the one in AuthenticatingWSManCommand base class
/// </remarks>
[Parameter]
[ValidateNotNullOrEmpty]
[Alias("auth", "am")]
public override AuthenticationMechanism Authentication
{
get { return authentication; }
set
{
authentication = value;
ValidateSpecifiedAuthentication();
}
}
private AuthenticationMechanism authentication = AuthenticationMechanism.None;
/// <summary>
/// The following is the definition of the input parameter "Port".
/// Specifies the port to be used when connecting to the ws management service.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[ValidateNotNullOrEmpty]
[ValidateRange(1, Int32.MaxValue)]
public Int32 Port
{
get { return port; }
set { port = value; }
}
private Int32 port = 0;
/// <summary>
/// The following is the definition of the input parameter "UseSSL".
/// Uses the Secure Sockets Layer (SSL) protocol to establish a connnection to
/// the remote computer. If SSL is not available on the port specified by the
/// Port parameter, the command fails.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]
public SwitchParameter UseSSL
{
get { return usessl; }
set { usessl = value; }
}
private SwitchParameter usessl;
/// <summary>
/// The following is the definition of the input parameter "ApplicationName".
/// ApplicationName identifies the remote endpoint.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[ValidateNotNullOrEmpty]
public String ApplicationName
{
get { return applicationname; }
set { applicationname = value; }
}
private String applicationname = null;
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
WSManHelper helper = new WSManHelper(this);
IWSManEx wsmanObject = (IWSManEx)new WSManClass();
string connectionStr = String.Empty;
connectionStr = helper.CreateConnectionString(null, port, computername, applicationname);
IWSManSession m_SessionObj = null;
try
{
m_SessionObj = helper.CreateSessionObject(wsmanObject, Authentication, null, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent);
m_SessionObj.Timeout = 1000; //1 sec. we are putting this low so that Test-WSMan can return promptly if the server goes unresponsive.
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(m_SessionObj.Identify(0));
WriteObject(xmldoc.DocumentElement);
}
catch(Exception)
{
try
{
if (!String.IsNullOrEmpty(m_SessionObj.Error))
{
XmlDocument ErrorDoc = new XmlDocument();
ErrorDoc.LoadXml(m_SessionObj.Error);
InvalidOperationException ex = new InvalidOperationException(ErrorDoc.OuterXml);
ErrorRecord er = new ErrorRecord(ex, "WsManError", ErrorCategory.InvalidOperation, computername);
this.WriteError(er);
}
}
catch(Exception)
{}
}
finally
{
if (m_SessionObj != null)
Dispose(m_SessionObj);
}
}//End BeginProcessing()
#region IDisposable Members
/// <summary>
/// public dispose method
/// </summary>
public
void
Dispose()
{
//CleanUp();
GC.SuppressFinalize(this);
}
/// <summary>
/// public dispose method
/// </summary>
public
void
Dispose(IWSManSession sessionObject)
{
sessionObject = null;
this.Dispose();
}
#endregion IDisposable Members
}//End Class
#endregion
}
@@ -0,0 +1,293 @@
//
// Copyright (C) Microsoft. All rights reserved.
//
using System;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#if CORECLR
using System.Xml.XPath;
#endif
namespace Microsoft.WSMan.Management
{
#region Set-WsManQuickConfig
//
/// <summary>
/// Performs configuration actions to enable the local machine for remote
/// management. Steps include:
/// 1. Check if WinRM service is running. If not start the WinRM service
/// 2. Set the WinRM service type to auto start
/// 3. Create a listener to accept request on any IP address. By default
/// transport is http
/// 4. Enable firewall exception for WS-Management traffic
/// </summary>
[Cmdlet(VerbsCommon.Set, "WSManQuickConfig", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=141463")]
public class SetWSManQuickConfigCommand : PSCmdlet, IDisposable
{
/// <summary>
/// The following is the definition of the input parameter "UseSSL".
/// Indicates a https listener to be created. If this switch is not specified
/// then by default a http listener will be created
/// </summary>
[Parameter]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]
public SwitchParameter UseSSL
{
get { return usessl; }
set { usessl = value; }
}
private SwitchParameter usessl;
//helper variable
private WSManHelper helper;
/// <summary>
/// Property that sets force parameter. This will allow
/// configuring WinRM without prompting the user.
/// </summary>
[Parameter()]
public SwitchParameter Force
{
get { return force; }
set { force = value; }
}
private bool force = false;
/// <summary>
/// Property that will allow configuring WinRM with Public profile exception enabled.
/// </summary>
[Parameter()]
public SwitchParameter SkipNetworkProfileCheck
{
get { return skipNetworkProfileCheck; }
set { skipNetworkProfileCheck = value; }
}
private bool skipNetworkProfileCheck = false;
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
//If not running elevated, then throw an "elevation required" error message.
WSManHelper.ThrowIfNotAdministrator();
helper = new WSManHelper(this);
String query = helper.GetResourceMsgFromResourcetext("QuickConfigContinueQuery");
String caption = helper.GetResourceMsgFromResourcetext("QuickConfigContinueCaption");
if (!force && !ShouldContinue(query, caption))
{
return;
}
QuickConfigRemoting(true);
QuickConfigRemoting(false);
}//End BeginProcessing()
#region private
private void QuickConfigRemoting(bool serviceonly)
{
IWSManSession m_SessionObj = null;
try
{
string transport;
IWSManEx wsmanObject = (IWSManEx)new WSManClass();
m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null);
string xpathEnabled = string.Empty;
string xpathText = string.Empty;
string xpathUpdate = string.Empty;
string analysisInputXml = string.Empty;
string action = string.Empty;
string xpathStatus = string.Empty;
string xpathResult = string.Empty;
if (!usessl)
{
transport = "http";
}
else
{
transport = "https";
}
if (serviceonly)
{
analysisInputXml = @"<AnalyzeService_INPUT xmlns=""http://schemas.microsoft.com/wbem/wsman/1/config/service""></AnalyzeService_INPUT>";
action = "AnalyzeService";
}
else
{
string openAllProfiles = skipNetworkProfileCheck ? "<Force/>" : String.Empty;
analysisInputXml = @"<Analyze_INPUT xmlns=""http://schemas.microsoft.com/wbem/wsman/1/config/service""><Transport>" + transport + "</Transport>" + openAllProfiles + "</Analyze_INPUT>";
action = "Analyze";
}
string analysisOutputXml = m_SessionObj.Invoke(action, "winrm/config/service", analysisInputXml, 0);
XmlDocument resultopxml = new XmlDocument();
resultopxml.LoadXml(analysisOutputXml);
if (serviceonly)
{
xpathEnabled = "/cfg:AnalyzeService_OUTPUT/cfg:RemotingEnabled";
xpathText = "/cfg:AnalyzeService_OUTPUT/cfg:Results";
xpathUpdate = "/cfg:AnalyzeService_OUTPUT/cfg:EnableService_INPUT";
}
else
{
xpathEnabled = "/cfg:Analyze_OUTPUT/cfg:RemotingEnabled";
xpathText = "/cfg:Analyze_OUTPUT/cfg:Results";
xpathUpdate = "/cfg:Analyze_OUTPUT/cfg:EnableRemoting_INPUT";
}
XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable);
nsmgr.AddNamespace("cfg", "http://schemas.microsoft.com/wbem/wsman/1/config/service");
string enabled = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).InnerText;
XmlNode sourceAttribute = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).Attributes.GetNamedItem("Source");
string source = null;
if (sourceAttribute != null)
{
source = sourceAttribute.Value;
}
string rxml = "";
if (enabled.Equals("true"))
{
string Err_Msg = "";
if (serviceonly)
{
Err_Msg = WSManResourceLoader.GetResourceString("L_QuickConfigNoServiceChangesNeeded_Message");
}
else
{
Err_Msg = WSManResourceLoader.GetResourceString("L_QuickConfigNoChangesNeeded_Message");
}
// ArgumentException e = new ArgumentException(Err_Msg);
// ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null);
// WriteError(er);
WriteObject(Err_Msg);
return;
}
if (!enabled.Equals("false"))
{
ArgumentException e = new ArgumentException(WSManResourceLoader.GetResourceString("L_QuickConfig_InvalidBool_0_ErrorMessage"));
ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null);
WriteError(er);
return;
}
string resultAction = resultopxml.SelectSingleNode(xpathText, nsmgr).InnerText;
if ( source != null && source.Equals("GPO"))
{
String Info_Msg = WSManResourceLoader.GetResourceString("L_QuickConfig_RemotingDisabledbyGP_00_ErrorMessage");
Info_Msg += " " + resultAction;
ArgumentException e = new ArgumentException(Info_Msg);
WriteError(new ErrorRecord(e, "NotSpecified", ErrorCategory.NotSpecified, null));
return;
}
string inputXml = resultopxml.SelectSingleNode(xpathUpdate, nsmgr).OuterXml;
if (resultAction.Equals("") || inputXml.Equals(""))
{
ArgumentException e = new ArgumentException(WSManResourceLoader.GetResourceString("L_ERR_Message") + WSManResourceLoader.GetResourceString("L_QuickConfig_MissingUpdateXml_0_ErrorMessage"));
ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null);
WriteError(er);
return;
}
if (serviceonly)
{
action = "EnableService";
}
else
{
action = "EnableRemoting";
}
rxml = m_SessionObj.Invoke(action, "winrm/config/service", inputXml, 0);
XmlDocument finalxml = new XmlDocument();
finalxml.LoadXml(rxml);
if (serviceonly)
{
xpathStatus = "/cfg:EnableService_OUTPUT/cfg:Status";
xpathResult = "/cfg:EnableService_OUTPUT/cfg:Results";
}
else
{
xpathStatus = "/cfg:EnableRemoting_OUTPUT/cfg:Status";
xpathResult = "/cfg:EnableRemoting_OUTPUT/cfg:Results";
}
if (finalxml.SelectSingleNode(xpathStatus, nsmgr).InnerText.ToString().Equals("succeeded"))
{
if (serviceonly)
{
WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdatedService_Message"));
}
else
{
WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdated_Message"));
}
WriteObject(finalxml.SelectSingleNode(xpathResult, nsmgr).InnerText);
}
else
{
helper.AssertError(WSManResourceLoader.GetResourceString("L_ERR_Message") + WSManResourceLoader.GetResourceString("L_QuickConfigUpdateFailed_ErrorMessage"), false, null);
}
}
finally
{
if (!String.IsNullOrEmpty(m_SessionObj.Error))
{
helper.AssertError(m_SessionObj.Error, true, null);
}
if (m_SessionObj != null)
Dispose(m_SessionObj);
}
}
#endregion private
#region IDisposable Members
/// <summary>
/// public dispose method
/// </summary>
public
void
Dispose()
{
//CleanUp();
GC.SuppressFinalize(this);
}
/// <summary>
/// public dispose method
/// </summary>
public
void
Dispose(IWSManSession sessionObject)
{
sessionObject = null;
this.Dispose();
}
#endregion IDisposable Members
}//End Class
#endregion Set-WsManQuickConfig
}
@@ -0,0 +1,363 @@
//
// Copyright (C) Microsoft. All rights reserved.
//
using System;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation.Runspaces;
using System.Diagnostics.CodeAnalysis;
using Dbg = System.Management.Automation;
namespace Microsoft.WSMan.Management
{
#region Base class for cmdlets taking credential, authentication, certificatethumbprint
/// <summary>
/// Common base class for all WSMan cmdlets that
/// take Authentication, CertificateThumbprint and Credential parameters
/// </summary>
public class AuthenticatingWSManCommand : PSCmdlet
{
/// <summary>
/// The following is the definition of the input parameter "Credential".
/// Specifies a user account that has permission to perform this action. The
/// default is the current user.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[Credential]
[Alias("cred", "c")]
public virtual PSCredential Credential
{
get { return credential; }
set
{
credential = value;
ValidateSpecifiedAuthentication();
}
}
private PSCredential credential;
/// <summary>
/// The following is the definition of the input parameter "Authentication".
/// This parameter takes a set of authentication methods the user can select
/// from. The available method are an enum called Authentication in the
/// System.Management.Automation.Runspaces namespace. The available options
/// should be as follows:
/// - Default : Use the default authentication (ad defined by the underlying
/// protocol) for establishing a remote connection.
/// - Negotiate
/// - Kerberos
/// - Basic: Use basic authentication for establishing a remote connection.
/// -CredSSP: Use CredSSP authentication for establishing a remote connection
/// which will enable the user to perform credential delegation. (i.e. second
/// hop)
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[Alias("auth", "am")]
public virtual AuthenticationMechanism Authentication
{
get { return authentication; }
set
{
authentication = value;
ValidateSpecifiedAuthentication();
}
}
private AuthenticationMechanism authentication = AuthenticationMechanism.Default;
/// <summary>
/// Specifies the certificate thumbprint to be used to impersonate the user on the
/// remote machine.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public virtual string CertificateThumbprint
{
get { return thumbPrint; }
set
{
thumbPrint = value;
ValidateSpecifiedAuthentication();
}
}
private string thumbPrint = null;
internal void ValidateSpecifiedAuthentication()
{
WSManHelper.ValidateSpecifiedAuthentication(
this.Authentication,
this.Credential,
this.CertificateThumbprint);
}
}
#endregion
#region Connect-WsMan
/// <summary>
/// connect wsman cmdlet
/// </summary>
[Cmdlet(VerbsCommunications.Connect, "WSMan", DefaultParameterSetName = "ComputerName", HelpUri = "http://go.microsoft.com/fwlink/?LinkId=141437")]
public class ConnectWSManCommand : AuthenticatingWSManCommand
{
#region Parameters
/// <summary>
/// The following is the definition of the input parameter "ApplicationName".
/// ApplicationName identifies the remote endpoint.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[ValidateNotNullOrEmpty]
public String ApplicationName
{
get { return applicationname; }
set { applicationname = value; }
}
private String applicationname = null;
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Executes the management operation on the specified computer(s). The default
/// is the local computer. Type the fully qualified domain name, NETBIOS name or
/// IP address to indicate the remote host(s)
/// </summary>
[Parameter(ParameterSetName = "ComputerName", Position = 0)]
[Alias("cn")]
public String ComputerName
{
get { return computername; }
set
{
computername = value;
if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase)))
{
computername = "localhost";
}
}
}
private String computername = null;
/// <summary>
/// The following is the definition of the input parameter "ConnectionURI".
/// Specifies the transport, server, port, and ApplicationName of the new
/// runspace. The format of this string is:
/// transport://server:port/ApplicationName.
/// </summary>
[Parameter(ParameterSetName = "URI")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")]
public Uri ConnectionURI
{
get { return connectionuri; }
set { connectionuri = value; }
}
private Uri connectionuri;
/// <summary>
/// The following is the definition of the input parameter "OptionSet".
/// OptionSet is a hash table and is used to pass a set of switches to the
/// service to modify or refine the nature of the request.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[Alias("os")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public Hashtable OptionSet
{
get { return optionset; }
set { optionset = value; }
}
private Hashtable optionset;
/// <summary>
/// The following is the definition of the input parameter "Port".
/// Specifies the port to be used when connecting to the ws management service.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[Parameter(ParameterSetName = "ComputerName")]
[ValidateRange(1, Int32.MaxValue)]
public Int32 Port
{
get { return port; }
set { port = value; }
}
private Int32 port = 0;
/// <summary>
/// The following is the definition of the input parameter "SessionOption".
/// Defines a set of extended options for the WSMan session. This hashtable can
/// be created using New-WSManSessionOption
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[Alias("so")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public SessionOption SessionOption
{
get { return sessionoption; }
set { sessionoption = value; }
}
private SessionOption sessionoption;
/// <summary>
/// The following is the definition of the input parameter "UseSSL".
/// Uses the Secure Sockets Layer (SSL) protocol to establish a connnection to
/// the remote computer. If SSL is not available on the port specified by the
/// Port parameter, the command fails.
/// </summary>
[Parameter(ParameterSetName = "ComputerName")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]
public SwitchParameter UseSSL
{
get { return usessl; }
set { usessl = value; }
}
private SwitchParameter usessl;
#endregion
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
WSManHelper helper = new WSManHelper(this);
if (connectionuri != null)
{
try
{
//always in the format http://server:port/applicationname
string[] constrsplit = connectionuri.OriginalString.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None);
string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None);
computername = constrsplit1[1].Trim();
}
catch (IndexOutOfRangeException)
{
helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri);
}
}
string crtComputerName = computername;
if (crtComputerName == null)
{
crtComputerName = "localhost";
}
if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(this.SessionState.Drive.Current.Name + ":" + WSManStringLiterals.DefaultPathSeparator + crtComputerName, StringComparison.CurrentCultureIgnoreCase))
{
helper.AssertError(helper.GetResourceMsgFromResourcetext("ConnectFailure"), false, computername);
}
helper.CreateWsManConnection(ParameterSetName, connectionuri, port, computername, applicationname, usessl.IsPresent, Authentication, sessionoption, Credential, CertificateThumbprint);
}//End BeginProcessing()
}//end class
#endregion
# region Disconnect-WSMAN
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Executes the management operation on the specified computer(s). The default
/// is the local computer. Type the fully qualified domain name, NETBIOS name or
/// IP address to indicate the remote host(s)
/// </summary>
[Cmdlet(VerbsCommunications.Disconnect, "WSMan", HelpUri = "http://go.microsoft.com/fwlink/?LinkId=141439")]
public class DisconnectWSManCommand : PSCmdlet, IDisposable
{
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Executes the management operation on the specified computer(s). The default
/// is the local computer. Type the fully qualified domain name, NETBIOS name or
/// IP address to indicate the remote host(s)
/// </summary>
[Parameter(Position = 0)]
public String ComputerName
{
get { return computername; }
set
{
computername = value;
if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase)))
{
computername = "localhost";
}
}
}
private String computername = null;
#region IDisposable Members
/// <summary>
/// public dispose method
/// </summary>
public
void
Dispose()
{
//CleanUp();
GC.SuppressFinalize(this);
}
/// <summary>
/// public dispose method
/// </summary>
public
void
Dispose(object session)
{
session = null;
this.Dispose();
}
#endregion IDisposable Members
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
WSManHelper helper = new WSManHelper(this);
if (computername == null)
{
computername = "localhost";
}
if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(WSManStringLiterals.rootpath + ":" + WSManStringLiterals.DefaultPathSeparator + computername, StringComparison.CurrentCultureIgnoreCase))
{
helper.AssertError(helper.GetResourceMsgFromResourcetext("DisconnectFailure"), false, computername);
}
if (computername.Equals("localhost", StringComparison.CurrentCultureIgnoreCase))
{
helper.AssertError(helper.GetResourceMsgFromResourcetext("LocalHost"), false, computername);
}
object _ws = helper.RemoveFromDictionary(computername);
if (_ws != null)
{
Dispose(_ws);
}
else
{
helper.AssertError(helper.GetResourceMsgFromResourcetext("InvalidComputerName"), false, computername);
}
}//End BeginProcessing()
}//End Class
#endregion Disconnect-WSMAN
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,92 @@
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Diagnostics;
using System.Text;
using System.Management;
using System.Management.Automation;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Microsoft.WSMan.Management
{
#region SnapIn
/// <summary>
/// Create the PowerShell snap-in used to register the
/// WsManPSSnapIn cmdlets. Declaring the PSSnapIn class identifies
/// this .cs file as a PowerShell snap-in.
/// </summary>
[RunInstaller(true)]
public class WSManPSSnapIn : PSSnapIn
{
/// <summary>
/// Create an instance of the WsManSnapin class.
/// </summary>
public WSManPSSnapIn()
: base()
{
}
/// <summary>
/// Specify the name of the PowerShell snap-in.
/// </summary>
public override string Name
{
get
{
return "WsManPSSnapIn";
}
}
/// <summary>
/// Specify the vendor for the PowerShell snap-in.
/// </summary>
public override string Vendor
{
get
{
return "Microsoft";
}
}
/// <summary>
/// Specify the localization resource information for the vendor.
/// Use the format: resourceBaseName,VendorName.
/// </summary>
public override string VendorResource
{
get
{
return "WsManPSSnapIn,Microsoft";
}
}
/// <summary>
/// Specify a description of the PowerShell snap-in.
/// </summary>
public override string Description
{
get
{
return "This is a PowerShell snap-in that includes the WsMan cmdlets.";
}
}
/// <summary>
/// Specify the localization resource information for the description.
/// Use the format: resourceBaseName,Description.
/// </summary>
public override string DescriptionResource
{
get
{
return "WsManPSSnapIn,This is a PowerShell snap-in that includes the WsMan cmdlets.";
}
}
}
#endregion SnapIn
}
@@ -0,0 +1,68 @@
# Copyright (c) 2008 Microsoft Corporation
# {0} = Delegate
Vendor=Microsoft
Description=This Windows PowerShell snap-in contains cmdlets (such as Get-WSManInstance and Set-WSManInstance) that are used by the Windows PowerShell host to manage WSMan operations.
InvalidComputerName=The WinRM client cannot complete the operation.Check if the computer name is valid.
InvalidFileName=This command cannot be used because file does not exist.Check the file existence and run your command.
InvalidPath=This command cannot be used because root path does not exist.Check the root path and run your command.
NoResourceMatch=This command cannot be used because the parameter does not match any properties on the ResourceURI.Check the input parameters and run your command.
MultipleResourceMatch=This command cannot be used because the parameter matches multiple properties on the ResourceURI.Check the input parameters and run your command.
NoAttributeMatch=This command cannot be used because the parameter matches a non-text property on the ResourceURI.Check the input parameters and run your command.
WinrmNotConfigured=This command cannot be used because the configuration is corrupted. Run WinRM invoke Restore WinRM/config to restore the default configuration
DelegateFreshCred=The machine is configured to allow delegating fresh credentials to the following target(s):
NoDelegateFreshCred=The machine is not configured to allow delegating fresh credentials.
LocalHost=This command cannot be used to remove the computer 'localhost' because it will always be connected. Give some other connected computer and run your command.
ConnectFailure=This command cannot be used from the current path. Move to root path of the provider using cd\\ and run your command again.
DisconnectFailure=This command cannot be used from the current path. Move to root path of the provider using cd\\ and run your command again.
value=This command cannot be used because Parameter Value is not supplied. Check the value again and run your command.
SetItemNotSupported=This command cannot be used in the current path because this cmdlet is not supported at this level of Provider path.
RemoveItemNotSupported=This command cannot be used in the current path because Remove-Item is not supported at this level of Provider path.
NewItemNotSupported=This command cannot be used in the current path because New-Item is not supported at this level of Provider path.
NoChangeValue=This command cannot set the input value because these values are Primary keys or Container items of the resource object. Change the input value and Run your command.
ConfigStorage=Root of WsMan Config Storage.
NewWSManSessionOptionCred=This command cannot be used without credential because the authentication algorithm is Basic or Digest. Use Credentials parameter to specify value and run your command.
NewWSManSessionOptionAuth=This command cannot be used without Basic or Digest authentication algorithm because credentials are specified.Use Basic or Digest authentication algorithm and run your command.
DriveRootError=This command cannot be used because WsMan drive root is not supported on this version of Windows OS.
ItemDoesNotExist=This command cannot be used because path does not exist.Check the path existence and run your command.
ErrorElevationNeeded=Access is denied. You need to run this cmdlet from an elevated process.
NewDriveRootDoesNotExist=Unable to create a drive with the specified root. The root path does not exist.
NotProperURI=This command cannot be executed because the Connection URI is not in correct format. Please check the connection uri and Run your command again.
WSManServiceStartCaption=Start WinRM Service
WSManServiceStartQuery=WinRM service is not started currently. Running this command will start the WinRM service.\n\nDo you want to continue?
WinRMServiceError=This command cannot be executed because the WinRM Service is not started.
SetItemShouldContinueCaption=Set the value of the item
SetItemShouldContinueQuery=This command set the value of the Item.\n\nDo you want to continue?
EnableCredSSPPolicyValidateError=This command cannot be executed because the setting cannot be enabled.
DisableCredSSPPolicyValidateError=This command cannot be executed because the setting cannot be disabled.
TrustedHostValueTypeError=Cannot convert 'System.Object[]' to the type 'System.String' required by the parameter. Specified method is not supported.
ShouldContinueSecurityCaption=Security Configuration for WinRM Plug-in.
ShouldContinueSecurityQuery=This command modifies the security settings on a resource in the following WinRM plug-in: {0}.\nDo you want to continue?
NewItemShouldContinueListenerCaption=Creates a new Listener item.
NewItemShouldContinueListenerQuery=This command creates a new Listener item.\n\nDo you want to continue?
NewItemShouldContinueClientCertCaption=Creates a new ClientCertificate item.
NewItemShouldContinueClientCertQuery=This command creates a new ClientCertificate item.\n\nDo you want to continue?
SetItemTrustedHostsWarningQuery=This command modifies the TrustedHosts list for the WinRM client. The computers in the TrustedHosts list might not be authenticated. The client might send credential information to these computers. Are you sure that you want to modify this list?
SetItemRootSDDLWarningQuery=This command modifies the RootSDDL setting for the WinRM service. The RootSDDL stores the default security settings for any WinRM securable resource that does not specify its own SDDL. Changing the SDDL might affect security for many WinRM resources. Are you sure that you want to modify these default settings?
SetItemGeneralSecurityCaption=WinRM Security Configuration.
ResourceURIMissingInResourceDir=Unable to find value for "{0}" element in the path {1}.
CredSSPContinueCaption=CredSSP Authentication Configuration for WS-Management
CredSSPContinueQuery=CredSSP authentication allows the user credentials on this computer to be sent to a remote computer. If you use CredSSP authentication for a connection to a malicious or compromised computer, that computer will have access to your user name and password. For more information, see the Enable-WSManCredSSP Help topic.\nDo you want to enable CredSSP authentication?
CredSSPServerContinueQuery=CredSSP authentication allows the server to accept user credentials from a remote computer. If you enable CredSSP authentication on the server, the server will have access to the user name and password of the client computer if the client computer sends them. For more information, see the Enable-WSManCredSSP Help topic. \nDo you want to enable CredSSP authentication?
CredSSPRoleAndDelegateCannotBeSpecified=The {0} parameter cannot be used when the {1} parameter value is {2}. The {0} parameter can be used only when the {1} parameter value is {3}.
CredSSPClientAndDelegateMustBeSpecified=The {0} parameter is mandatory when the {1} parameter value is {2}.
CredSSPServiceConfigured=This computer is configured to receive credentials from a remote client computer.
CredSSPServiceNotConfigured=This computer is not configured to receive credentials from a remote client computer.
QuickConfigContinueCaption=WinRM Quick Configuration
QuickConfigContinueQuery=Running the Set-WSManQuickConfig command has significant security implications, as it enables remote management through the WinRM service on this computer.\nThis command:\n 1. Checks whether the WinRM service is running. If the WinRM service is not running, the service is started.\n 2. Sets the WinRM service startup type to automatic.\n 3. Creates a listener to accept requests on any IP address. By default, the transport is HTTP.\n 4. Enables a firewall exception for WS-Management traffic.\n 5. Enables Kerberos and Negotiate service authentication.\nDo you want to enable remote management through the WinRM service on this computer?
AmbiguosAuthentication=A {0} cannot be specified when {1} is specified.
CmdletNotAvailable=This PowerShell cmdlet is not available on for Windows XP and Windows Server 2003.
InvalidValueType=This command cannot be used because the parameter value type is invalid. {0} configuration expects a value of Type {1}. Verify that the value is correct and try again.
ClearItemOnRunAsPassword=The RunAsPassword value cannot be removed. Remove the values for RunAsUser and RunAsPassword in PowerShell by calling the Clear-Item cmdlet with the value for -Path attribute equal to the value of RunAsUser.
SetItemOnRunAsPasswordNoRunAsUser=The value for RunAsPassword cannot be set without a value set for RunAsUser. Set the value for both RunAsUser and RunAsPassword in Powershell by calling the Set-Item cmdlet with the value for -Path attribute equal to the value of RunAsUser.
SetItemWhatIfAndConfirmText= "Set-Item" on the WinRM configuration setting "{0}" to update the value to "{1}"
SetItemWarnigForPPQ=The updated configuration is effective only if it is less than or equal to the value of global quota {0}. Verify the value for the global quota using the PowerShell cmdlet "Get-Item {0}".
SetItemWarningForGlobalQuota=The updated configuration might affect the operation of the plugins having a per plugin quota value greater than {0}. Verify the configuration of all the registered plugins and change the per plugin quota values for the affected plugins.
SetItemServiceRestartWarning= The configuration changes you made will only be effective after the WinRM service is restarted. To restart the WinRM service, run the following command: 'Restart-Service winrm'
SetItemServiceRestartWarningRemote= The configuration changes you made will only be effective after the WinRM service is restarted on {0}.
@@ -0,0 +1,213 @@
//
// Copyright (C) Microsoft. All rights reserved.
//
using System;
using System.IO;
using System.Xml;
using System.Net;
using System.Resources;
using System.Reflection;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
[assembly: CLSCompliant(true)]
namespace Microsoft.WSMan.Management
{
/// <summary>
/// Session option class
/// </summary>
public sealed class SessionOption
{
/// <summary>
/// property
/// </summary>
public bool SkipCACheck
{
get { return _SkipCACheck; }
set
{
_SkipCACheck = value;
}
}
private bool _SkipCACheck;
/// <summary>
/// property
/// </summary>
public bool SkipCNCheck
{
get { return _SkipCNCheck; }
set
{
_SkipCNCheck = value;
}
}
private bool _SkipCNCheck;
/// <summary>
/// property
/// </summary>
///
public bool SkipRevocationCheck
{
get { return _SkipRevocationCheck; }
set
{
_SkipRevocationCheck = value;
}
}
private bool _SkipRevocationCheck;
/// <summary>
/// property
/// </summary>
public bool UseEncryption
{
get { return _useencryption; }
set
{
_useencryption = value;
}
}
private bool _useencryption = true;
/// <summary>
/// property
/// </summary>
public bool UseUtf16
{
get { return _UTF16; }
set
{
_UTF16 = value;
}
}
private bool _UTF16;
/// <summary>
/// property
/// </summary>
public ProxyAuthentication ProxyAuthentication
{
get { return _ProxyAuthentication; }
set
{
_ProxyAuthentication = value;
}
}
private ProxyAuthentication _ProxyAuthentication;
/// <summary>
/// property
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")]
public int SPNPort
{
get { return _SPNPort; }
set
{
_SPNPort = value;
}
}
private int _SPNPort;
/// <summary>
/// property
/// </summary>
public int OperationTimeout
{
get { return _OperationTimeout; }
set
{
_OperationTimeout = value;
}
}
private int _OperationTimeout;
/// <summary>
/// property
/// </summary>
public NetworkCredential ProxyCredential
{
get { return _ProxyCredential; }
set
{
_ProxyCredential = value;
}
}
private NetworkCredential _ProxyCredential;
/// <summary>
/// property
/// </summary>
public ProxyAccessType ProxyAccessType
{
get { return _proxyaccesstype; }
set
{
_proxyaccesstype = value;
}
}
private ProxyAccessType _proxyaccesstype;
}
/// <summary>
/// property
/// </summary>
public enum ProxyAccessType
{
/// <summary>
/// property
/// </summary>
ProxyIEConfig = 0,
/// <summary>
/// property
/// </summary>
ProxyWinHttpConfig = 1,
/// <summary>
/// property
/// </summary>
ProxyAutoDetect = 2,
/// <summary>
/// property
/// </summary>
ProxyNoProxyServer = 3
}
/// <summary>
/// property
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")]
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")]
public enum ProxyAuthentication
{
/// <summary>
/// property
/// </summary>
Negotiate = 1,
/// <summary>
/// property
/// </summary>
Basic = 2,
/// <summary>
/// property
/// </summary>
Digest = 4
}
}