internal SessionStateFunctionEntry(string name, string definition, ScopedItemOptions options, SessionStateEntryVisibility visibility, System.Management.Automation.ScriptBlock scriptBlock, string helpFile) : base(name, visibility) { this._definition = definition; this._options = options; this._scriptBlock = scriptBlock; this._helpFile = helpFile; }
internal FunctionInfo(string verb, string noun, ScriptBlock function, IEnumerable<ParameterAst> explicitParams, ScopedItemOptions options) : this(verb + "-" + noun, function, explicitParams, options) { Verb = verb; Noun = noun; }
private void CopyFieldsFromOther(FunctionInfo other) { this._scriptBlock = other._scriptBlock; this._description = other._description; this._options = other._options; this._helpFile = other._helpFile; }
public CmdletInfo(string name, Type implementingType) : base(name, CommandTypes.Cmdlet, null) { this.verb = string.Empty; this.noun = string.Empty; this.helpFilePath = string.Empty; if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentNullException("name"); } if (implementingType == null) { throw PSTraceSource.NewArgumentNullException("name"); } if (!typeof(Cmdlet).IsAssignableFrom(implementingType)) { throw PSTraceSource.NewInvalidOperationException("DiscoveryExceptions", "CmdletDoesNotDeriveFromCmdletType", new object[] { "implementingType", implementingType.FullName }); } if (!SplitCmdletName(name, out this.verb, out this.noun)) { throw PSTraceSource.NewArgumentException("name", "DiscoveryExceptions", "InvalidCmdletNameFormat", new object[] { name }); } this.implementingType = implementingType; this.helpFilePath = string.Empty; this._PSSnapin = null; this.options = ScopedItemOptions.ReadOnly; }
internal SessionStateWorkflowEntry(string name, string definition, ScopedItemOptions options, SessionStateEntryVisibility visibility, System.Management.Automation.WorkflowInfo workflow, string helpFile) : base(name, visibility) { this._definition = definition; this._options = options; this._workflow = workflow; this._helpFile = helpFile; }
internal AliasInfo(string name, string definition, CommandManager cmdManager, ScopedItemOptions options) : base(name, CommandTypes.Alias) { Options = options; SetDefinition(definition, cmdManager); }
public SessionStateFunctionEntry(string name, string definition, ScopedItemOptions options) : base(name, SessionStateEntryVisibility.Public) { this.commandType = CommandTypes.Function; this.definition = definition; this.options = options; }
public SessionStateVariableEntry(string name, object value, string description, ScopedItemOptions options) : base(name, SessionStateEntryVisibility.Public) { this._description = string.Empty; this._value = value; this._description = description; this._options = options; }
internal FunctionInfo(string name, ScriptBlock function, ScopedItemOptions options) : base(name, CommandTypes.Function) { ScriptBlock = function; Options = options; ScopeUsage = ScopeUsages.NewScope; }
public SessionStateAliasEntry(string name, string definition, string description, ScopedItemOptions options) : base(name, SessionStateEntryVisibility.Public) { this.definition = definition; this.description = description; this.scopeoptions = options; }
public SessionStateWorkflowEntry(string name, string definition, ScopedItemOptions options, string helpFile) : base(name, SessionStateEntryVisibility.Public) { this._definition = definition; base._commandType = CommandTypes.Workflow; this._options = options; this._helpFile = helpFile; }
internal SessionStateAliasEntry(string name, string definition, string description, ScopedItemOptions options, SessionStateEntryVisibility visibility) : base(name, visibility) { this._description = string.Empty; this._definition = definition; base._commandType = CommandTypes.Alias; this._description = description; this._options = options; }
internal AliasInfo(string name, string definition, string description, CommandManager cmdManager, ScopedItemOptions options) : base(name, CommandTypes.Alias) { _cmdManager = cmdManager; Options = options; Description = description; _definition = definition; }
public SessionStateVariableEntry(string name, object value, string description, ScopedItemOptions options, Collection<Attribute> attributes) : base(name, SessionStateEntryVisibility.Public) { this.Options = options; this.Description = description; this.Value = value; this.Attributes = attributes; }
public SessionStateFunctionEntry(string name, string definition, ScopedItemOptions options, string helpFile) : base(name, SessionStateEntryVisibility.Public) { this._definition = definition; base._commandType = CommandTypes.Function; this._options = options; this._scriptBlock = System.Management.Automation.ScriptBlock.Create(this._definition); this._helpFile = helpFile; }
public SessionStateVariableEntry(string name, object value, string description, ScopedItemOptions options, Attribute attribute) : base(name, SessionStateEntryVisibility.Public) { this._description = string.Empty; this._value = value; this._description = description; this._options = options; this._attributes = new Collection<Attribute>(); this._attributes.Add(attribute); }
internal SessionStateCapacityVariable(string name, int defaultCapacity, int maxCapacity, int minCapacity, ScopedItemOptions options) : base(name, defaultCapacity, options) { this.maxCapacity = 0x7fffffff; ValidateRangeAttribute item = new ValidateRangeAttribute(minCapacity, maxCapacity); this.minCapacity = minCapacity; this.maxCapacity = maxCapacity; base.Attributes.Add(item); this._fastValue = defaultCapacity; }
public SessionStateCapacityVariable(string name, SessionStateCapacityVariable sharedCapacityVariable, ScopedItemOptions options) : base(name, sharedCapacityVariable.Value, options) { this.maxCapacity = 0x7fffffff; ValidateRangeAttribute item = new ValidateRangeAttribute(0, 0x7fffffff); base.Attributes.Add(item); this.sharedCapacityVariable = sharedCapacityVariable; this.Description = sharedCapacityVariable.Description; this._fastValue = (int) sharedCapacityVariable.Value; }
internal FunctionInfo(string verb, string noun, ScriptBlock function, ScopedItemOptions options) : base(verb + "-" + noun, CommandTypes.Function) { ScriptBlock = function; Options = options; Verb = verb; Noun = noun; ScopeUsage = ScopeUsages.NewScope; }
internal SessionStateVariableEntry(string name, object value, string description, ScopedItemOptions options, Collection<Attribute> attributes, SessionStateEntryVisibility visibility) : base(name, visibility) { this._description = string.Empty; this._value = value; this._description = description; this._options = options; this._attributes = new Collection<Attribute>(); this._attributes = attributes; }
internal FunctionInfo(string name, ScriptBlock function, IEnumerable<ParameterAst> explicitParams, ScopedItemOptions options) : base(name, CommandTypes.Function) { ScriptBlock = function; Options = options; ScopeUsage = ScopeUsages.NewScope; _explicitParameters = explicitParams == null ? new ReadOnlyCollection<ParameterAst>(new ParameterAst[0]) : explicitParams.ToReadOnlyCollection(); }
protected internal override void Update(FunctionInfo function, bool force, ScopedItemOptions options, string helpFile) { WorkflowInfo other = function as WorkflowInfo; if (other == null) { throw PSTraceSource.NewArgumentException("function"); } base.Update(function, force, options, helpFile); this.CopyFields(other); }
internal CmdletInfo(CmdletInfo other) : base(other) { this.verb = string.Empty; this.noun = string.Empty; this.helpFilePath = string.Empty; this.verb = other.verb; this.noun = other.noun; this.implementingType = other.implementingType; this.helpFilePath = other.helpFilePath; this._PSSnapin = other._PSSnapin; this.options = ScopedItemOptions.ReadOnly; }
internal AliasInfo(string name, string definition, ExecutionContext context, ScopedItemOptions options) : base(name, CommandTypes.Alias) { this._definition = string.Empty; this.description = string.Empty; this._definition = definition; base.Context = context; this.options = options; if (context != null) { base.SetModule(context.SessionState.Internal.Module); } }
public SessionStateVariableEntry( string name, object value, string description, ScopedItemOptions options, Attribute attribute) : base(name, SessionStateEntryVisibility.Public) { this._value = value; this._description = description; this._options = options; this._attributes = new Collection <Attribute>(); this._attributes.Add(attribute); }
internal SessionStateVariableEntry( string name, object value, string description, ScopedItemOptions options, Collection <Attribute> attributes, SessionStateEntryVisibility visibility) : base(name, visibility) { this._value = value; this._description = description; this._options = options; this._attributes = new Collection <Attribute>(); this._attributes = attributes; }
internal SessionStateCapacityVariable( string name, int defaultCapacity, int maxCapacity, int minCapacity, ScopedItemOptions options) : base(name, (object)defaultCapacity, options) { ValidateRangeAttribute validateRangeAttribute = new ValidateRangeAttribute((object)minCapacity, (object)maxCapacity); this.minCapacity = minCapacity; this.maxCapacity = maxCapacity; this.Attributes.Add((Attribute)validateRangeAttribute); this._fastValue = defaultCapacity; }
/// <summary> /// Creates an instance of the AliasInfo class with the specified name and referenced command /// </summary> /// /// <param name="name"> /// The name of the command. /// </param> /// /// <param name="definition"> /// The token that the alias refers to. /// </param> /// /// <param name="context"> /// The execution context for this engine instance, used to look up session state. /// </param> /// /// <param name="options"> /// The options to set on the alias. Note, Constant can only be set at creation time. /// </param> /// /// <exception cref="ArgumentException"> /// If <paramref name="definition"/> is null or empty. /// </exception> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="context"/> is null. /// </exception> /// internal AliasInfo( string name, string definition, ExecutionContext context, ScopedItemOptions options) : base(name, CommandTypes.Alias) { _definition = definition; this.Context = context; _options = options; if (context != null) { this.Module = context.SessionState.Internal.Module; } }
internal AliasInfo SetAliasValue(string name, string value, ScopedItemOptions options, System.Management.Automation.ExecutionContext context, bool force, CommandOrigin origin) { if (!this.GetAliases().ContainsKey(name)) { if (this.GetAliases().Count > (this.AliasCapacity.FastValue - 1)) { SessionStateOverflowException exception = new SessionStateOverflowException(name, SessionStateCategory.Alias, "AliasOverflow", SessionStateStrings.AliasOverflow, new object[] { this.AliasCapacity.FastValue }); throw exception; } AliasInfo info = new AliasInfo(name, value, context, options); this.GetAliases()[name] = info; } else { AliasInfo valueToCheck = this.GetAliases()[name]; if (((valueToCheck.Options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (!force && ((valueToCheck.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None))) { SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Alias, "AliasNotWritable", SessionStateStrings.AliasNotWritable); throw exception2; } if ((options & ScopedItemOptions.Constant) != ScopedItemOptions.None) { SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Alias, "AliasCannotBeMadeConstant", SessionStateStrings.AliasCannotBeMadeConstant); throw exception3; } if (((options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && ((valueToCheck.Options & ScopedItemOptions.AllScope) != ScopedItemOptions.None)) { SessionStateUnauthorizedAccessException exception4 = new SessionStateUnauthorizedAccessException(name, SessionStateCategory.Alias, "AliasAllScopeOptionCannotBeRemoved", SessionStateStrings.AliasAllScopeOptionCannotBeRemoved); throw exception4; } SessionState.ThrowIfNotVisible(origin, valueToCheck); this.RemoveAliasFromCache(valueToCheck.Name, valueToCheck.Definition); if (force) { this.GetAliases().Remove(name); valueToCheck = new AliasInfo(name, value, context, options); this.GetAliases()[name] = valueToCheck; } else { valueToCheck.Options = options; valueToCheck.SetDefinition(value, false); } } this.AddAliasToCache(name, value); return(this.GetAliases()[name]); }
/// <summary> /// Updates a function. /// </summary> /// <param name="newFunction"> /// The script block that the function should represent. /// </param> /// <param name="force"> /// If true, the script block will be applied even if the filter is ReadOnly. /// </param> /// <param name="options"> /// Any options to set on the new function, null if none. /// </param> /// <param name="helpFile"> /// The helpfile for this function. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="newFunction"/> is null. /// </exception> internal void Update(ScriptBlock newFunction, bool force, ScopedItemOptions options, string helpFile) { if (newFunction == null) { throw PSTraceSource.NewArgumentNullException("function"); } if ((_options & ScopedItemOptions.Constant) != 0) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( Name, SessionStateCategory.Function, "FunctionIsConstant", SessionStateStrings.FunctionIsConstant); throw e; } if (!force && (_options & ScopedItemOptions.ReadOnly) != 0) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( Name, SessionStateCategory.Function, "FunctionIsReadOnly", SessionStateStrings.FunctionIsReadOnly); throw e; } _scriptBlock = newFunction; this.Module = newFunction.Module; _commandMetadata = null; this._parameterSets = null; this.ExternalCommandMetadata = null; if (options != ScopedItemOptions.Unspecified) { this.Options = options; } _helpFile = helpFile; }
/// <summary> /// Constructs an instance of the variable with the specified name and /// initial capacity. /// </summary> /// /// <param name="name"> /// The name of the variable. /// </param> /// /// <param name="defaultCapacity"> /// The initial capacity /// </param> /// /// <param name="maxCapacity"> /// The maximum capacity for the scope. /// </param> /// /// <param name="minCapacity"> /// The minimum capacity for the scope. /// </param> /// /// <param name="options">Scoped item options for this variable</param> internal SessionStateCapacityVariable( string name, int defaultCapacity, int maxCapacity, int minCapacity, ScopedItemOptions options) : base(name, defaultCapacity, options) { // Now add a range constraint to the variable so that // it is discoverable... ValidateRangeAttribute validateRange = new ValidateRangeAttribute(minCapacity, maxCapacity); _minCapacity = minCapacity; _maxCapacity = maxCapacity; base.Attributes.Add(validateRange); _fastValue = defaultCapacity; }
/// <summary> /// Sets the options for the cmdlet and allows changes ReadOnly options only if force is specified. /// </summary> /// <param name="newOptions"> /// The new options value. /// </param> /// <param name="force"> /// If true the change to the options will happen even if the existing options are read-only. /// </param> internal void SetOptions(ScopedItemOptions newOptions, bool force) { // Check to see if the cmdlet is readonly, if so // throw an exception because the options cannot be changed. if ((_options & ScopedItemOptions.ReadOnly) != 0) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( Name, SessionStateCategory.Cmdlet, "CmdletIsReadOnly", SessionStateStrings.CmdletIsReadOnly); throw e; } _options = newOptions; }
internal CmdletInfo(string name, Type implementingType, string helpFile, PSSnapInInfo PSSnapin, System.Management.Automation.ExecutionContext context) : base(name, CommandTypes.Cmdlet, context) { this.verb = string.Empty; this.noun = string.Empty; this.helpFilePath = string.Empty; if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } if (!SplitCmdletName(name, out this.verb, out this.noun)) { throw PSTraceSource.NewArgumentException("name", "DiscoveryExceptions", "InvalidCmdletNameFormat", new object[] { name }); } this.implementingType = implementingType; this.helpFilePath = helpFile; this._PSSnapin = PSSnapin; this.options = ScopedItemOptions.ReadOnly; base.DefiningLanguageMode = 0; }
internal void SetOptions(ScopedItemOptions newOptions, bool force) { if (this.IsConstant || (!force && this.IsReadOnly)) { SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(this.name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable); throw exception; } if ((newOptions & ScopedItemOptions.Constant) != ScopedItemOptions.None) { SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(this.name, SessionStateCategory.Variable, "VariableCannotBeMadeConstant", SessionStateStrings.VariableCannotBeMadeConstant); throw exception2; } if (this.IsAllScope && ((newOptions & ScopedItemOptions.AllScope) == ScopedItemOptions.None)) { SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(this.name, SessionStateCategory.Variable, "VariableAllScopeOptionCannotBeRemoved", SessionStateStrings.VariableAllScopeOptionCannotBeRemoved); throw exception3; } this.options = newOptions; }
// Create a VariableInfo for both serialized and deserialized variables. private static VariableInfo TryVariableInfo(PSObject psObject) { if (psObject.TypeNames.Contains("System.Management.Automation.PSVariable")) { return(new VariableInfo(psObject.TypeNames.ToArray(), psObject.BaseObject as PSVariable)); } if (psObject.TypeNames.Contains("Deserialized.System.Management.Automation.PSVariable")) { // Rehydrate the relevant variable properties and recreate it. ScopedItemOptions options = (ScopedItemOptions)Enum.Parse(typeof(ScopedItemOptions), psObject.Properties["Options"].Value.ToString()); PSVariable reconstructedVar = new( psObject.Properties["Name"].Value.ToString(), psObject.Properties["Value"].Value, options ); return(new VariableInfo(psObject.TypeNames.ToArray(), reconstructedVar)); } return(null); }
internal AliasInfo( string name, string definition, ExecutionContext context, ScopedItemOptions options) : base(name, CommandTypes.Alias) { if (string.IsNullOrEmpty(definition)) { throw AliasInfo.tracer.NewArgumentException(nameof(definition)); } if (context == null) { throw AliasInfo.tracer.NewArgumentNullException(nameof(context)); } this._definition = definition; this._context = context; this.options = options; this.SetModule(context.SessionState.Internal.Module); }
public PSScriptRunner(PSScriptRunnerPreferences prefs) : base() { _prefs = prefs; /* MTH: Throw an exception if there is an error when opening a runspace. This is FALSE by default. * This is set because if this is FALSE, PowerShell does not report anything about broken modules. */ _initialSessionState.ThrowOnRunspaceOpenError = true; //Replace PSAuthorizationManager with a null manager which ignores execution policy. //This is required because else no script will be allowed to run if ExecutionPoliy is not at least RemoteSigned. //Because we do not set our own ShellId, the parameter is set to "Microsoft.PowerShell" //Source: [Bypassing Restricted Execution Policy in Code or in Script](http://www.nivot.org/blog/post/2012/02/10/Bypassing-Restricted-Execution-Policy-in-Code-or-in-Script) by Nivot Ink _initialSessionState.AuthorizationManager = new System.Management.Automation.AuthorizationManager("Microsoft.PowerShell"); //Import modules if a module path is set if (string.IsNullOrWhiteSpace(prefs.ModulePath) == false) { _initialSessionState.ImportPSModulesFromPath(prefs.ModulePath); } //Set variables (if any) foreach (VariablePlain var in _prefs.Variables) { //Variables are always created with AllScope because it should be visible and writable even if a script runs another script using: & "otherscript.ps1" ScopedItemOptions scopeOptions = ScopedItemOptions.AllScope; //Docs: http://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k%28System.Management.Automation.ScopedItemOptions%29;k%28TargetFrameworkMoniker-.NETFramework if (var.ReadOnly) { //.ReadOnly would also be an option but .ReadOnly variables can be removed while constanct can not scopeOptions = scopeOptions | ScopedItemOptions.Constant; //If trying to write to a variable with .Constanct set, PowerShell will issue the error: Cannot overwrite variable NAME because it is read-only or constant. } _initialSessionState.Variables.Add(new SessionStateVariableEntry(var.Name, var.Value, string.Empty, scopeOptions)); } //MTH: If we every want to change the value of $WarningPreference, $VerbosePreference or $DebugPreference, this can be done by using _initialSessionState.Variables }
public SessionStateCapacityVariable( string name, SessionStateCapacityVariable sharedCapacityVariable, ScopedItemOptions options) : base(name, sharedCapacityVariable.Value, options) { // Now add range constraints to the variable. ValidateRangeAttribute validateRange = new ValidateRangeAttribute(0, int.MaxValue); base.Attributes.Add(validateRange); _sharedCapacityVariable = sharedCapacityVariable; // Also propagate the description to prevent re-fetching them from the // resource manager. That causes a measurable performance degradation. this.Description = sharedCapacityVariable.Description; // Initialize the fast value... _fastValue = (int)sharedCapacityVariable.Value; }
/// <summary> /// Sets the alias with specified name to the specified value in the current scope. /// </summary> /// /// <param name="aliasName"> /// The name of the alias to set. /// </param> /// /// <param name="value"> /// The value to set the alias to. /// </param> /// /// <param name="options"> /// The options to set on the alias. /// </param> /// /// <param name="force"> /// If true, the value will be set even if the alias is ReadOnly. /// </param> /// /// <param name="origin"> /// The origin of the caller of this API /// </param> /// /// <returns> /// The resulting AliasInfo for the alias that was set. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="aliasName"/> or <paramref name="value"/> is null or empty. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the alias is read-only or constant. /// </exception> /// internal AliasInfo SetAliasValue( string aliasName, string value, ScopedItemOptions options, bool force, CommandOrigin origin) { if (String.IsNullOrEmpty(aliasName)) { throw PSTraceSource.NewArgumentException("aliasName"); } if (String.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentException("value"); } AliasInfo info = _currentScope.SetAliasValue(aliasName, value, options, this.ExecutionContext, force, origin); return(info); } // SetAliasValue
public PSVariable(string name, object value, ScopedItemOptions options, Collection<Attribute> attributes) { if (string.IsNullOrEmpty(name)) { throw new NullReferenceException("Variable name can't be empty"); } Name = name; Description = string.Empty; Value = value; Options = options; // Copy attributes Attributes = new Collection<Attribute>(); if (attributes != null) { foreach (Attribute attribute in attributes) { Attributes.Add(attribute); } } }
public PSVariable(string name, object value, ScopedItemOptions options, Collection <Attribute> attributes) { if (string.IsNullOrEmpty(name)) { throw new NullReferenceException("Variable name can't be empty"); } Name = name; Description = string.Empty; Value = value; Options = options; // Copy attributes Attributes = new Collection <Attribute>(); if (attributes != null) { foreach (Attribute attribute in attributes) { Attributes.Add(attribute); } } }
internal void SetOptions(ScopedItemOptions newOptions, bool force) { if ((this.options & ScopedItemOptions.Constant) != ScopedItemOptions.None) { SessionStateUnauthorizedAccessException exception = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasIsConstant", SessionStateStrings.AliasIsConstant); throw exception; } if (!force && ((this.options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None)) { SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasIsReadOnly", SessionStateStrings.AliasIsReadOnly); throw exception2; } if ((newOptions & ScopedItemOptions.Constant) != ScopedItemOptions.None) { SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasCannotBeMadeConstant", SessionStateStrings.AliasCannotBeMadeConstant); throw exception3; } if (((newOptions & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && ((this.options & ScopedItemOptions.AllScope) != ScopedItemOptions.None)) { SessionStateUnauthorizedAccessException exception4 = new SessionStateUnauthorizedAccessException(base.Name, SessionStateCategory.Alias, "AliasAllScopeOptionCannotBeRemoved", SessionStateStrings.AliasAllScopeOptionCannotBeRemoved); throw exception4; } this.options = newOptions; }
/// <summary> /// Constructs a variable with the given name, value, options, and attributes /// </summary> /// <param name="name"> /// The name of the variable. /// </param> /// <param name="value"> /// The value of the variable. /// </param> /// <param name="options"> /// The constraints of the variable. Note, variables can only be made constant /// in the constructor. /// </param> /// <param name="attributes"> /// The attributes for the variable. ValidateArgumentsAttribute and derived types /// will be used to validate a value before setting it. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="ValidationMetadataException"> /// If the validation metadata identified in <paramref name="attributes"/> /// throws an exception. /// </exception> public PSVariable( string name, object value, ScopedItemOptions options, Collection <Attribute> attributes) { if (String.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } Name = name; _attributes = new PSVariableAttributeCollection(this); // Note, it is OK to set the value before setting the attributes // because each attribute will be validated as it is set. SetValueRawImpl(value, true); if (attributes != null) { foreach (Attribute attribute in attributes) { _attributes.Add(attribute); } } // Set the options after setting the initial value. _options = options; if (IsAllScope) { Language.VariableAnalysis.NoteAllScopeVariable(name); } }
private SessionStateVariableEntry CreateSessionStateVariableEntry(Hashtable variable) { string str = TryGetValue(variable, ConfigFileContants.VariableNameToken); if (string.IsNullOrEmpty(str)) { return(null); } string str2 = TryGetValue(variable, ConfigFileContants.VariableValueToken); if (string.IsNullOrEmpty(str2)) { return(null); } string description = TryGetValue(variable, ConfigFileContants.AliasDescriptionToken); ScopedItemOptions none = ScopedItemOptions.None; string str4 = TryGetValue(variable, ConfigFileContants.AliasOptionsToken); if (!string.IsNullOrEmpty(str4)) { none = (ScopedItemOptions)Enum.Parse(typeof(ScopedItemOptions), str4, true); } return(new SessionStateVariableEntry(str, str2, description, none, new Collection <Attribute>(), SessionStateEntryVisibility.Public)); }
public PSVariable(string name, object value, ScopedItemOptions options, Collection<Attribute> attributes) { this.name = string.Empty; this.description = string.Empty; if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } this.name = name; this.attributes = new PSVariableAttributeCollection(this); this.SetValueRawImpl(value, true); if (attributes != null) { foreach (Attribute attribute in attributes) { this.attributes.Add(attribute); } } this.options = options; if (this.IsAllScope) { VariableAnalysis.NoteAllScopeVariable(name); } }
public PSVariable(string name, object value, ScopedItemOptions options, Collection <Attribute> attributes) { this.name = string.Empty; this.description = string.Empty; if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } this.name = name; this.attributes = new PSVariableAttributeCollection(this); this.SetValueRawImpl(value, true); if (attributes != null) { foreach (Attribute attribute in attributes) { this.attributes.Add(attribute); } } this.options = options; if (this.IsAllScope) { VariableAnalysis.NoteAllScopeVariable(name); } }
} // workflowInfo ctor /// <summary> /// Creates an instance of the WorkflowInfo class with the specified name and ScriptBlock /// </summary> /// /// <param name="name"> /// The name of the workflow. /// </param> /// /// <param name="workflow"> /// The ScriptBlock for the workflow /// </param> /// /// <param name="options"> /// The options to set on the function. Note, Constant can only be set at creation time. /// </param> /// /// <param name="context"> /// The execution context for the workflow. /// </param> /// /// <param name="helpFile"> /// The helpfile for the workflow. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="workflow"/> is null. /// </exception> /// internal WorkflowInfo(string name, ScriptBlock workflow, ScopedItemOptions options, ExecutionContext context, string helpFile) : base(name, workflow, options, context, helpFile) { SetCommandType(CommandTypes.Workflow); } // workflowInfo ctor
/// <summary> /// Creates an instance of the WorkflowInfo class with the specified name and ScriptBlock /// </summary> /// /// <param name="name"> /// The name of the workflow. /// </param> /// /// <param name="workflow"> /// The ScriptBlock for the workflow /// </param> /// /// <param name="options"> /// The options to set on the function. Note, Constant can only be set at creation time. /// </param> /// /// <param name="context"> /// The execution context for the workflow. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="workflow"/> is null. /// </exception> /// internal WorkflowInfo(string name, ScriptBlock workflow, ScopedItemOptions options, ExecutionContext context) : this(name, workflow, options, context, null) { } // workflowInfo ctor
} // SetSessionStateItem #pragma warning restore 0162 private static void SetOptions(CommandInfo function, ScopedItemOptions options) { ((FunctionInfo)function).Options = options; }
} // GetSessionStateItem /// <summary> /// Sets the function of the specified name to the specified value /// </summary> /// /// <param name="name"> /// The name of the function to set. /// </param> /// /// <param name="value"> /// The new value for the function. /// </param> /// /// <param name="writeItem"> /// If true, the item that was set should be written to WriteItemObject. /// </param> /// #pragma warning disable 0162 internal override void SetSessionStateItem(string name, object value, bool writeItem) { Dbg.Diagnostics.Assert( !String.IsNullOrEmpty(name), "The caller should verify this parameter"); FunctionProviderDynamicParameters dynamicParameters = DynamicParameters as FunctionProviderDynamicParameters; CommandInfo modifiedItem = null; bool dynamicParametersSpecified = dynamicParameters != null && dynamicParameters.OptionsSet; if (value == null) { // If the value wasn't specified but the options were, just set the // options on the existing function. // If the options weren't specified, then remove the function if (dynamicParametersSpecified) { modifiedItem = (CommandInfo)GetSessionStateItem(name); if (modifiedItem != null) { SetOptions(modifiedItem, dynamicParameters.Options); } } else { RemoveSessionStateItem(name); } } else { do // false loop { // Unwrap the PSObject before binding it as a scriptblock... PSObject pso = value as PSObject; if (pso != null) { value = pso.BaseObject; } ScriptBlock scriptBlockValue = value as ScriptBlock; if (scriptBlockValue != null) { if (dynamicParametersSpecified) { modifiedItem = SessionState.Internal.SetFunction(name, scriptBlockValue, null, dynamicParameters.Options, Force, Context.Origin); } else { modifiedItem = SessionState.Internal.SetFunction(name, scriptBlockValue, null, Force, Context.Origin); } break; } FunctionInfo function = value as FunctionInfo; if (function != null) { ScopedItemOptions options = function.Options; if (dynamicParametersSpecified) { options = dynamicParameters.Options; } modifiedItem = SessionState.Internal.SetFunction(name, function.ScriptBlock, function, options, Force, Context.Origin); break; } String stringValue = value as string; if (stringValue != null) { ScriptBlock scriptBlock = ScriptBlock.Create(Context.ExecutionContext, stringValue); if (dynamicParametersSpecified) { modifiedItem = SessionState.Internal.SetFunction(name, scriptBlock, null, dynamicParameters.Options, Force, Context.Origin); } else { modifiedItem = SessionState.Internal.SetFunction(name, scriptBlock, null, Force, Context.Origin); } break; } throw PSTraceSource.NewArgumentException("value"); } while (false); if (writeItem && modifiedItem != null) { WriteItemObject(modifiedItem, modifiedItem.Name, false); } } } // SetSessionStateItem
/// <summary> /// Sets the options for the alias and allows changes ReadOnly options only if force is specified. /// </summary> /// /// <param name="newOptions"> /// The new options value. /// </param> /// /// <param name="force"> /// If true the change to the options will happen even if the existing options are read-only. /// </param> /// internal void SetOptions(ScopedItemOptions newOptions, bool force) { // Check to see if the variable is constant, if so // throw an exception because the options cannot be changed. if ((_options & ScopedItemOptions.Constant) != 0) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( Name, SessionStateCategory.Alias, "AliasIsConstant", SessionStateStrings.AliasIsConstant); throw e; } // Check to see if the variable is readonly, if so // throw an exception because the options cannot be changed. if (!force && (_options & ScopedItemOptions.ReadOnly) != 0) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( Name, SessionStateCategory.Alias, "AliasIsReadOnly", SessionStateStrings.AliasIsReadOnly); throw e; } // Now check to see if the caller is trying to set // the options to constant. This is only allowed at // variable creation if ((newOptions & ScopedItemOptions.Constant) != 0) { // user is trying to set the variable to constant after // creating the variable. Do not allow this (as per spec). SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( Name, SessionStateCategory.Alias, "AliasCannotBeMadeConstant", SessionStateStrings.AliasCannotBeMadeConstant); throw e; } if ((newOptions & ScopedItemOptions.AllScope) == 0 && (_options & ScopedItemOptions.AllScope) != 0) { // user is trying to remove the AllScope option from the alias. // Do not allow this (as per spec). SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( this.Name, SessionStateCategory.Alias, "AliasAllScopeOptionCannotBeRemoved", SessionStateStrings.AliasAllScopeOptionCannotBeRemoved); throw e; } _options = newOptions; }
/// <summary/> protected internal virtual void Update(FunctionInfo newFunction, bool force, ScopedItemOptions options, string helpFile) { Update(newFunction.ScriptBlock, force, options, helpFile); }
/// <summary> /// Updates a function. /// </summary> /// <param name="newFunction"> /// The script block that the function should represent. /// </param> /// <param name="force"> /// If true, the script block will be applied even if the filter is ReadOnly. /// </param> /// <param name="options"> /// Any options to set on the new function, null if none. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="newFunction"/> is null. /// </exception> internal void Update(ScriptBlock newFunction, bool force, ScopedItemOptions options) { Update(newFunction, force, options, null); this.DefiningLanguageMode = newFunction.LanguageMode; }
/// <summary> /// Set a function in the current scope of session state. /// </summary> /// <param name="name"> /// The name of the function to set. /// </param> /// <param name="function"> /// The new value of the function being set. /// </param> /// <param name="originalFunction"> /// The original function (if any) from which the ScriptBlock is derived. /// </param> /// <param name="force"> /// If true, the function will be set even if its ReadOnly. /// </param> /// <param name="origin"> /// The origin of the caller /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// or /// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see> /// or <see cref="FunctionInfo">FunctionInfo</see> /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the function is read-only or constant. /// </exception> internal FunctionInfo SetFunction( string name, ScriptBlock function, FunctionInfo originalFunction, bool force, CommandOrigin origin) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } if (function == null) { throw PSTraceSource.NewArgumentNullException("function"); } string originalName = name; FunctionLookupPath path = new FunctionLookupPath(name); name = path.UnqualifiedPath; if (string.IsNullOrEmpty(name)) { SessionStateException exception = new SessionStateException( originalName, SessionStateCategory.Function, "ScopedFunctionMustHaveName", SessionStateStrings.ScopedFunctionMustHaveName, ErrorCategory.InvalidArgument); throw exception; } ScopedItemOptions options = ScopedItemOptions.None; if (path.IsPrivate) { options |= ScopedItemOptions.Private; } FunctionScopeItemSearcher searcher = new FunctionScopeItemSearcher( this, path, origin); FunctionInfo result = null; SessionStateScope scope = searcher.InitialScope; if (searcher.MoveNext()) { scope = searcher.CurrentLookupScope; name = searcher.Name; if (path.IsPrivate) { // Need to add the Private flag FunctionInfo existingFunction = scope.GetFunction(name); options |= existingFunction.Options; result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext); } else { result = scope.SetFunction(name, function, force, origin, ExecutionContext); } } else { if (path.IsPrivate) { result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext); } else { result = scope.SetFunction(name, function, force, origin, ExecutionContext); } } return(result); }
/// <summary> /// Sets the variables of the given names to the specified value. /// </summary> /// <param name="varNames"> /// The name(s) of the variables to set. /// </param> /// <param name="varValue"> /// The value to set the variable to. /// </param> private void SetVariable(string[] varNames, object varValue) { CommandOrigin origin = MyInvocation.CommandOrigin; foreach (string varName in varNames) { // First look for existing variables to set. List <PSVariable> matchingVariables = new List <PSVariable>(); bool wasFiltered = false; if (!string.IsNullOrEmpty(Scope)) { // We really only need to find matches if the scope was specified. // If the scope wasn't specified then we need to create the // variable in the local scope. matchingVariables = GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false); } else { // Since the scope wasn't specified, it doesn't matter if there // is a variable in another scope, it only matters if there is a // variable in the local scope. matchingVariables = GetMatchingVariables( varName, System.Management.Automation.StringLiterals.Local, out wasFiltered, false); } // We only want to create the variable if we are not filtering // the name. if (matchingVariables.Count == 0 && !wasFiltered) { try { ScopedItemOptions newOptions = ScopedItemOptions.None; if (!string.IsNullOrEmpty(Scope) && string.Equals("private", Scope, StringComparison.OrdinalIgnoreCase)) { newOptions = ScopedItemOptions.Private; } if (_options != null) { newOptions |= (ScopedItemOptions)_options; } object newVarValue = varValue; if (newVarValue == AutomationNull.Value) { newVarValue = null; } PSVariable varToSet = new PSVariable( varName, newVarValue, newOptions); if (Description == null) { Description = string.Empty; } varToSet.Description = Description; // If visibility was specified, set it on the variable if (_visibility != null) { varToSet.Visibility = Visibility; } string action = VariableCommandStrings.SetVariableAction; string target = StringUtil.Format(VariableCommandStrings.SetVariableTarget, varName, newVarValue); if (ShouldProcess(target, action)) { object result = null; if (string.IsNullOrEmpty(Scope)) { result = SessionState.Internal.SetVariable(varToSet, Force, origin); } else { result = SessionState.Internal.SetVariableAtScope(varToSet, Scope, Force, origin); } if (_passThru && result != null) { WriteObject(result); } } } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); continue; } catch (PSArgumentException argException) { WriteError( new ErrorRecord( argException.ErrorRecord, argException)); continue; } } else { foreach (PSVariable matchingVariable in matchingVariables) { string action = VariableCommandStrings.SetVariableAction; string target = StringUtil.Format(VariableCommandStrings.SetVariableTarget, matchingVariable.Name, varValue); if (ShouldProcess(target, action)) { object result = null; try { // Since the variable existed in the specified scope, or // in the local scope if no scope was specified, use // the reference returned to set the variable properties. // If we want to force setting over a readonly variable // we have to temporarily mark the variable writable. bool wasReadOnly = false; if (Force && (matchingVariable.Options & ScopedItemOptions.ReadOnly) != 0) { matchingVariable.SetOptions(matchingVariable.Options & ~ScopedItemOptions.ReadOnly, true); wasReadOnly = true; } // Now change the value, options, or description // and set the variable if (varValue != AutomationNull.Value) { matchingVariable.Value = varValue; if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { // In 'ConstrainedLanguage' we want to monitor untrusted values assigned to 'Global:' variables // and 'Script:' variables, because they may be set from 'ConstrainedLanguage' environment and // referenced within trusted script block, and thus result in security issues. // Here we are setting the value of an existing variable and don't know what scope this variable // is from, so we mark the value as untrusted, regardless of the scope. ExecutionContext.MarkObjectAsUntrusted(matchingVariable.Value); } } if (Description != null) { matchingVariable.Description = Description; } if (_options != null) { matchingVariable.Options = (ScopedItemOptions)_options; } else { if (wasReadOnly) { matchingVariable.SetOptions(matchingVariable.Options | ScopedItemOptions.ReadOnly, true); } } // If visibility was specified, set it on the variable if (_visibility != null) { matchingVariable.Visibility = Visibility; } result = matchingVariable; } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); continue; } catch (PSArgumentException argException) { WriteError( new ErrorRecord( argException.ErrorRecord, argException)); continue; } if (_passThru && result != null) { WriteObject(result); } } } } } }
/// <summary> /// Creates an instance of the FunctionInfo class with the specified name and ScriptBlock. /// </summary> /// <param name="name"> /// The name of the function. /// </param> /// <param name="function"> /// The ScriptBlock for the function /// </param> /// <param name="options"> /// The options to set on the function. Note, Constant can only be set at creation time. /// </param> /// <param name="context"> /// The execution context for the function. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> internal FunctionInfo(string name, ScriptBlock function, ScopedItemOptions options, ExecutionContext context) : this(name, function, options, context, null) { }