private static Expression GetPropertyOrFieldExpr(Type type, string name, Expression target) { const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy; try { var propertyInfo = type.GetProperty(name, bindingFlags); if (propertyInfo != null) { return(Expression.Property(target, propertyInfo)); } } catch (AmbiguousMatchException) { // This is uncommon - in C#, there is "new" property that hides a base property. // To get the correct property, get all properties, and assume the first that matches // the name we want is the correct one. This seems fragile, but the DotNetAdapter // does the same thing foreach (var propertyInfo in type.GetProperties(bindingFlags)) { if (propertyInfo.Name.Equals(name, StringComparison.Ordinal)) { return(Expression.Property(target, propertyInfo)); } } } try { var fieldInfo = type.GetField(name, bindingFlags); if (fieldInfo != null) { return(Expression.Field(target, fieldInfo)); } } catch (AmbiguousMatchException) { foreach (var fieldInfo in type.GetFields(bindingFlags)) { if (fieldInfo.Name.Equals(name, StringComparison.Ordinal)) { return(Expression.Field(target, fieldInfo)); } } } Diagnostics.Assert(false, "Can't find property or field?"); throw PSTraceSource.NewInvalidOperationException(); }
public void ApplyTo(object collectionToUpdate) { if (collectionToUpdate == null) { throw new ArgumentNullException("collectionToUpdate"); } collectionToUpdate = PSObject.Base(collectionToUpdate); IList list = collectionToUpdate as IList; if (list == null) { throw PSTraceSource.NewInvalidOperationException("PSListModifierStrings", "UpdateFailed", new object[0]); } this.ApplyTo(list); }
/// <summary> /// Retrieves a resource string based on a resource reference stored in the specified /// registry key. /// </summary> /// /// <param name="key"> /// The key in which there is a value that contains the reference to the resource /// to retrieve. /// </param> /// /// <param name="valueName"> /// The name of the value in the registry key that contains the reference to the resource. /// </param> /// /// <param name="assemblyName"> /// The full name of the assembly from which to load the resource. /// </param> /// /// <param name="modulePath"> /// The full path of the assembly from which to load the resource. /// </param> /// /// <returns> /// The resource string that was loaded or null if it could not be found. /// </returns> /// /// <remarks> /// This method ensures that an appropriate registry entry exists and that it contains /// a properly formatted resource reference ("BaseName,ResourceID"). It then creates an /// app-domain (or uses and existing one if it already exists on the instance of the class) /// and an instance of the ResourceRetriever in that app-domain. It then calls the ResourceRetriever /// to load the specified assembly and retrieve the resource. The assembly is loaded using ReflectionOnlyLoad /// or ReflectionOnlyLoadFrom using the assemblyName or moduleName (respectively) so that /// no code can be executed. /// /// The app-domain is unloaded when this class instance is disposed. /// </remarks> /// internal string GetResourceStringIndirect( RegistryKey key, string valueName, string assemblyName, string modulePath) { if (_disposed) { throw PSTraceSource.NewInvalidOperationException(MshSnapinInfo.ResourceReaderDisposed); } if (key == null) { throw PSTraceSource.NewArgumentNullException("key"); } if (String.IsNullOrEmpty(valueName)) { throw PSTraceSource.NewArgumentException("valueName"); } if (String.IsNullOrEmpty(assemblyName)) { throw PSTraceSource.NewArgumentException("assemblyName"); } if (String.IsNullOrEmpty(modulePath)) { throw PSTraceSource.NewArgumentException("modulePath"); } string result = null; do // false loop { // Read the resource reference from the registry string regValue = GetRegKeyValueAsString(key, valueName); if (regValue == null) { break; } result = GetResourceStringIndirect(assemblyName, modulePath, regValue); } while (false); return(result); }
} // WriteObject /// <summary> /// Writes the error to the pipeline or accumulates the error in an internal /// buffer. /// </summary> /// <param name="errorRecord"> /// The error record to write to the pipeline or the internal buffer. /// </param> /// <exception cref="InvalidOperationException"> /// The CmdletProvider could not stream the error because no /// cmdlet was specified to stream the output through. /// </exception> /// <exception cref="PipelineStoppedException"> /// If the pipeline has been signaled for stopping but /// the provider calls this method. /// </exception> internal void WriteError(ErrorRecord errorRecord) { // Making sure to obey the StopProcessing by // throwing an exception anytime a provider tries // to WriteError if (Stopping) { PipelineStoppedException stopPipeline = new PipelineStoppedException(); throw stopPipeline; } if (_streamErrors) { if (_command != null) { s_tracer.WriteLine("Writing error package to command error pipe"); _command.WriteError(errorRecord); } else { InvalidOperationException e = PSTraceSource.NewInvalidOperationException( SessionStateStrings.ErrorStreamingNotEnabled); throw e; } } else { // Since we are not streaming, just add the object to the accumulatedErrorObjects _accumulatedErrorObjects.Add(errorRecord); if (errorRecord.ErrorDetails != null && errorRecord.ErrorDetails.TextLookupError != null) { Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; errorRecord.ErrorDetails.TextLookupError = null; MshLog.LogProviderHealthEvent( this.ExecutionContext, this.ProviderInstance.ProviderInfo.Name, textLookupError, Severity.Warning); } } } // WriteError
/// <summary> /// Adds a <see cref="CommandParameter"/> instance to the last added command. /// </summary> internal PSCommand AddParameter(CommandParameter parameter) { if (_currentCommand == null) { throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, new object[] { "PSCommand" }); } if (_owner != null) { _owner.AssertChangesAreAccepted(); } _currentCommand.Parameters.Add(parameter); return(this); }
/// <summary> /// Adds an argument to the last added command. /// For example, to construct a command string "get-process | select-object name" /// <code> /// PSCommand command = new PSCommand("get-process"). /// AddCommand("select-object").AddParameter("name"); /// </code> /// This will add the value "name" to the positional parameter list of "select-object" /// cmdlet. When the command is invoked, this value will get bound to positional parameter 0 /// of the "select-object" cmdlet which is "Property". /// </summary> /// <param name="value"> /// Value for the parameter. /// </param> /// <returns> /// A PSCommand instance parameter value <paramref name="value"/> added /// to the parameter list of the last command. /// </returns> /// <exception cref="InvalidPowerShellStateException"> /// Powershell instance cannot be changed in its /// current state. /// </exception> /// <remarks> /// This method is not thread safe. /// </remarks> public PSCommand AddArgument(object value) { if (_currentCommand == null) { throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, new object[] { "PSCommand" }); } if (_owner != null) { _owner.AssertChangesAreAccepted(); } _currentCommand.Parameters.Add(null, value); return(this); }
public override void DisconnectAsync() { if (!this.CanDisconnect) { throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "DisconnectNotSupportedOnServer", new object[0]); } this.UpdatePoolDisconnectOptions(); try { this._runspacePool.BeginDisconnect(null, null); } catch (InvalidRunspacePoolStateException exception) { throw exception.ToInvalidRunspaceStateException(); } }
/// <summary> /// Update the given collection with the items in Add and Remove. /// </summary> /// <param name="collectionToUpdate">The collection to update.</param> public void ApplyTo(object collectionToUpdate) { if (collectionToUpdate == null) { throw new ArgumentNullException(nameof(collectionToUpdate)); } collectionToUpdate = PSObject.Base(collectionToUpdate); if (!(collectionToUpdate is IList list)) { throw PSTraceSource.NewInvalidOperationException(PSListModifierStrings.UpdateFailed); } ApplyTo(list); }
public override void Connect() { if (!this.CanConnect) { throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "CannotConnect", new object[0]); } this.UpdatePoolDisconnectOptions(); try { this._runspacePool.Connect(); } catch (InvalidRunspacePoolStateException exception) { throw exception.ToInvalidRunspaceStateException(); } }
public DefaultParameterDictionary(IDictionary dictionary) : base(StringComparer.OrdinalIgnoreCase) { if (dictionary == null) { throw new PSArgumentNullException("dictionary"); } List <object> list = new List <object>(); foreach (DictionaryEntry entry in dictionary) { if (entry.Key is string) { string key = ((string)entry.Key).Trim(); string cmdletName = null; string parameterName = null; if (!CheckKeyIsValid(key, ref cmdletName, ref parameterName)) { if (key.Equals("Disabled", StringComparison.OrdinalIgnoreCase)) { base.Add(entry.Key, entry.Value); } else { list.Add(entry.Key); } continue; } } if (list.Count == 0) { base.Add(entry.Key, entry.Value); } } StringBuilder builder = new StringBuilder(); foreach (object obj2 in list) { builder.Append(obj2.ToString() + ", "); } if (builder.Length > 0) { builder.Remove(builder.Length - 2, 2); string resourceId = (list.Count > 1) ? "MultipleKeysInBadFormat" : "SingleKeyInBadFormat"; throw PSTraceSource.NewInvalidOperationException("ParameterBinderStrings", resourceId, new object[] { builder }); } this._isChanged = true; }
private string BuildMessage(string template, string baseName, string resourceId, params object[] args) { if (string.IsNullOrEmpty(template) || (1 >= template.Trim().Length)) { this._textLookupError = PSTraceSource.NewInvalidOperationException("ErrorPackage", "ErrorDetailsEmptyTemplate", new object[] { baseName, resourceId }); return(""); } try { return(string.Format(Thread.CurrentThread.CurrentCulture, template, args)); } catch (FormatException exception) { this._textLookupError = exception; return(""); } }
/// <summary> /// Default constructor for creating ServerSteppablePipelineDriver...Used by server to concurrently /// run 2 pipelines. /// </summary> /// <param name="powershell">Decoded powershell object.</param> /// <param name="noInput">Whether there is input for this powershell.</param> /// <param name="clientPowerShellId">The client powershell id.</param> /// <param name="clientRunspacePoolId">The client runspacepool id.</param> /// <param name="runspacePoolDriver">runspace pool driver /// which is creating this powershell driver</param> /// <param name="apartmentState">Apartment state for this powershell.</param> /// <param name="hostInfo">host info using which the host for /// this powershell will be constructed</param> /// <param name="streamOptions">Serialization options for the streams in this powershell.</param> /// <param name="addToHistory"> /// true if the command is to be added to history list of the runspace. false, otherwise. /// </param> /// <param name="rsToUse"> /// If not null, this Runspace will be used to invoke Powershell. /// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used. /// </param> /// <param name="eventSubscriber"> /// Steppable pipeline event subscriber /// </param> /// <param name="powershellInput">Input collection of the PowerShell pipeline.</param> internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse, ServerSteppablePipelineSubscriber eventSubscriber, PSDataCollection <object> powershellInput) #endif { LocalPowerShell = powershell; InstanceId = clientPowerShellId; RunspacePoolId = clientRunspacePoolId; RemoteStreamOptions = streamOptions; #if !CORECLR // No ApartmentState In CoreCLR this.apartmentState = apartmentState; #endif NoInput = noInput; _addToHistory = addToHistory; _eventSubscriber = eventSubscriber; _powershellInput = powershellInput; Input = new PSDataCollection <object>(); InputEnumerator = Input.GetEnumerator(); Input.ReleaseOnEnumeration = true; DataStructureHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, RemoteStreamOptions, null); RemoteHost = DataStructureHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost); // subscribe to various data structure handler events DataStructureHandler.InputEndReceived += new EventHandler(HandleInputEndReceived); DataStructureHandler.InputReceived += new EventHandler <RemoteDataEventArgs <object> >(HandleInputReceived); DataStructureHandler.StopPowerShellReceived += new EventHandler(HandleStopReceived); DataStructureHandler.HostResponseReceived += new EventHandler <RemoteDataEventArgs <RemoteHostResponse> >(HandleHostResponseReceived); DataStructureHandler.OnSessionConnected += new EventHandler(HandleSessionConnected); if (rsToUse == null) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NestedPipelineMissingRunspace); } // else, set the runspace pool and invoke this powershell LocalPowerShell.Runspace = rsToUse; eventSubscriber.SubscribeEvents(this); PipelineState = PSInvocationState.NotStarted; }
internal object Deserialize(out string streamName) { object obj2; if (this.Done()) { throw PSTraceSource.NewInvalidOperationException("Serialization", "ReadCalledAfterDone", new object[0]); } try { obj2 = this._deserializer.ReadOneObject(out streamName); } catch (XmlException exception) { ReportExceptionForETW(exception); throw; } return(obj2); }
public override void Add(object key, object value) { if (key == null) { throw new PSArgumentNullException("key"); } if (key is string) { string str = ((string)key).Trim(); string cmdletName = null; string parameterName = null; if (!CheckKeyIsValid(str, ref cmdletName, ref parameterName) && !str.Equals("Disabled", StringComparison.OrdinalIgnoreCase)) { throw PSTraceSource.NewInvalidOperationException("ParameterBinderStrings", "SingleKeyInBadFormat", new object[] { key.ToString() }); } } base.Add(key, value); this._isChanged = true; }
public object GetDynamicParameters() { this._commandRuntime = (MshCommandRuntime)base.commandRuntime; if (this._scriptBlock.HasDynamicParameters) { ArrayList resultList = new ArrayList(); this._functionContext._outputPipe = new Pipe(resultList); this.RunClause(this._runOptimized ? this._scriptBlock.DynamicParamBlock : this._scriptBlock.UnoptimizedDynamicParamBlock, AutomationNull.Value, AutomationNull.Value); if (resultList.Count > 1) { throw PSTraceSource.NewInvalidOperationException("AutomationExceptions", "DynamicParametersWrongType", new object[] { PSObject.ToStringParser(base.Context, resultList) }); } if (resultList.Count != 0) { return(PSObject.Base(resultList[0])); } } return(null); }
private void InitPowerShell(bool syncCall, bool invokeAndDisconnect = false) { if ((this._commands == null) || (this._commands.Count == 0)) { throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "NoCommandInPipeline", new object[0]); } if (this._pipelineStateInfo.State != PipelineState.NotStarted) { InvalidPipelineStateException exception = new InvalidPipelineStateException(StringUtil.Format(RunspaceStrings.PipelineReInvokeNotAllowed, new object[0]), this._pipelineStateInfo.State, PipelineState.NotStarted); throw exception; } ((RemoteRunspace)this._runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall); PSInvocationSettings settings = new PSInvocationSettings { AddToHistory = this._addToHistory, InvokeAndDisconnect = invokeAndDisconnect }; this._powershell.InitForRemotePipeline(this._commands, this._inputStream, this._outputStream, this._errorStream, settings, base.RedirectShellErrorOutputPipe); this._powershell.RemotePowerShell.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(this.HandleHostCallReceived); }
private static Expression GetPropertyOrFieldExpr(Type type, string name, Expression target) { try { PropertyInfo property = type.GetProperty(name, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); if (property != null) { return(Expression.Property(target, property)); } } catch (AmbiguousMatchException) { foreach (PropertyInfo info2 in type.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance)) { if (info2.Name.Equals(name, StringComparison.Ordinal)) { return(Expression.Property(target, info2)); } } } try { FieldInfo field = type.GetField(name, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); if (field != null) { return(Expression.Field(target, field)); } } catch (AmbiguousMatchException) { foreach (FieldInfo info4 in type.GetFields(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance)) { if (info4.Name.Equals(name, StringComparison.Ordinal)) { return(Expression.Field(target, info4)); } } } throw PSTraceSource.NewInvalidOperationException(); }
internal RemoteRunspace(System.Management.Automation.Runspaces.RunspacePool runspacePool) { this._runningPipelines = new ArrayList(); this._syncRoot = new object(); this._runspaceStateInfo = new System.Management.Automation.Runspaces.RunspaceStateInfo(RunspaceState.BeforeOpen); this._version = PSVersionInfo.PSVersion; this._runspaceEventQueue = new Queue <RunspaceEventQueueItem>(); this.id = -1; if ((runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected) || !(runspacePool.ConnectionInfo is WSManConnectionInfo)) { throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "InvalidRunspacePool", new object[0]); } this._runspacePool = runspacePool; this._runspacePool.RemoteRunspacePoolInternal.SetMinRunspaces(1); this._runspacePool.RemoteRunspacePoolInternal.SetMaxRunspaces(1); this._connectionInfo = ((WSManConnectionInfo)runspacePool.ConnectionInfo).Copy(); this.SetRunspaceState(RunspaceState.Disconnected, null); this._runspaceAvailability = this._runspacePool.RemoteRunspacePoolInternal.AvailableForConnection ? System.Management.Automation.Runspaces.RunspaceAvailability.None : System.Management.Automation.Runspaces.RunspaceAvailability.Busy; this.SetEventHandlers(); PSEtwLog.SetActivityIdForCurrentThread(base.InstanceId); PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { base.InstanceId.ToString() }); }
internal void WriteObject(object obj) { if (this.Stopping) { PipelineStoppedException exception = new PipelineStoppedException(); throw exception; } if (this.streamObjects) { if (this.command == null) { throw PSTraceSource.NewInvalidOperationException("SessionStateStrings", "OutputStreamingNotEnabled", new object[0]); } tracer.WriteLine("Writing to command pipeline", new object[0]); this.command.WriteObject(obj); } else { tracer.WriteLine("Writing to accumulated objects", new object[0]); PSObject item = PSObject.AsPSObject(obj); this.accumulatedObjects.Add(item); } }
internal ScriptBlock NewBoundScriptBlock(ScriptBlock scriptBlockToBind, ExecutionContext context) { ScriptBlock block; if ((this._sessionState == null) || (context == null)) { throw PSTraceSource.NewInvalidOperationException("Modules", "InvalidOperationOnBinaryModule", new object[0]); } lock (context.EngineSessionState) { SessionStateInternal engineSessionState = context.EngineSessionState; try { context.EngineSessionState = this._sessionState.Internal; block = scriptBlockToBind.Clone(true); block.SessionState = this._sessionState; } finally { context.EngineSessionState = engineSessionState; } } return(block); }
internal string GetResourceStringIndirect(string assemblyName, string modulePath, string baseNameRIDPair) { if (this._disposed) { throw PSTraceSource.NewInvalidOperationException("PSSnapinInfo", "ResourceReaderDisposed", new object[0]); } if (string.IsNullOrEmpty(assemblyName)) { throw PSTraceSource.NewArgumentException("assemblyName"); } if (string.IsNullOrEmpty(modulePath)) { throw PSTraceSource.NewArgumentException("modulePath"); } if (string.IsNullOrEmpty(baseNameRIDPair)) { throw PSTraceSource.NewArgumentException("baseNameRIDPair"); } string str = null; if (this._resourceRetriever == null) { this.CreateAppDomain(); } if (this._resourceRetriever != null) { string[] strArray = baseNameRIDPair.Split(new char[] { ',' }); if (strArray.Length == 2) { string baseName = strArray[0]; string resourceID = strArray[1]; str = this._resourceRetriever.GetStringResource(assemblyName, modulePath, baseName, resourceID); } } return(str); }
internal Uri LookupUriFromCommandInfo() { CommandTypes cmdlet = CommandTypes.Cmdlet; switch (this.HelpCategory) { case System.Management.Automation.HelpCategory.Function: cmdlet = CommandTypes.Function; break; case System.Management.Automation.HelpCategory.Filter: cmdlet = CommandTypes.Filter; break; case System.Management.Automation.HelpCategory.ExternalScript: cmdlet = CommandTypes.ExternalScript; break; case System.Management.Automation.HelpCategory.Cmdlet: cmdlet = CommandTypes.Cmdlet; break; case System.Management.Automation.HelpCategory.ScriptCommand: cmdlet = CommandTypes.Script; break; default: return(null); } string name = this.Name; string result = string.Empty; if (this.FullHelp.Properties["ModuleName"] != null) { PSNoteProperty property = this.FullHelp.Properties["ModuleName"] as PSNoteProperty; if (property != null) { LanguagePrimitives.TryConvertTo <string>(property.Value, CultureInfo.InvariantCulture, out result); } } string commandName = name; if (!string.IsNullOrEmpty(result)) { commandName = string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", new object[] { result, name }); } ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); if (executionContextFromTLS != null) { try { CommandInfo info = null; if (cmdlet == CommandTypes.Cmdlet) { info = executionContextFromTLS.SessionState.InvokeCommand.GetCmdlet(commandName); } else { info = executionContextFromTLS.SessionState.InvokeCommand.GetCommands(commandName, cmdlet, false).FirstOrDefault <CommandInfo>(); } if ((info == null) || (info.CommandMetadata == null)) { return(null); } if (!string.IsNullOrEmpty(info.CommandMetadata.HelpUri)) { try { return(new Uri(info.CommandMetadata.HelpUri)); } catch (UriFormatException) { throw PSTraceSource.NewInvalidOperationException("HelpErrors", "InvalidURI", new object[] { info.CommandMetadata.HelpUri }); } } } catch (CommandNotFoundException) { } } return(null); }
/// <summary> /// Get a Hashtable object out of a PowerShell data file (.psd1) /// </summary> /// <param name="parameterName"> /// Name of the parameter that takes the specified .psd1 file as a value /// </param> /// <param name="psDataFilePath"> /// Path to the powershell data file /// </param> /// <param name="context"> /// ExecutionContext to use /// </param> /// <param name="allowedCommands"> /// Set of command names that are allowed to use in the .psd1 file /// </param> /// <param name="allowedVariables"> /// Set of variable names that are allowed to use in the .psd1 file /// </param> /// <param name="allowEnvironmentVariables"> /// If true, allow to use environment variables in the .psd1 file /// </param> /// <param name="skipPathValidation"> /// If true, caller guarantees the path is valid /// </param> /// <returns></returns> internal static Hashtable EvaluatePowerShellDataFile( string parameterName, string psDataFilePath, ExecutionContext context, IEnumerable <string> allowedCommands, IEnumerable <string> allowedVariables, bool allowEnvironmentVariables, bool skipPathValidation) { if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) { throw PSTraceSource.NewArgumentNullException("parameterName"); } if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException("psDataFilePath"); } if (context == null) { throw PSTraceSource.NewArgumentNullException("context"); } string resolvedPath; if (skipPathValidation) { resolvedPath = psDataFilePath; } else { #region "ValidatePowerShellDataFilePath" bool isPathValid = true; // File extension needs to be .psd1 string pathExt = Path.GetExtension(psDataFilePath); if (string.IsNullOrEmpty(pathExt) || !StringLiterals.PowerShellDataFileExtension.Equals(pathExt, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } ProviderInfo provider; var resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider); // ConfigPath should be resolved as FileSystem provider if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } // ConfigPath should be resolved to a single path if (resolvedPaths.Count != 1) { isPathValid = false; } if (!isPathValid) { throw PSTraceSource.NewArgumentException( parameterName, ParserStrings.CannotResolvePowerShellDataFilePath, psDataFilePath); } resolvedPath = resolvedPaths[0]; #endregion "ValidatePowerShellDataFilePath" } #region "LoadAndEvaluatePowerShellDataFile" object evaluationResult; try { // Create the scriptInfo for the .psd1 file string dataFileName = Path.GetFileName(resolvedPath); var dataFileScriptInfo = new ExternalScriptInfo(dataFileName, resolvedPath, context); ScriptBlock scriptBlock = dataFileScriptInfo.ScriptBlock; // Validate the scriptblock scriptBlock.CheckRestrictedLanguage(allowedCommands, allowedVariables, allowEnvironmentVariables); // Evaluate the scriptblock object oldPsScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath); try { // Set the $PSScriptRoot before the evaluation context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(resolvedPath)); evaluationResult = PSObject.Base(scriptBlock.InvokeReturnAsIs()); } finally { context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPsScriptRoot); } } catch (RuntimeException ex) { throw PSTraceSource.NewInvalidOperationException( ex, ParserStrings.CannotLoadPowerShellDataFile, psDataFilePath, ex.Message); } var retResult = evaluationResult as Hashtable; if (retResult == null) { throw PSTraceSource.NewInvalidOperationException( ParserStrings.InvalidPowerShellDataFile, psDataFilePath); } #endregion "LoadAndEvaluatePowerShellDataFile" return(retResult); }
internal Uri LookupUriFromCommandInfo() { CommandTypes cmdTypesToLookFor = CommandTypes.Cmdlet; switch (this.HelpCategory) { case Automation.HelpCategory.Cmdlet: cmdTypesToLookFor = CommandTypes.Cmdlet; break; case Automation.HelpCategory.Function: cmdTypesToLookFor = CommandTypes.Function; break; case Automation.HelpCategory.ScriptCommand: cmdTypesToLookFor = CommandTypes.Script; break; case Automation.HelpCategory.ExternalScript: cmdTypesToLookFor = CommandTypes.ExternalScript; break; case Automation.HelpCategory.Filter: cmdTypesToLookFor = CommandTypes.Filter; break; case Automation.HelpCategory.Configuration: cmdTypesToLookFor = CommandTypes.Configuration; break; default: return(null); } string commandName = this.Name; string moduleName = string.Empty; if (this.FullHelp.Properties["ModuleName"] != null) { PSNoteProperty moduleNameNP = this.FullHelp.Properties["ModuleName"] as PSNoteProperty; if (null != moduleNameNP) { LanguagePrimitives.TryConvertTo <string>(moduleNameNP.Value, CultureInfo.InvariantCulture, out moduleName); } } string commandToSearch = commandName; if (!string.IsNullOrEmpty(moduleName)) { commandToSearch = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", moduleName, commandName); } ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); if (null == context) { return(null); } try { CommandInfo cmdInfo = null; if (cmdTypesToLookFor == CommandTypes.Cmdlet) { cmdInfo = context.SessionState.InvokeCommand.GetCmdlet(commandToSearch); } else { cmdInfo = context.SessionState.InvokeCommand.GetCommands(commandToSearch, cmdTypesToLookFor, false).FirstOrDefault(); } if ((cmdInfo == null) || (cmdInfo.CommandMetadata == null)) { return(null); } string uriString = cmdInfo.CommandMetadata.HelpUri; if (!string.IsNullOrEmpty(uriString)) { if (!System.Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute)) { // WinBlue: 545315 Online help links are broken with localized help // Example: https://go.microsoft.com/fwlink/?LinkID=113324 (möglicherwei se auf Englisch) // Split the string based on <s> (space). We decided to go with this approach as // UX localization authors use spaces. Correctly extracting only the wellformed URI // is out-of-scope for this fix. string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space); uriString = tempUriSplitArray[0]; } try { return(new System.Uri(uriString)); // return only the first Uri (ignore other uris) } catch (UriFormatException) { throw PSTraceSource.NewInvalidOperationException(HelpErrors.InvalidURI, cmdInfo.CommandMetadata.HelpUri); } } } catch (CommandNotFoundException) { } return(null); }
/// <summary> /// Check if anyother pipeline is executing. /// In case of nested pipeline, checks that it is called /// from currently executing pipeline's thread. /// </summary> /// <param name="syncCall">True if method is called from Invoke, false /// if called from InvokeAsync</param> /// <exception cref="InvalidOperationException"> /// 1) A pipeline is already executing. Pipeline cannot execute /// concurrently. /// 2) InvokeAsync is called on nested pipeline. Nested pipeline /// cannot be executed Asynchronously. /// 3) Attempt is made to invoke a nested pipeline directly. Nested /// pipeline must be invoked from a running pipeline. /// </exception> internal void DoConcurrentCheck(bool syncCall) { RemotePipeline currentPipeline = (RemotePipeline)((RemoteRunspace)_runspace).GetCurrentlyRunningPipeline(); if (_isNested == false) { if (currentPipeline == null && ((RemoteRunspace)_runspace).RunspaceAvailability != RunspaceAvailability.Busy && ((RemoteRunspace)_runspace).RunspaceAvailability != RunspaceAvailability.RemoteDebug) { // We can add a new pipeline to the runspace only if it is // available (not busy). return; } if (currentPipeline == null && ((RemoteRunspace)_runspace).RemoteCommand != null && _connectCmdInfo != null && Guid.Equals(((RemoteRunspace)_runspace).RemoteCommand.CommandId, _connectCmdInfo.CommandId)) { // Connect case. We can add a pipeline to a busy runspace when // that pipeline represents the same command as is currently // running. return; } if (currentPipeline != null && ReferenceEquals(currentPipeline, this)) { // Reconnect case. We can add a pipeline to a busy runspace when the // pipeline is the same (reconnecting). return; } if (!_isSteppable) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.ConcurrentInvokeNotAllowed); } } else { if (_performNestedCheck) { if (_isSteppable) { return; } if (syncCall == false) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.NestedPipelineInvokeAsync); } if (currentPipeline == null) { if (!_isSteppable) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.NestedPipelineNoParentPipeline); } } } } }
internal virtual PowerShell GetPowerShell(Guid instanceId) { throw PSTraceSource.NewInvalidOperationException(); }
internal static Uri GetUriFromCommandPSObject(PSObject commandFullHelp) { // this object knows Maml format... // So retrieve Uri information as per the format.. if ((commandFullHelp == null) || (commandFullHelp.Properties["relatedLinks"] == null) || (commandFullHelp.Properties["relatedLinks"].Value == null)) { // return the default.. return(null); } PSObject relatedLinks = PSObject.AsPSObject(commandFullHelp.Properties["relatedLinks"].Value); if (relatedLinks.Properties["navigationLink"] == null) { return(null); } object[] navigationLinks = (object[])LanguagePrimitives.ConvertTo( relatedLinks.Properties["navigationLink"].Value, typeof(object[]), CultureInfo.InvariantCulture); foreach (object navigationLinkAsObject in navigationLinks) { if (navigationLinkAsObject == null) { continue; } PSObject navigationLink = PSObject.AsPSObject(navigationLinkAsObject); PSNoteProperty uriNP = navigationLink.Properties["uri"] as PSNoteProperty; if (null != uriNP) { string uriString = string.Empty; LanguagePrimitives.TryConvertTo <string>(uriNP.Value, CultureInfo.InvariantCulture, out uriString); if (!string.IsNullOrEmpty(uriString)) { if (!System.Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute)) { // WinBlue: 545315 Online help links are broken with localized help // Example: https://go.microsoft.com/fwlink/?LinkID=113324 (möglicherwei se auf Englisch) // Split the string based on <s> (space). We decided to go with this approach as // UX localization authors use spaces. Correctly extracting only the wellformed URI // is out-of-scope for this fix. string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space); uriString = tempUriSplitArray[0]; } try { return(new System.Uri(uriString)); // return only the first Uri (ignore other uris) } catch (UriFormatException) { throw PSTraceSource.NewInvalidOperationException(HelpErrors.InvalidURI, uriString); } } } } return(null); }
private PSModuleInfo CreateModuleImplementation(string name, string path, object moduleCode, IScriptExtent scriptPosition, SessionState ss, object privateData, out ArrayList result, params object[] arguments) { if (ss == null) { ss = new SessionState(this._context, true, true); } SessionStateInternal engineSessionState = this._context.EngineSessionState; PSModuleInfo info = new PSModuleInfo(name, path, this._context, ss); ss.Internal.Module = info; info.PrivateData = privateData; bool flag = false; int newValue = 0; try { ScriptBlock scriptBlock; this._context.EngineSessionState = ss.Internal; ExternalScriptInfo scriptCommandInfo = moduleCode as ExternalScriptInfo; if (scriptCommandInfo != null) { scriptBlock = scriptCommandInfo.ScriptBlock; this._context.Debugger.RegisterScriptFile(scriptCommandInfo); } else { scriptBlock = moduleCode as ScriptBlock; if (scriptBlock != null) { PSLanguageMode?languageMode = scriptBlock.LanguageMode; scriptBlock = scriptBlock.Clone(true); scriptBlock.LanguageMode = languageMode; scriptBlock.SessionState = ss; } else if (moduleCode is string) { scriptBlock = ScriptBlock.Create(this._context, (string)moduleCode); } } if (scriptBlock == null) { throw PSTraceSource.NewInvalidOperationException(); } scriptBlock.SessionStateInternal = ss.Internal; InvocationInfo invocationInfo = new InvocationInfo(scriptCommandInfo, scriptPosition); info._definitionExtent = scriptBlock.Ast.Extent; ArrayList resultList = new ArrayList(); try { Pipe outputPipe = new Pipe(resultList); scriptBlock.InvokeWithPipe(false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, AutomationNull.Value, AutomationNull.Value, outputPipe, invocationInfo, arguments ?? new object[0]); } catch (ExitException exception) { newValue = (int)exception.Argument; flag = true; } result = resultList; } finally { this._context.EngineSessionState = engineSessionState; } if (flag) { this._context.SetVariable(SpecialVariables.LastExitCodeVarPath, newValue); } return(info); }