MegaBites-AI/Windows-powershell
0372
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4using System;5using System.Collections.Generic;6using System.Diagnostics.CodeAnalysis;7using System.Management.Automation;8using System.Management.Automation.Security;9 10//11// Now define the set of commands for manipulating modules.12//13 14namespace Microsoft.PowerShell.Commands15{16 #region New-Module17 18 /// <summary>19 /// Implements a cmdlet that creates a dynamic module from a scriptblock..20 /// </summary>21 [Cmdlet(VerbsCommon.New, "Module", DefaultParameterSetName = "ScriptBlock", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096698")]22 [OutputType(typeof(PSModuleInfo))]23 public sealed class NewModuleCommand : ModuleCmdletBase24 {25 /// <summary>26 /// This parameter specifies the name to assign to the dynamic module.27 /// </summary>28 [Parameter(ParameterSetName = "Name", Mandatory = true, ValueFromPipeline = true, Position = 0)]29 public string Name30 {31 get { return _name; }32 33 set { _name = value; }34 }35 36 private string _name;37 38 /// <summary>39 /// Specify a scriptblock to use for the module body...40 /// </summary>41 [Parameter(ParameterSetName = "Name", Mandatory = true, Position = 1)]42 [Parameter(ParameterSetName = "ScriptBlock", Mandatory = true, Position = 0)]43 [ValidateNotNull]44 public ScriptBlock ScriptBlock45 {46 get47 {48 return _scriptBlock;49 }50 51 set52 {53 _scriptBlock = value;54 }55 }56 57 private ScriptBlock _scriptBlock;58 59 /// <summary>60 /// This parameter specifies the patterns matching the functions to import from the module...61 /// </summary>62 [Parameter]63 [ValidateNotNull]64 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]65 public string[] Function66 {67 get68 {69 return _functionImportList;70 }71 72 set73 {74 if (value == null)75 return;76 77 _functionImportList = value;78 // Create the list of patterns to match at parameter bind time79 // so errors will be reported before loading the module...80 BaseFunctionPatterns = new List<WildcardPattern>();81 foreach (string pattern in _functionImportList)82 {83 BaseFunctionPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase));84 }85 }86 }87 88 private string[] _functionImportList = Array.Empty<string>();89 90 /// <summary>91 /// This parameter specifies the patterns matching the cmdlets to import from the module...92 /// </summary>93 [Parameter]94 [ValidateNotNull]95 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]96 public string[] Cmdlet97 {98 get99 {100 return _cmdletImportList;101 }102 103 set104 {105 if (value == null)106 return;107 108 _cmdletImportList = value;109 // Create the list of patterns to match at parameter bind time110 // so errors will be reported before loading the module...111 BaseCmdletPatterns = new List<WildcardPattern>();112 foreach (string pattern in _cmdletImportList)113 {114 BaseCmdletPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase));115 }116 }117 }118 119 private string[] _cmdletImportList = Array.Empty<string>();120 121 /// <summary>122 /// This parameter causes the session state instance to be written...123 /// </summary>124 [Parameter]125 public SwitchParameter ReturnResult126 {127 get { return (SwitchParameter)_returnResult; }128 129 set { _returnResult = value; }130 }131 132 private bool _returnResult;133 134 /// <summary>135 /// This parameter causes the session state instance to be written...136 /// </summary>137 [Parameter]138 public SwitchParameter AsCustomObject139 {140 get { return (SwitchParameter)_asCustomObject; }141 142 set { _asCustomObject = value; }143 }144 145 private bool _asCustomObject;146 147 /// <summary>148 /// The arguments to pass to the scriptblock used to create the module.149 /// </summary>150 [Parameter(ValueFromRemainingArguments = true)]151 [Alias("Args")]152 [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]153 public object[] ArgumentList154 {155 get { return _arguments; }156 157 set { _arguments = value; }158 }159 160 private object[] _arguments;161 162 /// <summary>163 /// Create the new module...164 /// </summary>165 protected override void EndProcessing()166 {167 // Create a module from a scriptblock...168 if (_scriptBlock != null)169 {170 // Check ScriptBlock language mode. If it is different than the context language mode171 // then throw error since private trusted script functions may be exposed.172 if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage && _scriptBlock.LanguageMode == PSLanguageMode.FullLanguage)173 {174 if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit)175 {176 this.ThrowTerminatingError(177 new ErrorRecord(178 new PSSecurityException(Modules.CannotCreateModuleWithScriptBlock),179 "Modules_CannotCreateModuleWithFullLanguageScriptBlock",180 ErrorCategory.SecurityError,181 targetObject: null));182 }183 184 SystemPolicy.LogWDACAuditMessage(185 context: Context,186 title: Modules.WDACNewModuleCommandLogTitle,187 message: Modules.WDACNewModuleCommandLogMessage,188 fqid: "NewModuleCmdletWitFullLanguageScriptblockNotAllowed",189 dropIntoDebugger: true);190 }191 192 string gs = System.Guid.NewGuid().ToString();193 if (string.IsNullOrEmpty(_name))194 {195 _name = PSModuleInfo.DynamicModulePrefixString + gs;196 }197 198 try199 {200 Context.Modules.IncrementModuleNestingDepth(this, _name);201 202 List<object> results = null;203 PSModuleInfo localModule = null;204 try205 {206 // The path for a "dynamic" module will be a GUID so it's unique.207 localModule = Context.Modules.CreateModule(_name, gs, _scriptBlock, null, out results, _arguments);208 209 // Export all functions and variables if no exports were specified...210 if (!localModule.SessionState.Internal.UseExportList)211 {212 List<WildcardPattern> cmdletPatterns = BaseCmdletPatterns ?? MatchAll;213 List<WildcardPattern> functionPatterns = BaseFunctionPatterns ?? MatchAll;214 215 ModuleIntrinsics.ExportModuleMembers(this,216 localModule.SessionState.Internal,217 functionPatterns, cmdletPatterns, BaseAliasPatterns, BaseVariablePatterns, null);218 }219 }220 catch (RuntimeException e)221 {222 // Preserve the inner module invocation info...223 e.ErrorRecord.PreserveInvocationInfoOnce = true;224 WriteError(e.ErrorRecord);225 }226 227 // If the module was created successfully, then process the result...228 if (localModule != null)229 {230 if (_returnResult)231 {232 // import the specified members...233 ImportModuleMembers(localModule, string.Empty /* no -Prefix for New-Module cmdlet */);234 WriteObject(results, true);235 }236 else if (_asCustomObject)237 {238 WriteObject(localModule.AsCustomObject());239 }240 else241 {242 // import the specified members...243 ImportModuleMembers(localModule, string.Empty /* no -Prefix for New-Module cmdlet */);244 WriteObject(localModule);245 }246 }247 }248 finally249 {250 Context.Modules.DecrementModuleNestingCount();251 }252 253 return;254 }255 }256 }257 258 #endregion259}260 