protected override void ProcessRecord() { AliasInfo alias = new AliasInfo(base.Name, base.Value, base.Context, base.Option) { Description = base.Description }; string setAliasAction = AliasCommandStrings.SetAliasAction; string target = StringUtil.Format(AliasCommandStrings.SetAliasTarget, base.Name, base.Value); if (base.ShouldProcess(target, setAliasAction)) { AliasInfo sendToPipeline = null; try { if (string.IsNullOrEmpty(base.Scope)) { sendToPipeline = base.SessionState.Internal.SetAliasItem(alias, (bool) base.Force, base.MyInvocation.CommandOrigin); } else { sendToPipeline = base.SessionState.Internal.SetAliasItemAtScope(alias, base.Scope, (bool) base.Force, base.MyInvocation.CommandOrigin); } } catch (SessionStateException exception) { base.WriteError(new ErrorRecord(exception.ErrorRecord, exception)); return; } if ((base.PassThru != 0) && (sendToPipeline != null)) { base.WriteObject(sendToPipeline); } } }
private AliasHelpInfo(AliasInfo aliasInfo) { _fullHelpObject = new PSObject(); string name = (aliasInfo.ResolvedCommand == null) ? aliasInfo.UnresolvedCommandName : aliasInfo.ResolvedCommand.Name; this.ForwardTarget = name; // A Cmdlet/Function/Script etc can have alias. this.ForwardHelpCategory = HelpCategory.Cmdlet | HelpCategory.Function | HelpCategory.ExternalScript | HelpCategory.ScriptCommand | HelpCategory.Filter | HelpCategory.Workflow; if (!String.IsNullOrEmpty(aliasInfo.Name)) { Name = aliasInfo.Name.Trim(); } if (!String.IsNullOrEmpty(name)) { Synopsis = name.Trim(); } _fullHelpObject.TypeNames.Clear(); _fullHelpObject.TypeNames.Add(string.Format(Globalization.CultureInfo.InvariantCulture, "AliasHelpInfo#{0}", Name)); _fullHelpObject.TypeNames.Add("AliasHelpInfo"); _fullHelpObject.TypeNames.Add("HelpInfo"); }
/// <summary> /// Add a new alias entry to this session state object... /// </summary> /// <param name="entry">The entry to add</param> /// <param name="scopeID"> /// A scope identifier that is either one of the "special" scopes like /// "global", "script", "local", or "private, or a numeric ID of a relative scope /// to the current scope. /// </param> internal void AddSessionStateEntry(SessionStateAliasEntry entry, string scopeID) { AliasInfo alias = new AliasInfo(entry.Name, entry.Definition, this.ExecutionContext, entry.Options) { Visibility = entry.Visibility, Module = entry.Module, Description = entry.Description }; // Create alias in the global scope... this.SetAliasItemAtScope(alias, scopeID, true, CommandOrigin.Internal); }
/// <summary> /// The main processing loop of the command. /// </summary> /// protected override void ProcessRecord() { // Create the alias info AliasInfo aliasToSet = new AliasInfo( Name, Value, Context, Option); aliasToSet.Description = Description; string action = AliasCommandStrings.SetAliasAction; string target = StringUtil.Format(AliasCommandStrings.SetAliasTarget, Name, Value); if (ShouldProcess(target, action)) { // Set the alias in the specified scope or the // current scope. AliasInfo result = null; try { if (String.IsNullOrEmpty(Scope)) { result = SessionState.Internal.SetAliasItem(aliasToSet, Force, MyInvocation.CommandOrigin); } else { result = SessionState.Internal.SetAliasItemAtScope(aliasToSet, Scope, Force, MyInvocation.CommandOrigin); } } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); return; } // Write the alias to the pipeline if PassThru was specified if (PassThru && result != null) { WriteObject(result); } } } // ProcessRecord
private Collection<AliasInfo> GetAliasesFromFile(bool isLiteralPath) { Collection<AliasInfo> collection = new Collection<AliasInfo>(); string filePath = null; using (StreamReader reader = this.OpenFile(out filePath, isLiteralPath)) { CSVHelper helper = new CSVHelper(','); long num = 0L; string line = null; while ((line = reader.ReadLine()) != null) { num += 1L; if (((line.Length != 0) && !OnlyContainsWhitespace(line)) && (line[0] != '#')) { Collection<string> collection2 = helper.ParseCsv(line); if (collection2.Count != 4) { string message = StringUtil.Format(AliasCommandStrings.ImportAliasFileInvalidFormat, filePath, num); FormatException exception = new FormatException(message); ErrorRecord errorRecord = new ErrorRecord(exception, "ImportAliasFileFormatError", ErrorCategory.ReadError, filePath) { ErrorDetails = new ErrorDetails(message) }; base.ThrowTerminatingError(errorRecord); } ScopedItemOptions none = ScopedItemOptions.None; try { none = (ScopedItemOptions) Enum.Parse(typeof(ScopedItemOptions), collection2[3], true); } catch (ArgumentException exception2) { string str4 = StringUtil.Format(AliasCommandStrings.ImportAliasOptionsError, filePath, num); ErrorRecord record2 = new ErrorRecord(exception2, "ImportAliasOptionsError", ErrorCategory.ReadError, filePath) { ErrorDetails = new ErrorDetails(str4) }; base.WriteError(record2); continue; } AliasInfo item = new AliasInfo(collection2[0], collection2[1], base.Context, none); if (!string.IsNullOrEmpty(collection2[2])) { item.Description = collection2[2]; } collection.Add(item); } } reader.Close(); } return collection; }
public void SetUpRunspace() { TestHost host = new TestHost(new TestHostUserInterface()); // use public static property, so we can access e.g. the ExecutionContext after execution _runspace = RunspaceFactory.CreateRunspace(host) as LocalRunspace; _runspace.Open(); var alias = new AliasInfo("gciAlias", "Get-ChildItem", _runspace.CommandManager); _runspace.ExecutionContext.SessionState.Alias.New(alias, "global"); _runspace.ExecutionContext.SessionState.Function.Set("MyFunction", new ScriptBlock(null)); _runspace.ExecutionContext.SessionState.PSVariable.Set("myvar", 1); var newScope = _runspace.ExecutionContext.Clone(ScopeUsages.NewScope); newScope.SessionState.PSVariable.Set("myothervar", 2); newScope.SessionState.Function.Set("MyFun2", new ScriptBlock(null)); _runspace.ExecutionContext = newScope; _tabExp = new TabExpansionProvider(_runspace); }
internal static AliasHelpInfo GetHelpInfo(AliasInfo aliasInfo) { if (aliasInfo == null) { return null; } if ((aliasInfo.ResolvedCommand == null) && (aliasInfo.UnresolvedCommandName == null)) { return null; } AliasHelpInfo info = new AliasHelpInfo(aliasInfo); if (string.IsNullOrEmpty(info.Name)) { return null; } info.AddCommonHelpProperties(); return info; }
private AliasHelpInfo(AliasInfo aliasInfo) { string str = (aliasInfo.ResolvedCommand == null) ? aliasInfo.UnresolvedCommandName : aliasInfo.ResolvedCommand.Name; base.ForwardTarget = str; base.ForwardHelpCategory = System.Management.Automation.HelpCategory.Workflow | System.Management.Automation.HelpCategory.ExternalScript | System.Management.Automation.HelpCategory.Filter | System.Management.Automation.HelpCategory.Function | System.Management.Automation.HelpCategory.ScriptCommand | System.Management.Automation.HelpCategory.Cmdlet; if (!string.IsNullOrEmpty(aliasInfo.Name)) { this._name = aliasInfo.Name.Trim(); } if (!string.IsNullOrEmpty(str)) { this._synopsis = str.Trim(); } this._fullHelpObject.TypeNames.Clear(); this._fullHelpObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "AliasHelpInfo#{0}", new object[] { this.Name })); this._fullHelpObject.TypeNames.Add("AliasHelpInfo"); this._fullHelpObject.TypeNames.Add("HelpInfo"); }
internal override void SetSessionStateItem(string name, object value, bool writeItem) { Path path = PathIntrinsics.RemoveDriveName(name); path = path.TrimStartSlash(); if (value is Array) { var array = (Array)value; if (array.Length > 1) { throw new PSArgumentException("value"); } value = array.GetValue(0); } var aliasInfo = new AliasInfo(path, value.ToString(), null); SessionState.Alias.Set(aliasInfo, "global"); var a = SessionState.Alias.Get(path); Console.WriteLine(a.Definition); }
private Collection<AliasInfo> GetAliasesFromFile(bool isLiteralPath) { Collection<AliasInfo> result = new Collection<AliasInfo>(); string filePath = null; using (StreamReader reader = OpenFile(out filePath, isLiteralPath)) { CSVHelper csvHelper = new CSVHelper(','); Int64 lineNumber = 0; string line = null; while ((line = reader.ReadLine()) != null) { ++lineNumber; // Ignore blank lines if (line.Length == 0) { continue; } // Ignore lines that only contain whitespace if (OnlyContainsWhitespace(line)) { continue; } // Ignore comment lines if (line[0] == '#') { continue; } Collection<string> values = csvHelper.ParseCsv(line); if (values.Count != 4) { string message = StringUtil.Format(AliasCommandStrings.ImportAliasFileInvalidFormat, filePath, lineNumber); FormatException formatException = new FormatException(message); ErrorRecord errorRecord = new ErrorRecord( formatException, "ImportAliasFileFormatError", ErrorCategory.ReadError, filePath); errorRecord.ErrorDetails = new ErrorDetails(message); ThrowTerminatingError(errorRecord); } ScopedItemOptions options = ScopedItemOptions.None; try { options = (ScopedItemOptions)Enum.Parse(typeof(ScopedItemOptions), values[3], true); } catch (ArgumentException argException) { string message = StringUtil.Format(AliasCommandStrings.ImportAliasOptionsError, filePath, lineNumber); ErrorRecord errorRecord = new ErrorRecord( argException, "ImportAliasOptionsError", ErrorCategory.ReadError, filePath); errorRecord.ErrorDetails = new ErrorDetails(message); WriteError(errorRecord); continue; } AliasInfo newAlias = new AliasInfo( values[0], values[1], Context, options); if (!String.IsNullOrEmpty(values[2])) { newAlias.Description = values[2]; } result.Add(newAlias); } reader.Dispose(); } return result; }
protected override void ProcessRecord() { AliasInfo info = new AliasInfo(Name, Value, SessionState.SessionStateGlobal.CommandManager, Option); SessionState.Alias.Set(info, Scope); }
public CommandManager(ExecutionContext context) { _context = context; _snapins = new Dictionary<string, PSSnapInInfo>(StringComparer.CurrentCultureIgnoreCase); _cmdLets = new Dictionary<string, List<CmdletInfo>>(StringComparer.CurrentCultureIgnoreCase); _scripts = new Dictionary<string, ScriptInfo>(StringComparer.CurrentCultureIgnoreCase); _aliases = new Dictionary<string, AliasInfo>(StringComparer.CurrentCultureIgnoreCase); _providers = new Collection<SnapinProviderPair>(); // if no execution scope is provided load all the initial settings from the config file if (context == null) { ExecutionContextConfigurationSection configSection = System.Configuration.ConfigurationManager.GetSection("defaultExecutionContext") as ExecutionContextConfigurationSection; if (configSection != null) { if (configSection.PSSnapins != null) { foreach (PSSnapinElement snapin in configSection.PSSnapins) { var tmpProviders = new Collection<SnapinProviderPair>(); // Load all PSSnapin's foreach (CmdletInfo cmdLetInfo in LoadCmdletsFromPSSnapin(snapin.type, out tmpProviders)) { // Register PSSnapin if (_snapins.ContainsKey(cmdLetInfo.PSSnapIn.Name)) { _snapins.Add(cmdLetInfo.PSSnapIn.Name, cmdLetInfo.PSSnapIn); } // Copy all the found Cmdlets List<CmdletInfo> cmdletList = null; if (_cmdLets.ContainsKey(cmdLetInfo.Name)) { cmdletList = _cmdLets[cmdLetInfo.Name]; } else { cmdletList = new List<CmdletInfo>(); _cmdLets.Add(cmdLetInfo.Name, cmdletList); } cmdletList.Add(cmdLetInfo); } foreach (SnapinProviderPair providerTypePair in tmpProviders) { _providers.Add(providerTypePair); } } } // copy functions if (configSection.Functions != null) { // TODO: resolve the difference between the function and a script? foreach (FunctionElement function in configSection.Functions) { ScriptInfo scriptInfo = null; switch (function.type) { case "inline": scriptInfo = new ScriptInfo(function.name, new ScriptBlock(context, function.value)); break; case "file": // TODO: read the function from a file break; } if (scriptInfo != null) _scripts.Add(scriptInfo.Name, scriptInfo); } } if (configSection.Aliases != null) { // TODO: cache aliases foreach (AliasElement alias in configSection.Aliases) { AliasInfo aliasInfo = new AliasInfo(alias.name, alias.definition, this); if (aliasInfo != null) _aliases.Add(aliasInfo.Name, aliasInfo); } } // fill variables into the execution scope if (_context != null) { if (configSection.Variables != null) { // TODO: prepopulate variables list } // TODO: copy all the variables from the environment } } } }
} // SetAliasItemAtScope /// <summary> /// Sets the alias with specified name to the specified value in the current scope. /// </summary> /// /// <param name="alias"> /// The AliasInfo representing the alias. /// </param> /// /// <param name="scopeID"> /// A scope identifier that is either one of the "special" scopes like /// "global", "script", "local", or "private, or a numeric ID of a relative scope /// to the current scope. /// </param> /// /// <param name="force"> /// If true, the alias will be set even if there is an existing ReadOnly /// alias. /// </param> /// /// <returns> /// The resulting AliasInfo for the alias that was set. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="scopeID"/> is less than zero, or not /// a number and not "script", "global", "local", or "private" /// </exception> /// /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently /// active scopes. /// </exception> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="alias"/> is null. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the alias is read-only or constant. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If the maximum number of aliases has been reached for this scope. /// </exception> /// internal AliasInfo SetAliasItemAtScope(AliasInfo alias, string scopeID, bool force) { return SetAliasItemAtScope(alias, scopeID, force, CommandOrigin.Internal); }
} // SetAliasItem /// <summary> /// Sets the alias with specified name to the specified value in the current scope. /// </summary> /// /// <param name="alias"> /// The AliasInfo representing the alias. /// </param> /// /// <param name="scopeID"> /// A scope identifier that is either one of the "special" scopes like /// "global", "script", "local", or "private, or a numeric ID of a relative scope /// to the current scope. /// </param> /// /// <param name="force"> /// If true, the alias will be set even if there is an existing ReadOnly /// alias. /// </param> /// /// <param name="origin"> /// Specifies the command origin of the calling command. /// </param> /// /// <returns> /// The resulting AliasInfo for the alias that was set. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="scopeID"/> is less than zero, or not /// a number and not "script", "global", "local", or "private" /// </exception> /// /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently /// active scopes. /// </exception> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="alias"/> is null. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the alias is read-only or constant. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If the maximum number of aliases has been reached for this scope. /// </exception> /// internal AliasInfo SetAliasItemAtScope(AliasInfo alias, string scopeID, bool force, CommandOrigin origin) { if (alias == null) { throw PSTraceSource.NewArgumentNullException("alias"); } // If the "private" scope was specified, make sure the options contain // the Private flag if (String.Equals(scopeID, StringLiterals.Private, StringComparison.OrdinalIgnoreCase)) { alias.Options |= ScopedItemOptions.Private; } SessionStateScope scope = GetScopeByID(scopeID); AliasInfo info = scope.SetAliasItem(alias, force, origin); return info; } // SetAliasItemAtScope
public void Set(AliasInfo info, string scope) { _scope.SetAtScope(info, scope, true); }
/// <summary> /// The main processing loop of the command. /// </summary> /// protected override void ProcessRecord() { // If not force, then see if the alias already exists if (!Force) { AliasInfo existingAlias = null; if (String.IsNullOrEmpty(Scope)) { existingAlias = SessionState.Internal.GetAlias(Name); } else { existingAlias = SessionState.Internal.GetAliasAtScope(Name, Scope); } if (existingAlias != null) { // Throw if alias exists and is private... SessionState.ThrowIfNotVisible(this.CommandOrigin, existingAlias); // Since the alias already exists, write an error. SessionStateException aliasExists = new SessionStateException( Name, SessionStateCategory.Alias, "AliasAlreadyExists", SessionStateStrings.AliasAlreadyExists, ErrorCategory.ResourceExists); WriteError( new ErrorRecord( aliasExists.ErrorRecord, aliasExists)); return; } } // Create the alias info AliasInfo newAlias = new AliasInfo( Name, Value, Context, Option); newAlias.Description = Description; string action = AliasCommandStrings.NewAliasAction; string target = StringUtil.Format(AliasCommandStrings.NewAliasTarget, Name, Value); if (ShouldProcess(target, action)) { // Set the alias in the specified scope or the // current scope. AliasInfo result = null; try { if (String.IsNullOrEmpty(Scope)) { result = SessionState.Internal.SetAliasItem(newAlias, Force, MyInvocation.CommandOrigin); } else { result = SessionState.Internal.SetAliasItemAtScope(newAlias, Scope, Force, MyInvocation.CommandOrigin); } } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); return; } catch (PSArgumentOutOfRangeException argOutOfRange) { WriteError( new ErrorRecord( argOutOfRange.ErrorRecord, argOutOfRange)); return; } catch (PSArgumentException argException) { WriteError( new ErrorRecord( argException.ErrorRecord, argException)); return; } // Write the alias to the pipeline if PassThru was specified if (PassThru && result != null) { WriteObject(result); } } } // ProcessRecord
private static string GetAliasLine(AliasInfo alias, string formatString) { return string.Format(CultureInfo.InvariantCulture, formatString, new object[] { alias.Name, alias.Definition, alias.Description, alias.Options }); }
} // GetValueOfItem /// <summary> /// Sets the alias of the specified name to the specified value /// </summary> /// /// <param name="name"> /// The name of the alias to set. /// </param> /// /// <param name="value"> /// The new value for the alias. /// </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"); AliasProviderDynamicParameters dynamicParameters = DynamicParameters as AliasProviderDynamicParameters; AliasInfo item = null; bool dynamicParametersSpecified = dynamicParameters != null && dynamicParameters.OptionsSet; if (value == null) { if (dynamicParametersSpecified) { item = (AliasInfo)GetSessionStateItem(name); if (item != null) { item.SetOptions(dynamicParameters.Options, Force); } } else { RemoveSessionStateItem(name); } } else { do // false loop { string stringValue = value as string; if (stringValue != null) { if (dynamicParametersSpecified) { item = SessionState.Internal.SetAliasValue(name, stringValue, dynamicParameters.Options, Force, Context.Origin); } else { item = SessionState.Internal.SetAliasValue(name, stringValue, Force, Context.Origin); } break; } AliasInfo alias = value as AliasInfo; if (alias != null) { AliasInfo newAliasInfo = new AliasInfo( name, alias.Definition, this.Context.ExecutionContext, alias.Options); if (dynamicParametersSpecified) { newAliasInfo.SetOptions(dynamicParameters.Options, Force); } item = SessionState.Internal.SetAliasItem(newAliasInfo, Force, Context.Origin); break; } throw PSTraceSource.NewArgumentException("value"); } while (false); } if (writeItem && item != null) { WriteItemObject(item, item.Name, false); } } // SetSessionStateItem
protected override void ProcessRecord() { if (base.Force == 0) { AliasInfo valueToCheck = null; if (string.IsNullOrEmpty(base.Scope)) { valueToCheck = base.SessionState.Internal.GetAlias(base.Name); } else { valueToCheck = base.SessionState.Internal.GetAliasAtScope(base.Name, base.Scope); } if (valueToCheck != null) { SessionState.ThrowIfNotVisible(base.CommandOrigin, valueToCheck); SessionStateException replaceParentContainsErrorRecordException = new SessionStateException(base.Name, SessionStateCategory.Alias, "AliasAlreadyExists", SessionStateStrings.AliasAlreadyExists, ErrorCategory.ResourceExists, new object[0]); base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException)); return; } } AliasInfo alias = new AliasInfo(base.Name, base.Value, base.Context, base.Option) { Description = base.Description }; string newAliasAction = AliasCommandStrings.NewAliasAction; string target = StringUtil.Format(AliasCommandStrings.NewAliasTarget, base.Name, base.Value); if (base.ShouldProcess(target, newAliasAction)) { AliasInfo sendToPipeline = null; try { if (string.IsNullOrEmpty(base.Scope)) { sendToPipeline = base.SessionState.Internal.SetAliasItem(alias, (bool) base.Force, base.MyInvocation.CommandOrigin); } else { sendToPipeline = base.SessionState.Internal.SetAliasItemAtScope(alias, base.Scope, (bool) base.Force, base.MyInvocation.CommandOrigin); } } catch (SessionStateException exception2) { base.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2)); return; } catch (PSArgumentOutOfRangeException exception3) { base.WriteError(new ErrorRecord(exception3.ErrorRecord, exception3)); return; } catch (PSArgumentException exception4) { base.WriteError(new ErrorRecord(exception4.ErrorRecord, exception4)); return; } if ((base.PassThru != 0) && (sendToPipeline != null)) { base.WriteObject(sendToPipeline); } } }
internal AliasInfo SetAliasItemAtScope(AliasInfo alias, string scopeID, bool force, CommandOrigin origin) { if (alias == null) { throw PSTraceSource.NewArgumentNullException("alias"); } if (string.Equals(scopeID, "PRIVATE", StringComparison.OrdinalIgnoreCase)) { alias.Options |= ScopedItemOptions.Private; } return this.GetScopeByID(scopeID).SetAliasItem(alias, force, origin); }
internal void AddSessionStateEntry(SessionStateAliasEntry entry) { AliasInfo alias = new AliasInfo(entry.Name, entry.Definition, this.ExecutionContext, entry.Options) { Visibility = entry.Visibility }; alias.SetModule(entry.Module); if (!string.IsNullOrEmpty(entry.Description)) { alias.Description = entry.Description; } this.SetAliasItemAtScope(alias, "global", true, CommandOrigin.Internal); }
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]; }
private static string GetAliasLine(AliasInfo alias, string formatString) { // Using the invariant culture here because we don't want the // file to vary based on locale. string result = String.Format( System.Globalization.CultureInfo.InvariantCulture, formatString, alias.Name, alias.Definition, alias.Description, alias.Options); return result; }
protected override void ProcessRecord() { var localRunspace = ExecutionContext.CurrentRunspace as LocalRunspace; AliasInfo info = new AliasInfo(Name, Value, localRunspace == null ? null : localRunspace.CommandManager, Option); SessionState.Alias.New(info, Scope); }
internal AliasInfo SetAliasItem(AliasInfo aliasToSet, bool force, CommandOrigin origin = CommandOrigin.Internal) { if (!this.GetAliases().ContainsKey(aliasToSet.Name)) { if (this.GetAliases().Count > (this.AliasCapacity.FastValue - 1)) { SessionStateOverflowException exception = new SessionStateOverflowException(aliasToSet.Name, SessionStateCategory.Alias, "AliasOverflow", SessionStateStrings.AliasOverflow, new object[] { this.AliasCapacity.FastValue }); throw exception; } this.GetAliases()[aliasToSet.Name] = aliasToSet; } else { AliasInfo valueToCheck = this.GetAliases()[aliasToSet.Name]; SessionState.ThrowIfNotVisible(origin, valueToCheck); if (((valueToCheck.Options & ScopedItemOptions.Constant) != ScopedItemOptions.None) || (((valueToCheck.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None) && !force)) { SessionStateUnauthorizedAccessException exception2 = new SessionStateUnauthorizedAccessException(aliasToSet.Name, SessionStateCategory.Alias, "AliasNotWritable", SessionStateStrings.AliasNotWritable); throw exception2; } if (((aliasToSet.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && ((valueToCheck.Options & ScopedItemOptions.AllScope) != ScopedItemOptions.None)) { SessionStateUnauthorizedAccessException exception3 = new SessionStateUnauthorizedAccessException(aliasToSet.Name, SessionStateCategory.Alias, "AliasAllScopeOptionCannotBeRemoved", SessionStateStrings.AliasAllScopeOptionCannotBeRemoved); throw exception3; } this.RemoveAliasFromCache(valueToCheck.Name, valueToCheck.Definition); this.GetAliases()[aliasToSet.Name] = aliasToSet; } this.AddAliasToCache(aliasToSet.Name, aliasToSet.Definition); return this.GetAliases()[aliasToSet.Name]; }
internal override void SetSessionStateItem(string name, object value, bool writeItem) { AliasProviderDynamicParameters dynamicParameters = base.DynamicParameters as AliasProviderDynamicParameters; AliasInfo item = null; bool flag = (dynamicParameters != null) && dynamicParameters.OptionsSet; if (value == null) { if (flag) { item = (AliasInfo) this.GetSessionStateItem(name); if (item != null) { item.SetOptions(dynamicParameters.Options, (bool) base.Force); } } else { this.RemoveSessionStateItem(name); } } else { string str = value as string; if (str != null) { if (flag) { item = base.SessionState.Internal.SetAliasValue(name, str, dynamicParameters.Options, (bool) base.Force, base.Context.Origin); } else { item = base.SessionState.Internal.SetAliasValue(name, str, (bool) base.Force, base.Context.Origin); } } else { AliasInfo info2 = value as AliasInfo; if (info2 == null) { throw PSTraceSource.NewArgumentException("value"); } AliasInfo alias = new AliasInfo(name, info2.Definition, base.Context.ExecutionContext, info2.Options); if (flag) { alias.SetOptions(dynamicParameters.Options, (bool) base.Force); } item = base.SessionState.Internal.SetAliasItem(alias, (bool) base.Force, base.Context.Origin); } } if (writeItem && (item != null)) { base.WriteItemObject(item, item.Name, false); } }
public void NewAlias(string name, string definition) { if (this._aliases.ContainsKey(name)) throw new Exception("duplicate alias"); AliasInfo aliasInfo = new AliasInfo(name, definition, this); _aliases.Add(aliasInfo.Name, aliasInfo); }
public void New(AliasInfo info, string scope) { _scope.SetAtScope(info, scope, false); }
/// <summary> /// Sets the alias with specified name to the specified value in the current scope. /// </summary> /// /// <param name="alias"> /// The AliasInfo representing the alias. /// </param> /// /// <param name="force"> /// If true, the alias will be set even if there is an existing ReadOnly /// alias. /// </param> /// /// <param name="origin"> /// Specifies the origin of the command setting the alias. /// </param> /// /// <returns> /// The resulting AliasInfo for the alias that was set. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="alias"/> is null. /// </exception> /// /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the alias is read-only or constant. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If the maximum number of aliases has been reached for this scope. /// </exception> /// internal AliasInfo SetAliasItem(AliasInfo alias, bool force, CommandOrigin origin) { if (alias == null) { throw PSTraceSource.NewArgumentNullException("alias"); } AliasInfo info = _currentScope.SetAliasItem(alias, force, origin); return info; } // SetAliasItem
private void AddInitialSessionCommands() { foreach (SessionStateCommandEntry cmdEntry in _initialSessionState.Commands) { if (cmdEntry is SessionStateAliasEntry) { var aliasEntry = (SessionStateAliasEntry)cmdEntry; var aliasInfo = new AliasInfo(aliasEntry.Name, aliasEntry.Definition, aliasEntry.Description, CommandManager, aliasEntry.Options); ExecutionContext.SessionState.Alias.Set(aliasInfo, "global"); } else if (cmdEntry is SessionStateFunctionEntry) { var funEntry = (SessionStateFunctionEntry)cmdEntry; var scriptBlock = new ScriptBlock(Parser.ParseInput(funEntry.Definition)); var funInfo = new FunctionInfo(funEntry.Name, scriptBlock, null, funEntry.Options); ExecutionContext.SessionState.Function.Set(funInfo); } } }