private static void WarnAboutUnsupportedActionPreferences( Cmdlet cmdlet, ActionPreference effectiveActionPreference, string nameOfCommandLineParameter, Func<string> inquireMessageGetter, Func<string> stopMessageGetter) { string message; switch (effectiveActionPreference) { case ActionPreference.Stop: message = stopMessageGetter(); break; case ActionPreference.Inquire: message = inquireMessageGetter(); break; default: return; // we can handle everything that is not Stop or Inquire } bool actionPreferenceComesFromCommandLineParameter = cmdlet.MyInvocation.BoundParameters.ContainsKey(nameOfCommandLineParameter); if (actionPreferenceComesFromCommandLineParameter) { Exception exception = new ArgumentException(message); ErrorRecord errorRecord = new ErrorRecord(exception, "ActionPreferenceNotSupportedByCimCmdletAdapter", ErrorCategory.NotImplemented, null); cmdlet.ThrowTerminatingError(errorRecord); } }
internal CmdletParameterBinderController(Cmdlet cmdlet, CommandMetadata commandMetadata, ParameterBinderBase parameterBinder) : base(cmdlet.MyInvocation, cmdlet.Context, parameterBinder) { this._warningSet = new HashSet<string>(); this._useDefaultParameterBinding = true; this._delayBindScriptBlocks = new Dictionary<MergedCompiledCommandParameter, DelayedScriptBlockArgument>(); this._defaultParameterValues = new Dictionary<string, CommandParameterInternal>(StringComparer.OrdinalIgnoreCase); if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException("commandMetadata"); } this.Command = cmdlet; this._commandRuntime = (MshCommandRuntime)cmdlet.CommandRuntime; this._commandMetadata = commandMetadata; if (commandMetadata.ImplementsDynamicParameters) { base.UnboundParameters = base.BindableParameters.ReplaceMetadata(commandMetadata.StaticCommandParameterMetadata); base.BindableParameters.GenerateParameterSetMappingFromMetadata(commandMetadata.DefaultParameterSetName); } else { base._bindableParameters = commandMetadata.StaticCommandParameterMetadata; base.UnboundParameters = new List<MergedCompiledCommandParameter>(base._bindableParameters.BindableParameters.Values); } }
public void Write(Cmdlet cmd, string response) { foreach (var writer in Writers) { writer.Write(cmd, response); } }
internal CmdletProviderContext(CmdletProviderContext contextToCopyFrom) { this.credentials = PSCredential.Empty; this._origin = CommandOrigin.Internal; this.accumulatedObjects = new Collection<PSObject>(); this.accumulatedErrorObjects = new Collection<ErrorRecord>(); this.stopReferrals = new Collection<CmdletProviderContext>(); if (contextToCopyFrom == null) { throw PSTraceSource.NewArgumentNullException("contextToCopyFrom"); } this.executionContext = contextToCopyFrom.ExecutionContext; this.command = contextToCopyFrom.command; if (contextToCopyFrom.Credential != null) { this.credentials = contextToCopyFrom.Credential; } this.drive = contextToCopyFrom.Drive; this.force = (bool) contextToCopyFrom.Force; this.CopyFilters(contextToCopyFrom); this.suppressWildcardExpansion = contextToCopyFrom.SuppressWildcardExpansion; this.dynamicParameters = contextToCopyFrom.DynamicParameters; this._origin = contextToCopyFrom._origin; this.stopping = contextToCopyFrom.Stopping; contextToCopyFrom.StopReferrals.Add(this); this.copiedContext = contextToCopyFrom; }
/// <summary> /// Process the exception that was thrown and write the error details. /// </summary> /// <param name="cmdlet">The cmdlet for which to write the error output.</param> /// <param name="clientRequestId">The unique id for this request.</param> /// <param name="exception">The exception that was thrown.</param> public static void WriteErrorDetails( Cmdlet cmdlet, string clientRequestId, Exception exception) { string requestId; ErrorRecord errorRecord = RetrieveExceptionDetails(exception, out requestId); // Write the request Id as a warning if (requestId != null) { // requestId was availiable from the server response, write that as warning to the // console. cmdlet.WriteWarning(string.Format( CultureInfo.InvariantCulture, Resources.ExceptionRequestId, requestId)); } else { // requestId was not availiable from the server response, write the client Ids that // was sent. cmdlet.WriteWarning(string.Format( CultureInfo.InvariantCulture, Resources.ExceptionClientSessionId, SqlDatabaseCmdletBase.clientSessionId)); cmdlet.WriteWarning(string.Format( CultureInfo.InvariantCulture, Resources.ExceptionClientRequestId, clientRequestId)); } // Write the actual errorRecord containing the exception details cmdlet.WriteError(errorRecord); }
private string BuildMessage(Cmdlet cmdlet, string baseName, string resourceId, params object[] args) { if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } if (string.IsNullOrEmpty(baseName)) { throw PSTraceSource.NewArgumentNullException("baseName"); } if (string.IsNullOrEmpty(resourceId)) { throw PSTraceSource.NewArgumentNullException("resourceId"); } string template = ""; try { template = cmdlet.GetResourceString(baseName, resourceId); } catch (MissingManifestResourceException exception) { this._textLookupError = exception; return ""; } catch (ArgumentException exception2) { this._textLookupError = exception2; return ""; } return this.BuildMessage(template, baseName, resourceId, args); }
public void Write(Cmdlet cmd, string response) { var doc = new XmlDocument(); doc.LoadXml(response); cmd.WriteObject(doc.DocumentElement); }
/// <summary> /// Constructs the parameter binder with the specified type metadata. The binder is only valid /// for a single instance of a bindable object and only for the duration of a command. /// </summary> /// /// <param name="target"> /// The target object that the parameter values will be bound to. /// </param> /// /// <param name="command"> /// An instance of the command so that attributes can access the context. /// </param> /// /// <param name="commandLineParameters"> /// The dictionary to use to record the parameters set by this object... /// </param> /// internal ReflectionParameterBinder( object target, Cmdlet command, CommandLineParameters commandLineParameters) : base(target, command.MyInvocation, command.Context, command) { this.CommandLineParameters = commandLineParameters; }
/// <summary> /// Internal Constructor /// </summary> /// <param name="childJob">Job associated with this operation</param> /// <param name="wmiObject">object associated with this operation</param> /// <param name="computerName"> computer on which the operation is invoked </param> /// <param name="results"> sink to get wmi objects </param> internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string computerName, ManagementOperationObserver results) { _wmiObject = wmiObject; _computerName = computerName; _results = results; this.State = WmiState.NotStarted; _job = childJob; }
internal static Encoding Convert(Cmdlet cmdlet, string encoding) { if (string.IsNullOrEmpty(encoding) || (string.Equals(encoding, "unknown", StringComparison.OrdinalIgnoreCase) || string.Equals(encoding, "string", StringComparison.OrdinalIgnoreCase)) || string.Equals(encoding, "unicode", StringComparison.OrdinalIgnoreCase)) { return Encoding.Unicode; } if (string.Equals(encoding, "bigendianunicode", StringComparison.OrdinalIgnoreCase)) { return Encoding.BigEndianUnicode; } if (string.Equals(encoding, "ascii", StringComparison.OrdinalIgnoreCase)) { return Encoding.ASCII; } if (string.Equals(encoding, "utf8", StringComparison.OrdinalIgnoreCase)) { return Encoding.UTF8; } if (string.Equals(encoding, "utf7", StringComparison.OrdinalIgnoreCase)) { return Encoding.UTF7; } if (string.Equals(encoding, "utf32", StringComparison.OrdinalIgnoreCase)) { return Encoding.UTF32; } if (string.Equals(encoding, "default", StringComparison.OrdinalIgnoreCase)) { return Encoding.Default; } if (string.Equals(encoding, "oem", StringComparison.OrdinalIgnoreCase)) { return Encoding.GetEncoding((int) NativeMethods.GetOEMCP()); } var str = string.Join( ", ", "unknown", "string", "unicode", "bigendianunicode", "ascii", "utf8", "utf7", "utf32", "default", "oem"); var message = StringUtil.Format(PathUtilStrings.OutFile_WriteToFileEncodingUnknown, encoding, str); cmdlet.ThrowTerminatingError( new ErrorRecord( ExceptionUtils.NewArgumentException("Encoding"), "WriteToFileEncodingUnknown", ErrorCategory.InvalidArgument, null) {ErrorDetails = new ErrorDetails(message)}); return null; }
internal ChildItemCmdletProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } this.cmdlet = cmdlet; this.sessionState = cmdlet.Context.EngineSessionState; }
public CmdletLogger(Cmdlet cmdlet) { _cmdlet = cmdlet; _name = (from attr in _cmdlet.GetType().GetCustomAttributes(true) let cmdletattr = attr as CmdletAttribute where null != cmdletattr select cmdletattr.NounName + "-" + cmdletattr.VerbName).FirstOrDefault() ?? "Unknown Cmdlet"; }
} // CmdletProviderIntrinsics private /// <summary> /// Constructs a facade over the "real" session state API /// </summary> /// /// <param name="cmdlet"> /// An instance of the cmdlet. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="cmdlet"/> is null. /// </exception> /// internal ContentCmdletProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } _cmdlet = cmdlet; _sessionState = cmdlet.Context.EngineSessionState; } // ContentCmdletProviderIntrinsics internal
/// <summary> /// First phase of cmdlet lifecycle: "Binding Parameters that Take Command-Line Input" /// </summary> public override void Prepare() { Cmdlet cmdlet = (Cmdlet)Activator.CreateInstance(_cmdletInfo.ImplementingType); cmdlet.CommandInfo = _cmdletInfo; cmdlet.ExecutionContext = base.ExecutionContext; cmdlet.CommandRuntime = CommandRuntime; Command = cmdlet; MergeParameters(); _argumentBinder = new CmdletParameterBinder(_cmdletInfo, Command); _argumentBinder.BindCommandLineParameters(Parameters); }
internal static Encoding Convert(Cmdlet cmdlet, string encoding) { if ((encoding == null) || (encoding.Length == 0)) { return Encoding.Unicode; } if (string.Equals(encoding, "unknown", StringComparison.OrdinalIgnoreCase)) { return Encoding.Unicode; } if (string.Equals(encoding, "string", StringComparison.OrdinalIgnoreCase)) { return Encoding.Unicode; } if (string.Equals(encoding, "unicode", StringComparison.OrdinalIgnoreCase)) { return Encoding.Unicode; } if (string.Equals(encoding, "bigendianunicode", StringComparison.OrdinalIgnoreCase)) { return Encoding.BigEndianUnicode; } if (string.Equals(encoding, "ascii", StringComparison.OrdinalIgnoreCase)) { return Encoding.ASCII; } if (string.Equals(encoding, "utf8", StringComparison.OrdinalIgnoreCase)) { return Encoding.UTF8; } if (string.Equals(encoding, "utf7", StringComparison.OrdinalIgnoreCase)) { return Encoding.UTF7; } if (string.Equals(encoding, "utf32", StringComparison.OrdinalIgnoreCase)) { return Encoding.UTF32; } if (string.Equals(encoding, "default", StringComparison.OrdinalIgnoreCase)) { return Encoding.Default; } if (string.Equals(encoding, "oem", StringComparison.OrdinalIgnoreCase)) { return Encoding.GetEncoding((int) NativeMethods.GetOEMCP()); } string str = string.Join(", ", new string[] { "unknown", "string", "unicode", "bigendianunicode", "ascii", "utf8", "utf7", "utf32", "default", "oem" }); string message = StringUtil.Format(PathUtilsStrings.OutFile_WriteToFileEncodingUnknown, encoding, str); ErrorRecord errorRecord = new ErrorRecord(PSTraceSource.NewArgumentException("Encoding"), "WriteToFileEncodingUnknown", ErrorCategory.InvalidArgument, null) { ErrorDetails = new ErrorDetails(message) }; cmdlet.ThrowTerminatingError(errorRecord); return null; }
public IScriptCSSession GetOrCreate( string name, Cmdlet cmdlet ) { var session = Get(name); if (null == session) { session = ScriptCSSession.Create(cmdlet); _map.Add( name, session ); } return session; }
internal void AddChildJobAndPotentiallyBlock(Cmdlet cmdlet, StartableJob childJob, ChildJobFlags flags) { using (CancellationTokenSource source = new CancellationTokenSource()) { if (childJob == null) { throw new ArgumentNullException("childJob"); } this.AddChildJobWithoutBlocking(childJob, flags, new Action(source.Cancel)); this.ForwardAllResultsToCmdlet(cmdlet, new CancellationToken?(source.Token)); } }
public CmdletParameterBinder(CmdletInfo cmdletInfo, Cmdlet cmdlet) { _cmdletInfo = cmdletInfo; _cmdlet = cmdlet; _defaultValues = new Dictionary<MemberInfo, object>(); _boundParameters = new Collection<MemberInfo>(); _candidateParameterSets = new Collection<CommandParameterSetInfo>(); _commandLineValuesBackup = new Dictionary<MemberInfo, object>(); _activeSet = null; _defaultSet = null; _hasDefaultSet = true; }
internal ProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } this.cmdlet = cmdlet; this.item = new ItemCmdletProviderIntrinsics(cmdlet); this.childItem = new ChildItemCmdletProviderIntrinsics(cmdlet); this.content = new ContentCmdletProviderIntrinsics(cmdlet); this.property = new PropertyCmdletProviderIntrinsics(cmdlet); this.securityDescriptor = new SecurityDescriptorCmdletProviderIntrinsics(cmdlet); }
public ProviderRuntime(ProviderRuntime runtime) : this(runtime.SessionState, runtime.Force, runtime.AvoidGlobbing) { _cmdlet = runtime._cmdlet; PassThru = runtime.PassThru; PSDriveInfo = runtime.PSDriveInfo; Include = new Collection<string>(runtime.Include); Exclude = new Collection<string>(runtime.Exclude); Filter = runtime.Filter; AvoidGlobbing = runtime.AvoidGlobbing; IgnoreFiltersForGlobbing = runtime.IgnoreFiltersForGlobbing; Credential = new PSCredential(runtime.Credential); DynamicParameters = runtime.DynamicParameters; }
internal ProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { throw new NullReferenceException("Cmdlet can't be null."); } _cmdlet = cmdlet; ChildItem = new ChildItemCmdletProviderIntrinsics(_cmdlet); Content = new ContentCmdletProviderIntrinsics(_cmdlet); Item = new ItemCmdletProviderIntrinsics(_cmdlet); Property = new PropertyCmdletProviderIntrinsics(_cmdlet); SecurityDescriptor = new SecurityDescriptorCmdletProviderIntrinsics(_cmdlet); }
public CmdletParameterBinder(CmdletInfo cmdletInfo, Cmdlet cmdlet) { _cmdletInfo = cmdletInfo; _cmdlet = cmdlet; _defaultValues = new Dictionary<MemberInfo, object>(); _boundParameters = new Collection<MemberInfo>(); _candidateParameterSets = _cmdletInfo.ParameterSets.ToList(); _commandLineValuesBackup = new Dictionary<MemberInfo, object>(); _activeSet = null; _defaultSet = null; _hasDefaultSet = true; _commonParameters = (from parameter in CommonCmdletParameters.CommonParameterSetInfo.Parameters select parameter.MemberInfo).ToList(); _engineIntrinsics = new EngineIntrinsics(_cmdlet.ExecutionContext); }
internal PSWmiJob(Cmdlet cmds, string[] computerName, int throttleLimit, string command, int count) : base(command, null) { this.throttleManager = new ThrottleManager(); this.syncObject = new object(); base.PSJobTypeName = "WmiJob"; this.throttleManager.ThrottleLimit = throttleLimit; for (int i = 0; i < (int)computerName.Length; i++) { PSWmiChildJob pSWmiChildJob = new PSWmiChildJob(cmds, computerName[i], this.throttleManager, count); pSWmiChildJob.StateChanged += new EventHandler<JobStateEventArgs>(this.HandleChildJobStateChanged); pSWmiChildJob.JobUnblocked += new EventHandler(this.HandleJobUnblocked); base.ChildJobs.Add(pSWmiChildJob); } this.CommonInit(throttleLimit); }
public CmdletParameterBinder(CmdletInfo cmdletInfo, Cmdlet cmdlet) { _cmdletInfo = cmdletInfo; _cmdlet = cmdlet; _defaultValues = new Dictionary<MemberInfo, object>(); _boundParameters = new Collection<MemberInfo>(); _candidateParameterSets = _cmdletInfo.ParameterSets.ToList(); _commandLineValuesBackup = new Dictionary<MemberInfo, object>(); _activeSet = null; _defaultSet = null; _hasDefaultSet = true; _bindDestinationLookup = new Dictionary<MemberInfo, object>(); _engineIntrinsics = new EngineIntrinsics(_cmdlet.ExecutionContext); // make sure common parameters are set in the CommonParameter member object, not the cmdlet itself AddBindDestionations(CommonCmdletParameters.ParameterDiscovery, _cmdlet.CommonParameters); }
/// <summary> /// Output a message in the appropriate way in a powershell command /// </summary> /// <param name="caller">the Cmdlet object running</param> /// <param name="e">the event containing the message</param> public static void Handle(Cmdlet caller, MessageEventArgs e) { switch (e.MessageType) { case MessageType.Verbose: caller.WriteVerbose(e.Message); break; case MessageType.Progress: caller.WriteProgress(new ProgressRecord(0, e.Activity, e.Message)); break; case MessageType.Error: ToolsHelper.WriteException(caller, e.Exception); caller.ThrowTerminatingError(new ErrorRecord(e.Exception, "0", ErrorCategory.InvalidOperation, caller)); break; case MessageType.Output: caller.WriteObject(e.Message); break; } }
public static ScriptCSSession Create(Cmdlet cmdlet) { ScriptCSSession session = null; var logger = new CurrentLogger(); using (logger.CreateActiveLoggerSession(new CmdletLogger(cmdlet))) { IScriptHostFactory factory = new ScriptHostFactory(); var engine = new RoslynScriptEngine(factory, logger); engine.BaseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var currentCmdletScriptPack = new CurrentCmdletScriptPack(); var scriptPackSession = new ScriptPackSession(new IScriptPack[] { currentCmdletScriptPack }); scriptPackSession.InitializePacks(); session = new ScriptCSSession( engine, scriptPackSession, currentCmdletScriptPack, logger ); } return session; }
internal CmdletProviderContext(Cmdlet command) { this.credentials = PSCredential.Empty; this._origin = CommandOrigin.Internal; this.accumulatedObjects = new Collection<PSObject>(); this.accumulatedErrorObjects = new Collection<ErrorRecord>(); this.stopReferrals = new Collection<CmdletProviderContext>(); if (command == null) { throw PSTraceSource.NewArgumentNullException("command"); } this.command = command; this._origin = command.CommandOrigin; if (command.Context == null) { throw PSTraceSource.NewArgumentException("command.Context"); } this.executionContext = command.Context; this.streamObjects = true; this.streamErrors = true; }
internal static void CheckForSevereException(Cmdlet cmdlet, Exception e) { if (e as AccessViolationException != null || e as StackOverflowException != null) { try { if (!CommandsCommon.alreadyFailing) { CommandsCommon.alreadyFailing = true; MshLog.LogCommandHealthEvent(cmdlet.Context, e, Severity.Critical); } } finally { if (!CommandsCommon.designForTestability_SkipFailFast) { WindowsErrorReporting.FailFast(e); } } } }
/// <summary> /// Initializes the cmdlet parameter binder controller for /// the specified cmdlet and engine context /// </summary> /// /// <param name="cmdlet"> /// The cmdlet that the parameters will be bound to. /// </param> /// /// <param name="commandMetadata"> /// The metadata about the cmdlet. /// </param> /// /// <param name="parameterBinder"> /// The default parameter binder to use. /// </param> /// internal CmdletParameterBinderController( Cmdlet cmdlet, CommandMetadata commandMetadata, ParameterBinderBase parameterBinder) : base( cmdlet.MyInvocation, cmdlet.Context, parameterBinder) { if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException("commandMetadata"); } this.Command = cmdlet; _commandRuntime = (MshCommandRuntime)cmdlet.CommandRuntime; _commandMetadata = commandMetadata; // Add the static parameter metadata to the bindable parameters // And add them to the unbound parameters list if (commandMetadata.ImplementsDynamicParameters) { // ReplaceMetadata makes a copy for us, so we can use that collection as is. this.UnboundParameters = this.BindableParameters.ReplaceMetadata(commandMetadata.StaticCommandParameterMetadata); } else { _bindableParameters = commandMetadata.StaticCommandParameterMetadata; // Must make a copy of the list because we'll modify it. this.UnboundParameters = new List<MergedCompiledCommandParameter>(_bindableParameters.BindableParameters.Values); } }
} // ProviderIntrinsics private /// <summary> /// Constructs a facade over the "real" session state API /// </summary> /// /// <param name="cmdlet"> /// An instance of the cmdlet. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="cmdlet"/> is null. /// </exception> /// internal ProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } _cmdlet = cmdlet; Item = new ItemCmdletProviderIntrinsics(cmdlet); ChildItem = new ChildItemCmdletProviderIntrinsics(cmdlet); Content = new ContentCmdletProviderIntrinsics(cmdlet); Property = new PropertyCmdletProviderIntrinsics(cmdlet); #if SUPPORTS_IMULTIVALUEPROPERTYCMDLETPROVIDER this.propertyValue = new PropertyValueCmdletProviderIntrinsics(cmdlet); #endif SecurityDescriptor = new SecurityDescriptorCmdletProviderIntrinsics(cmdlet); #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release this.relationship = new RelationshipProviderIntrinsics(cmdlet.Context.EngineSessionState); #endif } // ProviderIntrinsics internal