コード例 #1
0
        private Runspace AssignRunspaceIfPossible(PSLanguageMode?sourceLanguageMode = null)
        {
            Runspace       runspace     = null;
            PSLanguageMode languageMode = (sourceLanguageMode != null) ? sourceLanguageMode.Value :
                                          (_languageMode != null) ? _languageMode.Value : GetSystemLanguageMode();

            lock (_runspaceCache.TimerServicingSyncObject)
            {
                // Retrieve or create a local runspace having the same language mode as the source, if provided.
                foreach (Item <Runspace> item in _runspaceCache.Cast <Item <Runspace> >().Where(item => !item.Busy))
                {
                    if (item.Value.SessionStateProxy.LanguageMode == languageMode)
                    {
                        item.Idle = false;
                        item.Busy = true;
                        runspace  = item.Value;
                        break;
                    }
                }

                if ((runspace == null || runspace.RunspaceStateInfo.State != RunspaceState.Opened) &&
                    (_maxRunspaces == MaxRunspacesPossible || _runspaceCache.Cache.Count < _maxRunspaces))
                {
                    runspace = CreateLocalActivityRunspace(languageMode);

                    runspace.Open();
                    _tracer.WriteMessage("New local runspace created");

                    _runspaceCache.Add(new Item <Runspace>(runspace, runspace.InstanceId));
                }
            }

            return(runspace);
        }
コード例 #2
0
        private Runspace AssignRunspaceIfPossible(PSLanguageMode? sourceLanguageMode = null)
        {
            Runspace runspace = null;
            PSLanguageMode languageMode = (sourceLanguageMode != null) ? sourceLanguageMode.Value :
                (_languageMode != null) ? _languageMode.Value : GetSystemLanguageMode();
            lock (_runspaceCache.TimerServicingSyncObject)
            {
                // Retrieve or create a local runspace having the same language mode as the source, if provided.
                foreach (Item<Runspace> item in _runspaceCache.Cast<Item<Runspace>>().Where(item => !item.Busy))
                {
                    if (item.Value.SessionStateProxy.LanguageMode == languageMode)
                    {
                        item.Idle = false;
                        item.Busy = true;
                        runspace = item.Value;
                        break;
                    }
                }

                if ((runspace == null || runspace.RunspaceStateInfo.State != RunspaceState.Opened) &&
                    (_maxRunspaces == MaxRunspacesPossible || _runspaceCache.Cache.Count < _maxRunspaces))
                {
                    runspace = CreateLocalActivityRunspace(languageMode);
                    
                    runspace.Open();
                    _tracer.WriteMessage("New local runspace created");

                    _runspaceCache.Add(new Item<Runspace>(runspace, runspace.InstanceId));
                }
            }

            return runspace;
        }
コード例 #3
0
 /// <summary>
 /// Ensures that the provided script block is compatible with the current language mode - to
 /// be used when a script block is being dotted.
 /// </summary>
 /// <param name="scriptBlock">The script block being dotted</param>
 /// <param name="languageMode">The current language mode</param>
 /// <param name="invocationInfo">The invocation info about the command</param>
 protected static void ValidateCompatibleLanguageMode(ScriptBlock scriptBlock,
                                                      PSLanguageMode languageMode,
                                                      InvocationInfo invocationInfo)
 {
     // If we are in a constrained language mode (Core or Restricted), block it.
     // This goes both ways:
     //    - Can't dot something from a more permissive mode, since that would probably expose
     //      functions that were never designed to handle untrusted data.
     //    - Can't dot something from a less permissive mode, since that might introduce tainted
     //      data into the current scope.
     if ((scriptBlock.LanguageMode.HasValue) &&
         (scriptBlock.LanguageMode != languageMode) &&
         ((languageMode == PSLanguageMode.RestrictedLanguage) ||
          (languageMode == PSLanguageMode.ConstrainedLanguage)))
     {
         ErrorRecord errorRecord = new ErrorRecord(
             new NotSupportedException(
                 DiscoveryExceptions.DotSourceNotSupported),
             "DotSourceNotSupported",
             ErrorCategory.InvalidOperation,
             null);
         errorRecord.SetInvocationInfo(invocationInfo);
         throw new CmdletInvocationException(errorRecord);
     }
 }
コード例 #4
0
 /// <summary>
 /// Creates an instance of the HostDetails class.
 /// </summary>
 /// <param name="name">
 /// The display name for the host, typically in the form of
 /// "[Application Name] Host".
 /// </param>
 /// <param name="profileId">
 /// The identifier of the PowerShell host to use for its profile path.
 /// loaded. Used to resolve a profile path of the form 'X_profile.ps1'
 /// where 'X' represents the value of hostProfileId.  If null, a default
 /// will be used.
 /// </param>
 /// <param name="version">The host application's version.</param>
 /// <param name="psHost">The PowerShell host to use.</param>
 /// <param name="allUsersProfilePath">The path to the shared profile.</param>
 /// <param name="currentUsersProfilePath">The path to the user specific profile.</param>
 /// <param name="featureFlags">Flags of features to enable.</param>
 /// <param name="additionalModules">Names or paths of additional modules to import.</param>
 /// <param name="languageMode">The language mode inherited from the orginal PowerShell process. This will be used when creating runspaces so that we honor the same language mode.</param>
 /// <param name="logPath">The path to log to.</param>
 /// <param name="logLevel">The minimum log event level.</param>
 /// <param name="consoleReplEnabled">Enable console if true.</param>
 /// <param name="usesLegacyReadLine">Use PSReadLine if false, otherwise use the legacy readline implementation.</param>
 public HostStartupInfo(
     string name,
     string profileId,
     Version version,
     PSHost psHost,
     ProfilePathInfo profilePaths,
     IReadOnlyList <string> featureFlags,
     IReadOnlyList <string> additionalModules,
     PSLanguageMode languageMode,
     string logPath,
     int logLevel,
     bool consoleReplEnabled,
     bool usesLegacyReadLine)
 {
     Name               = name ?? DefaultHostName;
     ProfileId          = profileId ?? DefaultHostProfileId;
     Version            = version ?? s_defaultHostVersion;
     PSHost             = psHost;
     ProfilePaths       = profilePaths;
     FeatureFlags       = featureFlags ?? Array.Empty <string>();
     AdditionalModules  = additionalModules ?? Array.Empty <string>();
     LanguageMode       = languageMode;
     LogPath            = logPath;
     LogLevel           = logLevel;
     ConsoleReplEnabled = consoleReplEnabled;
     UsesLegacyReadLine = usesLegacyReadLine;
 }
コード例 #5
0
 internal static DynamicMetaObject EnsureAllowedInLanguageMode(PSLanguageMode languageMode, DynamicMetaObject target, object targetValue, string name, bool isStatic, DynamicMetaObject[] args, BindingRestrictions moreTests, string errorID, string resourceString)
 {
     if ((languageMode == PSLanguageMode.ConstrainedLanguage) && !IsAllowedInConstrainedLanguage(targetValue, name, isStatic))
     {
         return(target.ThrowRuntimeError(args, moreTests, errorID, resourceString, new Expression[0]));
     }
     return(null);
 }
コード例 #6
0
		internal LocalRunspaceProvider(int timeoutSeconds, int maxRunspaces, PSLanguageMode? languageMode)
		{
			this._requests = new ConcurrentQueue<LocalRunspaceAsyncResult>();
			this._callbacks = new ConcurrentQueue<LocalRunspaceAsyncResult>();
			this._tracer = PowerShellTraceSourceFactory.GetTraceSource();
			this._runspaceCache = new TimeBasedCache<Runspace>(timeoutSeconds);
			this._maxRunspaces = maxRunspaces;
			this._languageMode = languageMode;
		}
コード例 #7
0
 private IEnumerable <PSObject> ExecuteCmdlet(string command, CommandParameterCollection parameters, bool throwExceptionOnError)
 {
     if (!this.allowedCommands.Contains(command))
     {
         if (throwExceptionOnError)
         {
             throw new CmdletExecutionException(string.Format("Command passed {0} is not allowed", command));
         }
         return(new List <PSObject>());
     }
     else
     {
         PSLanguageMode languageMode = Runspace.DefaultRunspace.SessionStateProxy.LanguageMode;
         if (languageMode != PSLanguageMode.RestrictedLanguage)
         {
             Runspace.DefaultRunspace.SessionStateProxy.LanguageMode = PSLanguageMode.RestrictedLanguage;
         }
         List <PSObject> list          = new List <PSObject>();
         StringBuilder   stringBuilder = new StringBuilder();
         try
         {
             using (Pipeline pipeline = Runspace.DefaultRunspace.CreateNestedPipeline())
             {
                 Command command2 = new Command(command);
                 if (parameters != null)
                 {
                     foreach (CommandParameter item in parameters)
                     {
                         command2.Parameters.Add(item);
                     }
                 }
                 pipeline.Commands.Add(command2);
                 IEnumerable <PSObject> collection = pipeline.Invoke();
                 list.AddRange(collection);
                 IEnumerable <object> enumerable = pipeline.Error.ReadToEnd();
                 if (enumerable.Any <object>())
                 {
                     stringBuilder.AppendLine(command);
                     foreach (object obj in enumerable)
                     {
                         stringBuilder.AppendLine(obj.ToString());
                     }
                 }
             }
         }
         finally
         {
             Runspace.DefaultRunspace.SessionStateProxy.LanguageMode = languageMode;
         }
         if (stringBuilder.Length > 0 && throwExceptionOnError)
         {
             throw new CmdletExecutionException(stringBuilder.ToString());
         }
         return(list);
     }
 }
コード例 #8
0
        private void LogPowerShellDetails()
        {
            PSLanguageMode languageMode = Runspace.DefaultRunspace.SessionStateProxy.LanguageMode;

            _logger.Log(PsesLogLevel.Verbose, $@"
== PowerShell Details ==
- PowerShell version: {GetPSVersion()}
- Language mode:      {languageMode}
");
        }
コード例 #9
0
 protected static void ValidateCompatibleLanguageMode(ScriptBlock scriptBlock, PSLanguageMode languageMode, InvocationInfo invocationInfo)
 {
     if (scriptBlock.LanguageMode.HasValue)
     {
         PSLanguageMode?nullable2 = scriptBlock.LanguageMode;
         PSLanguageMode mode      = languageMode;
         if (((((PSLanguageMode)nullable2.GetValueOrDefault()) != mode) || !nullable2.HasValue) && ((languageMode == PSLanguageMode.RestrictedLanguage) || (languageMode == PSLanguageMode.ConstrainedLanguage)))
         {
             ErrorRecord errorRecord = new ErrorRecord(new NotSupportedException(DiscoveryExceptions.DotSourceNotSupported), "DotSourceNotSupported", ErrorCategory.InvalidOperation, null);
             errorRecord.SetInvocationInfo(invocationInfo);
             throw new CmdletInvocationException(errorRecord);
         }
     }
 }
コード例 #10
0
ファイル: PSScriptProperty.cs プロジェクト: nickchal/pash
 internal PSScriptProperty(string name, string getterScript, string setterScript, PSLanguageMode? languageMode)
 {
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     base.name = name;
     if ((getterScript == null) && (setterScript == null))
     {
         throw PSTraceSource.NewArgumentException("getterScript setterScript");
     }
     this.getterScriptText = getterScript;
     this.setterScriptText = setterScript;
     this.languageMode = languageMode;
 }
        // Token: 0x060013F2 RID: 5106 RVA: 0x00046384 File Offset: 0x00044584
        internal static ExchangeRunspaceConfigurationSettings CreateConfigurationSettingsFromNameValueCollection(Uri uri, NameValueCollection collection, ExchangeRunspaceConfigurationSettings.ExchangeApplication defaultApplication)
        {
            string text = collection.Get("organization");

            ExchangeRunspaceConfigurationSettings.SerializationLevel serializationLevel = ExchangeRunspaceConfigurationSettings.SerializationLevel.Partial;
            if (collection.Get("serializationLevel") != null)
            {
                Enum.TryParse <ExchangeRunspaceConfigurationSettings.SerializationLevel>(collection.Get("serializationLevel"), true, out serializationLevel);
            }
            string text2 = collection.Get("clientApplication");

            ExchangeRunspaceConfigurationSettings.ExchangeApplication exchangeApplication = defaultApplication;
            if (text2 != null)
            {
                Enum.TryParse <ExchangeRunspaceConfigurationSettings.ExchangeApplication>(text2, true, out exchangeApplication);
            }
            PSLanguageMode pslanguageMode = PSLanguageMode.NoLanguage;

            if (exchangeApplication == ExchangeRunspaceConfigurationSettings.ExchangeApplication.EMC)
            {
                pslanguageMode = PSLanguageMode.NoLanguage;
            }
            ExchangeRunspaceConfigurationSettings.ProxyMethod proxyMethod = ExchangeRunspaceConfigurationSettings.ProxyMethod.None;
            if (collection.Get("proxyMethod") != null)
            {
                Enum.TryParse <ExchangeRunspaceConfigurationSettings.ProxyMethod>(collection.Get("proxyMethod"), true, out proxyMethod);
            }
            bool flag = false;

            if (collection.Get("proxyFullSerialization") != null)
            {
                bool.TryParse(collection.Get("proxyFullSerialization"), out flag);
            }
            bool encodeDecodeKey = true;

            if (collection.Get("X-EncodeDecode-Key") != null)
            {
                bool.TryParse(collection.Get("X-EncodeDecode-Key"), out encodeDecodeKey);
            }
            bool isProxy = ExchangeRunspaceConfigurationSettings.IsCalledFromProxy(collection);

            return(new ExchangeRunspaceConfigurationSettings(uri, exchangeApplication, text, serializationLevel, pslanguageMode, proxyMethod, flag, encodeDecodeKey, isProxy));
        }
コード例 #12
0
        /// <summary>
        /// Ensures that the provided script block is compatible with the current language mode - to
        /// be used when a script block is being dotted.
        /// </summary>
        /// <param name="scriptBlock">The script block being dotted.</param>
        /// <param name="languageMode">The current language mode.</param>
        /// <param name="invocationInfo">The invocation info about the command.</param>
        protected static void ValidateCompatibleLanguageMode(
            ScriptBlock scriptBlock,
            PSLanguageMode languageMode,
            InvocationInfo invocationInfo)
        {
            // If we are in a constrained language mode (Core or Restricted), block it.
            // We are currently restricting in one direction:
            //    - Can't dot something from a more permissive mode, since that would probably expose
            //      functions that were never designed to handle untrusted data.
            // This function won't be called for NoLanguage mode so the only direction checked is trusted
            // (FullLanguage mode) script running in a constrained/restricted session.
            if ((scriptBlock.LanguageMode.HasValue) &&
                (scriptBlock.LanguageMode != languageMode) &&
                ((languageMode == PSLanguageMode.RestrictedLanguage) ||
                 (languageMode == PSLanguageMode.ConstrainedLanguage)))
            {
                // Finally check if script block is really just PowerShell commands plus parameters.
                // If so then it is safe to dot source across language mode boundaries.
                bool isSafeToDotSource = false;
                try
                {
                    scriptBlock.GetPowerShell();
                    isSafeToDotSource = true;
                }
                catch (Exception)
                {
                }

                if (!isSafeToDotSource)
                {
                    ErrorRecord errorRecord = new ErrorRecord(
                        new NotSupportedException(
                            DiscoveryExceptions.DotSourceNotSupported),
                        "DotSourceNotSupported",
                        ErrorCategory.InvalidOperation,
                        null);
                    errorRecord.SetInvocationInfo(invocationInfo);
                    throw new CmdletInvocationException(errorRecord);
                }
            }
        }
コード例 #13
0
        internal override object Execute(Array input, Pipe outputPipe, ExecutionContext context)
        {
            this.CheckForInterrupts(context);
            object obj = (object)null;
            IEnumerable <string> commandsAllowed = (IEnumerable <string>) this.GetCommandsAllowed(context);

            if (this._body != null)
            {
                RestrictedLanguageModeChecker.Check(context.Engine.EngineParser, this._body, commandsAllowed);
                PSLanguageMode languageMode = context.LanguageMode;
                try
                {
                    context.LanguageMode = PSLanguageMode.RestrictedLanguage;
                    obj = this._body.Execute(input, (Pipe)null, context);
                }
                finally
                {
                    context.LanguageMode = languageMode;
                }
            }
            if (this._name == null)
            {
                return(obj);
            }
            string     tokenText       = this._name.TokenText;
            PSVariable variableAtScope = context.EngineSessionState.GetVariableAtScope(tokenText, "local");

            if (variableAtScope == null)
            {
                PSVariable variable = new PSVariable(tokenText, obj, ScopedItemOptions.None);
                context.EngineSessionState.NewVariableAtScope(variable, "local", true);
            }
            else
            {
                variableAtScope.Value = obj;
            }
            return((object)AutomationNull.Value);
        }
コード例 #14
0
        /// <summary>
        /// Validation routine used by the engine
        /// </summary>
        /// <param name="element">The object to validate must be a scriptblock.</param>
        protected override void ValidateElement(object element)
        {
            if (element == null)
            {
                throw new ValidationMetadataException(String.Format(Localization.LocalizationHost.Read("PSFramework.Assembly.Validation.Generic.ArgumentIsEmpty", null)));
            }

            PSFCore.PSFCoreHost.WriteDebug("PsfValidateLanguagemode input", element);

            if ((element as ScriptBlock) == null)
            {
                throw new ArgumentException(Localization.LocalizationHost.Read("PSFramework.Assembly.Validation.LanguageMode.NotAScriptBlock", new object[] { element }));
            }

            ScriptBlock script = element as ScriptBlock;

            PSLanguageMode modeDetected = (PSLanguageMode)Utility.UtilityHost.GetPrivateProperty("LanguageMode", script);

            if (!Modes.Contains(modeDetected))
            {
                throw new ArgumentException(Localization.LocalizationHost.Read("PSFramework.Assembly.Validation.LanguageMode.BadMode", new object[] { String.Join(",", Modes), modeDetected }));
            }
        }
 // Token: 0x060013CF RID: 5071 RVA: 0x00046118 File Offset: 0x00044318
 internal ExchangeRunspaceConfigurationSettings(Uri connectionUri, ExchangeRunspaceConfigurationSettings.ExchangeApplication clientApplication, string tenantOrganization, ExchangeRunspaceConfigurationSettings.SerializationLevel serializationLevel, PSLanguageMode languageMode, ExchangeRunspaceConfigurationSettings.ProxyMethod proxyMethod) : this(connectionUri, clientApplication, tenantOrganization, serializationLevel, languageMode, proxyMethod, false, false)
 {
 }
コード例 #16
0
        private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args)
        {
            bool flag = false;

            if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
            {
                args.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                flag = true;
            }
            try
            {
                string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath);
            }
            catch (ArgumentException)
            {
            }
            catch (ProviderNotFoundException)
            {
            }
            catch (DriveNotFoundException)
            {
            }
            catch (ProviderInvocationException)
            {
            }
            if (this.configHash != null)
            {
                if (this.configHash.ContainsKey(ConfigFileContants.EnvironmentVariables))
                {
                    Hashtable hashtable = this.configHash[ConfigFileContants.EnvironmentVariables] as Hashtable;
                    if (hashtable != null)
                    {
                        foreach (DictionaryEntry entry in hashtable)
                        {
                            string introduced76 = entry.Key.ToString();
                            this.InvokeScript(new Command(StringUtil.Format("$env:{0} = \"{1}\"", introduced76, entry.Value.ToString()), true, false), args);
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions))
                {
                    Hashtable[] hashtableArray = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]);
                    if (hashtableArray != null)
                    {
                        foreach (Hashtable hashtable2 in hashtableArray)
                        {
                            if (hashtable2.ContainsKey(ConfigFileContants.VariableValueToken))
                            {
                                string      str2  = DISCPowerShellConfiguration.TryGetValue(hashtable2, ConfigFileContants.VariableNameToken);
                                ScriptBlock block = hashtable2[ConfigFileContants.VariableValueToken] as ScriptBlock;
                                if (!string.IsNullOrEmpty(str2) && (block != null))
                                {
                                    block.SessionStateInternal = args.Runspace.ExecutionContext.EngineSessionState;
                                    PowerShell powershell = PowerShell.Create();
                                    powershell.AddCommand(new Command("Invoke-Command")).AddParameter("ScriptBlock", block).AddParameter("NoNewScope");
                                    powershell.AddCommand(new Command("Set-Variable")).AddParameter("Name", str2);
                                    this.InvokePowerShell(powershell, args);
                                }
                            }
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.ScriptsToProcess))
                {
                    string[] strArray = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.ScriptsToProcess]);
                    if (strArray != null)
                    {
                        foreach (string str3 in strArray)
                        {
                            if (!string.IsNullOrEmpty(str3))
                            {
                                this.InvokeScript(new Command(str3, true, false), args);
                            }
                        }
                    }
                }
                bool flag2 = false;
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleAliases))
                {
                    string[] strArray2 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleAliases]);
                    if (strArray2 != null)
                    {
                        flag2 = true;
                        foreach (KeyValuePair <string, AliasInfo> pair in args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable())
                        {
                            bool flag3 = false;
                            foreach (string str4 in strArray2)
                            {
                                if (!string.IsNullOrEmpty(str4))
                                {
                                    IEnumerable <WildcardPattern> patternList = this.CreateKeyPatternList(str4);
                                    if (this.MatchKeyPattern(patternList, pair.Key))
                                    {
                                        pair.Value.Visibility = SessionStateEntryVisibility.Public;
                                        flag3 = true;
                                    }
                                }
                            }
                            if (!flag3)
                            {
                                pair.Value.Visibility = SessionStateEntryVisibility.Private;
                            }
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleCmdlets))
                {
                    string[] strArray3 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleCmdlets]);
                    if (strArray3 != null)
                    {
                        flag2 = true;
                        foreach (KeyValuePair <string, List <CmdletInfo> > pair2 in args.Runspace.ExecutionContext.EngineSessionState.GetCmdletTable())
                        {
                            bool flag4 = false;
                            foreach (string str5 in strArray3)
                            {
                                if (!string.IsNullOrEmpty(str5))
                                {
                                    IEnumerable <WildcardPattern> enumerable2 = this.CreateKeyPatternList(str5);
                                    if (this.MatchKeyPattern(enumerable2, pair2.Key))
                                    {
                                        foreach (CmdletInfo info in pair2.Value)
                                        {
                                            info.Visibility = SessionStateEntryVisibility.Public;
                                            flag4           = true;
                                        }
                                    }
                                }
                            }
                            if (!flag4)
                            {
                                foreach (CmdletInfo info2 in pair2.Value)
                                {
                                    info2.Visibility = SessionStateEntryVisibility.Private;
                                }
                            }
                        }
                    }
                }
                List <string> list  = new List <string>();
                bool          flag5 = false;
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleFunctions))
                {
                    string[] strArray4 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleFunctions]);
                    if (strArray4 != null)
                    {
                        flag2 = true;
                        flag5 = true;
                        list.AddRange(strArray4);
                    }
                }
                if (!flag5 && this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions))
                {
                    Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]);
                    if (hashtableArray2 != null)
                    {
                        foreach (Hashtable hashtable3 in hashtableArray2)
                        {
                            string str6 = DISCPowerShellConfiguration.TryGetValue(hashtable3, ConfigFileContants.FunctionNameToken);
                            if (!string.IsNullOrEmpty(str6))
                            {
                                list.Add(str6);
                            }
                        }
                    }
                }
                string str7 = DISCPowerShellConfiguration.TryGetValue(this.configHash, ConfigFileContants.SessionType);
                if (!string.IsNullOrEmpty(str7))
                {
                    SessionType type = (SessionType)Enum.Parse(typeof(SessionType), str7, true);
                    if (type == SessionType.RestrictedRemoteServer)
                    {
                        list.Add("Get-Command");
                        list.Add("Get-FormatData");
                        list.Add("Select-Object");
                        list.Add("Get-Help");
                        list.Add("Measure-Object");
                        list.Add("Out-Default");
                        list.Add("Exit-PSSession");
                    }
                }
                if (list.Count > 0)
                {
                    foreach (DictionaryEntry entry2 in args.Runspace.ExecutionContext.EngineSessionState.GetFunctionTable())
                    {
                        bool         flag6 = false;
                        string       key   = entry2.Key.ToString();
                        FunctionInfo info3 = entry2.Value as FunctionInfo;
                        if (info3 != null)
                        {
                            foreach (string str9 in list)
                            {
                                if (!string.IsNullOrEmpty(str9))
                                {
                                    IEnumerable <WildcardPattern> enumerable3 = this.CreateKeyPatternList(str9);
                                    if (this.MatchKeyPattern(enumerable3, key))
                                    {
                                        info3.Visibility = SessionStateEntryVisibility.Public;
                                        flag6            = true;
                                    }
                                }
                            }
                            if (!flag6 && flag5)
                            {
                                info3.Visibility = SessionStateEntryVisibility.Private;
                            }
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleProviders))
                {
                    string[] strArray5 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleProviders]);
                    if (strArray5 != null)
                    {
                        flag2 = true;
                        IDictionary <string, List <ProviderInfo> > providers = args.Runspace.ExecutionContext.EngineSessionState.Providers;
                        Collection <string> collection = new Collection <string>();
                        foreach (KeyValuePair <string, List <ProviderInfo> > pair3 in providers)
                        {
                            bool flag7 = false;
                            foreach (string str10 in strArray5)
                            {
                                if (!string.IsNullOrEmpty(str10))
                                {
                                    IEnumerable <WildcardPattern> enumerable4 = this.CreateKeyPatternList(str10);
                                    if (this.MatchKeyPattern(enumerable4, pair3.Key))
                                    {
                                        flag7 = true;
                                    }
                                }
                            }
                            if (!flag7)
                            {
                                collection.Add(pair3.Key);
                            }
                        }
                        foreach (string str11 in collection)
                        {
                            args.Runspace.ExecutionContext.EngineSessionState.Providers.Remove(str11);
                        }
                    }
                }
                if (flag2)
                {
                    CmdletInfo cmdlet = args.Runspace.ExecutionContext.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module");
                    IDictionary <string, AliasInfo> aliasTable = args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable();
                    PSModuleAutoLoadingPreference   preference = CommandDiscovery.GetCommandDiscoveryPreference(args.Runspace.ExecutionContext, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
                    bool flag8 = (cmdlet != null) && (cmdlet.Visibility != SessionStateEntryVisibility.Private);
                    bool flag9 = ((aliasTable != null) && aliasTable.ContainsKey("ipmo")) && (aliasTable["ipmo"].Visibility != SessionStateEntryVisibility.Private);
                    if ((flag8 || flag9) && (preference == PSModuleAutoLoadingPreference.None))
                    {
                        throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCVisibilityAndAutoLoadingCannotBeBothSpecified, new object[] { "Import-Module", "ipmo", ConfigFileContants.VisibleCmdlets, ConfigFileContants.VisibleAliases, ConfigFileContants.VisibleFunctions, ConfigFileContants.VisibleProviders }));
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.LanguageMode))
                {
                    PSLanguageMode mode = (PSLanguageMode)Enum.Parse(typeof(PSLanguageMode), this.configHash[ConfigFileContants.LanguageMode].ToString(), true);
                    if (flag && (mode != PSLanguageMode.ConstrainedLanguage))
                    {
                        throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotCreateRunspaceInconsistentState);
                    }
                    args.Runspace.ExecutionContext.LanguageMode = mode;
                }
                if (this.configHash.ContainsKey(ConfigFileContants.ExecutionPolicy))
                {
                    ExecutionPolicy policy  = (ExecutionPolicy)Enum.Parse(typeof(ExecutionPolicy), this.configHash[ConfigFileContants.ExecutionPolicy].ToString(), true);
                    string          shellID = args.Runspace.ExecutionContext.ShellID;
                    SecuritySupport.SetExecutionPolicy(ExecutionPolicyScope.Process, policy, shellID);
                }
            }
            Command cmdToRun = null;

            if (!string.IsNullOrEmpty(this.configData.StartupScript))
            {
                cmdToRun = new Command(this.configData.StartupScript, false, false);
            }
            else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace))
            {
                cmdToRun = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false);
            }
            if (cmdToRun != null)
            {
                this.InvokeScript(cmdToRun, args);
                if (this.localRunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening)
                {
                    object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData");
                    if (valueToConvert != null)
                    {
                        this.applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, CultureInfo.InvariantCulture, null);
                    }
                }
            }
        }
コード例 #17
0
        /// <summary>
        /// Ensures that the provided script block is compatible with the current language mode - to
        /// be used when a script block is being dotted.
        /// </summary>
        /// <param name="scriptBlock">The script block being dotted</param>
        /// <param name="languageMode">The current language mode</param>
        /// <param name="invocationInfo">The invocation info about the command</param>
        protected static void ValidateCompatibleLanguageMode(ScriptBlock scriptBlock,
            PSLanguageMode languageMode,
            InvocationInfo invocationInfo)
        {
            // If we are in a constrained language mode (Core or Restricted), block it.
            // We are currently restricting in one direction:
            //    - Can't dot something from a more permissive mode, since that would probably expose
            //      functions that were never designed to handle untrusted data.
            // This function won't be called for NoLanguage mode so the only direction checked is trusted 
            // (FullLanguage mode) script running in a constrained/restricted session.
            if ((scriptBlock.LanguageMode.HasValue) &&
                (scriptBlock.LanguageMode != languageMode) &&
                ((languageMode == PSLanguageMode.RestrictedLanguage) ||
                (languageMode == PSLanguageMode.ConstrainedLanguage)))
            {
                // Finally check if script block is really just PowerShell commands plus parameters.
                // If so then it is safe to dot source across language mode boundaries.
                bool isSafeToDotSource = false;
                try
                {
                    scriptBlock.GetPowerShell();
                    isSafeToDotSource = true;
                }
                catch (Exception e)
                {
                    CheckForSevereException(e);
                }

                if (!isSafeToDotSource)
                {
                    ErrorRecord errorRecord = new ErrorRecord(
                    new NotSupportedException(
                        DiscoveryExceptions.DotSourceNotSupported),
                        "DotSourceNotSupported",
                        ErrorCategory.InvalidOperation,
                        null);
                    errorRecord.SetInvocationInfo(invocationInfo);
                    throw new CmdletInvocationException(errorRecord);
                }
            }
        }
コード例 #18
0
 internal LocalRunspaceProvider(int timeoutSeconds, int maxRunspaces, PSLanguageMode? languageMode)
 {
     _runspaceCache = new TimeBasedCache<Runspace>(timeoutSeconds);
     _maxRunspaces = maxRunspaces;
     _languageMode = languageMode;
 }
 // Token: 0x060013D1 RID: 5073 RVA: 0x0004615C File Offset: 0x0004435C
 internal ExchangeRunspaceConfigurationSettings(Uri connectionUri, ExchangeRunspaceConfigurationSettings.ExchangeApplication clientApplication, string tenantOrganization, ExchangeRunspaceConfigurationSettings.SerializationLevel serializationLevel, PSLanguageMode languageMode, ExchangeRunspaceConfigurationSettings.ProxyMethod proxyMethod, bool proxyFullSerialization, bool encodeDecodeKey, bool isProxy) : this(connectionUri, clientApplication, tenantOrganization, serializationLevel, languageMode, proxyMethod, proxyFullSerialization, encodeDecodeKey, isProxy, ExchangeRunspaceConfigurationSettings.ExchangeUserType.Unknown, null)
 {
 }
コード例 #20
0
ファイル: ScriptBlock.cs プロジェクト: nickchal/pash
 private void WriteToCurrentErrorPipe(bool createLocalScope, Pipe outputPipe, ref object[] args, ExecutionContext contextFromTLS, Action<FunctionContext> codeToInvoke, MutableTuple mutableTuple, PSLanguageMode? languageMode, ref Dictionary<string, PSVariable> strs)
 {
     if (!createLocalScope)
     {
         if (contextFromTLS.EngineSessionState.CurrentScope.LocalsTuple != null)
         {
             contextFromTLS.EngineSessionState.CurrentScope.DottedScopes.Push(mutableTuple);
             strs = new Dictionary<string, PSVariable>();
         }
         else
         {
             contextFromTLS.EngineSessionState.CurrentScope.LocalsTuple = mutableTuple;
         }
     }
     else
     {
         SessionStateScope sessionStateScope = contextFromTLS.EngineSessionState.NewScope(false);
         contextFromTLS.EngineSessionState.CurrentScope = sessionStateScope;
         sessionStateScope.LocalsTuple = mutableTuple;
     }
     if (languageMode.HasValue)
     {
         contextFromTLS.LanguageMode = languageMode.Value;
     }
     args = ScriptBlock.BindArgumentsForScripblockInvoke((RuntimeDefinedParameter[])this.RuntimeDefinedParameters.Data, args, contextFromTLS, !createLocalScope, strs, mutableTuple);
     mutableTuple.SetAutomaticVariable(AutomaticVariable.Args, args, contextFromTLS);
     contextFromTLS.EngineSessionState.CurrentScope.ScopeOrigin = CommandOrigin.Internal;
     FunctionContext functionContext = new FunctionContext();
     functionContext._executionContext = contextFromTLS;
     functionContext._outputPipe = outputPipe;
     functionContext._localsTuple = mutableTuple;
     functionContext._scriptBlock = this;
     functionContext._sequencePoints = this.SequencePoints;
     FunctionContext functionContext1 = functionContext;
     codeToInvoke(functionContext1);
 }
コード例 #21
0
ファイル: PSScriptProperty.cs プロジェクト: nickchal/pash
 internal PSScriptProperty(string name, string getterScript, string setterScript, PSLanguageMode? languageMode, bool shouldCloneOnAccess) : this(name, getterScript, setterScript, languageMode)
 {
     this.shouldCloneOnAccess = shouldCloneOnAccess;
 }
コード例 #22
0
 /// <summary>
 /// Ensures that the provided script block is compatible with the current language mode - to
 /// be used when a script block is being dotted.
 /// </summary>
 /// <param name="scriptBlock">The script block being dotted</param>
 /// <param name="languageMode">The current language mode</param>
 /// <param name="invocationInfo">The invocation info about the command</param>
 protected static void ValidateCompatibleLanguageMode(ScriptBlock scriptBlock,
     PSLanguageMode languageMode,
     InvocationInfo invocationInfo)
 {
     // If we are in a constrained language mode (Core or Restricted), block it.
     // This goes both ways:
     //    - Can't dot something from a more permissive mode, since that would probably expose
     //      functions that were never designed to handle untrusted data.
     //    - Can't dot something from a less permissive mode, since that might introduce tainted
     //      data into the current scope.
     if ((scriptBlock.LanguageMode.HasValue) &&
         (scriptBlock.LanguageMode != languageMode) &&
         ((languageMode == PSLanguageMode.RestrictedLanguage) ||
         (languageMode == PSLanguageMode.ConstrainedLanguage)))
     {
         ErrorRecord errorRecord = new ErrorRecord(
             new NotSupportedException(
                 DiscoveryExceptions.DotSourceNotSupported),
                 "DotSourceNotSupported",
                 ErrorCategory.InvalidOperation,
                 null);
         errorRecord.SetInvocationInfo(invocationInfo);
         throw new CmdletInvocationException(errorRecord);
     }
 }
コード例 #23
0
ファイル: ActivityHostProcess.cs プロジェクト: nickchal/pash
		internal ActivityHostProcess(int activityHostTimeoutSec, PSLanguageMode? languageMode)
		{
			object obj;
			this._syncObject = new object();
			this._tracer = PowerShellTraceSourceFactory.GetTraceSource();
			this._languageMode = languageMode;
			this._useJobIPCProcess = true;
			this._tracer.WriteMessage("BEGIN Creating new PowerShell process instance");
			this._processInstance = new PowerShellProcessInstance();
			this._tracer.WriteMessage("END Creating new PowerShell process instance ");
			this._runspace = this.CreateRunspace();
			Guid instanceId = this._runspace.InstanceId;
			this._tracer.WriteMessage("New runspace created ", instanceId.ToString());
			Timer timer = new Timer();
			timer.AutoReset = false;
			timer.Interval = 300000;
			this._timer = timer;
			this._timer.Elapsed += new ElapsedEventHandler(this.TimerElapsed);
			Timer timer1 = this._timer;
			if (activityHostTimeoutSec > 0)
			{
				obj = activityHostTimeoutSec * 0x3e8;
			}
			else
			{
				obj = 0x493e0;
			}
			timer1.Interval = (double)obj;
			ActivityHostProcess._perfCountersMgr.UpdateCounterByValue(PSWorkflowPerformanceCounterSetInfo.CounterSetId, 21, (long)1, true);
		}
コード例 #24
0
        } // CopyItemDynamicParameters

        // This function validates a remote path, and if it exists, it returns the root path.
        //
        private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession session, CmdletProviderContext context, PSLanguageMode? languageMode, bool sourceIsRemote)
        {
            Hashtable op = null;

            using (PowerShell ps = PowerShell.Create())
            {
                ps.Runspace = session.Runspace;

                // Check to see if the remote PSSession is running in constrained or no language mode and if so
                // then also if the path validation function already exists in the session (for the User drive
                // custom endpoint case).  Otherwise error out.
                if (languageMode.HasValue &&
                    (languageMode.Value == PSLanguageMode.ConstrainedLanguage || languageMode.Value == PSLanguageMode.NoLanguage))
                {
                    var psRemoteUtilsName = CopyFileRemoteUtils.PSCopyRemoteUtilsName;
                    ps.Runspace = session.Runspace;
                    ps.AddCommand("Get-Command").AddArgument(psRemoteUtilsName);
                    var result = ps.Invoke<bool>();

                    if (result.Count == 0)
                    {
                        context.WriteError(new ErrorRecord(
                            new InvalidOperationException(
                                String.Format(
                                    System.Globalization.CultureInfo.InvariantCulture,
                                    SessionStateStrings.CopyItemSessionProperties,
                                    "LanguageMode",
                                    session.Runspace.SessionStateProxy.LanguageMode)
                                ),
                                "SessionIsNotInFullLanguageMode",
                                ErrorCategory.InvalidOperation,
                                session.Availability
                            )
                        );

                        return null;
                    }

                    ps.Commands.Clear();
                    ps.Streams.ClearStreams();
                    ps.AddCommand(psRemoteUtilsName);
                }
                else
                {
                    string remoteScript = CopyFileRemoteUtils.PSValidatePathDefinition;
                    ps.AddScript(remoteScript);
                }

                ps.AddParameter("pathToValidate", path);

                if (sourceIsRemote)
                {
                    ps.AddParameter("sourceIsRemote", true);
                }

                op = Microsoft.PowerShell.Commands.SafeInvokeCommand.Invoke(ps, null, context);
            }

            if (op == null)
            {
                context.WriteError(new ErrorRecord(
                                new InvalidOperationException(
                                    String.Format(
                                    System.Globalization.CultureInfo.InvariantCulture, SessionStateStrings.CopyItemValidateRemotePath, path)),
                                    "FailedToValidateRemotePath",
                                    ErrorCategory.InvalidOperation,
                                    path));
                return null;
            }

            // If the remote path is not absolute, display an error to the user.
            if (op["IsAbsolute"] != null)
            {
                bool isAbsolute = (bool)op["IsAbsolute"];
                if (!isAbsolute)
                {
                    context.WriteError(new ErrorRecord(
                                        new ArgumentException(
                                            String.Format(
                                            System.Globalization.CultureInfo.InvariantCulture, SessionStateStrings.CopyItemRemotelyPathIsNotAbsolute, path)),
                                            "RemotePathIsNotAbsolute",
                                            ErrorCategory.InvalidArgument,
                                            path));
                    return null;
                }
            }

            bool pathExist = false;
            string root = null;

            if (op["Exists"] != null)
                pathExist = (bool)op["Exists"];

            if (op["Root"] != null)
                root = (string)op["Root"];

            // Here there are two scenarios:
            // 1) If the source is remote and the path does not exist, error out.
            bool invalidRemoteSource = (sourceIsRemote && (!pathExist));

            // 2) For a remote destination, if the root does not exist, error out.
            bool invalidRemoteDestination = (root == null);

            if (invalidRemoteSource || invalidRemoteDestination)
            {
                context.WriteError(new ErrorRecord(
                                            new ArgumentException(
                                                String.Format(
                                                System.Globalization.CultureInfo.InvariantCulture, SessionStateStrings.PathNotFound, path)),
                                                "RemotePathNotFound",
                                                ErrorCategory.InvalidArgument,
                                                path));
                return null;
            }

            return root;
        }
コード例 #25
0
		internal LocalRunspaceProvider(int timeoutSeconds, PSLanguageMode? languageMode) : this(timeoutSeconds, -1, languageMode)
		{
		}
コード例 #26
0
		internal static Runspace CreateLocalActivityRunspace(PSLanguageMode? languageMode = null, bool useCurrentThreadForExecution = true)
		{
			InitialSessionState initialSessionStateWithSharedTypesAndNoFormat = LocalRunspaceProvider.GetInitialSessionStateWithSharedTypesAndNoFormat();
			if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
			{
				initialSessionStateWithSharedTypesAndNoFormat.LanguageMode = PSLanguageMode.ConstrainedLanguage;
			}
			if (languageMode.HasValue && languageMode.HasValue)
			{
				initialSessionStateWithSharedTypesAndNoFormat.LanguageMode = languageMode.Value;
			}
			SessionStateVariableEntry sessionStateVariableEntry = new SessionStateVariableEntry("RunningInPSWorkflowEndpoint", (object)((bool)1), "True if we're in a Workflow Endpoint", ScopedItemOptions.Constant);
			initialSessionStateWithSharedTypesAndNoFormat.Variables.Add(sessionStateVariableEntry);
			Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionStateWithSharedTypesAndNoFormat);
			if (useCurrentThreadForExecution)
			{
				runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
			}
			return runspace;
		}
コード例 #27
0
        internal LocalRunspaceProvider(int timeoutSeconds, PSLanguageMode? languageMode) : this(timeoutSeconds, DefaultMaxRunspaces, languageMode)
        {

        }
コード例 #28
0
        protected override void ProcessRecord()
        {
            string filePath = this.GetFilePath();

            if (filePath != null)
            {
                if (!File.Exists(filePath))
                {
                    InvalidOperationException exception = PSTraceSource.NewInvalidOperationException("ImportLocalizedData", "FileNotExist", new object[] { filePath });
                    base.WriteError(new ErrorRecord(exception, "ImportLocalizedData", ErrorCategory.ObjectNotFound, filePath));
                }
                else
                {
                    string script = this.GetScript(filePath);
                    if (script != null)
                    {
                        try
                        {
                            object      obj2;
                            ScriptBlock block = base.Context.Engine.ParseScriptBlock(script, false);
                            block.CheckRestrictedLanguage(this.SupportedCommand, null, false);
                            PSLanguageMode languageMode = base.Context.LanguageMode;
                            base.Context.LanguageMode = PSLanguageMode.RestrictedLanguage;
                            try
                            {
                                obj2 = block.InvokeReturnAsIs(new object[0]);
                                if (obj2 == AutomationNull.Value)
                                {
                                    obj2 = null;
                                }
                            }
                            finally
                            {
                                base.Context.LanguageMode = languageMode;
                            }
                            if (this._bindingVariable != null)
                            {
                                VariablePath variablePath = new VariablePath(this._bindingVariable);
                                if (variablePath.IsUnscopedVariable)
                                {
                                    variablePath = variablePath.CloneAndSetLocal();
                                }
                                if (string.IsNullOrEmpty(variablePath.UnqualifiedPath))
                                {
                                    InvalidOperationException exception2 = PSTraceSource.NewInvalidOperationException("ImportLocalizedData", "IncorrectVariableName", new object[] { this._bindingVariable });
                                    base.WriteError(new ErrorRecord(exception2, "ImportLocalizedData", ErrorCategory.InvalidArgument, this._bindingVariable));
                                }
                                else
                                {
                                    SessionStateScope scope        = null;
                                    PSVariable        variableItem = base.SessionState.Internal.GetVariableItem(variablePath, out scope);
                                    if (variableItem == null)
                                    {
                                        variableItem = new PSVariable(variablePath.UnqualifiedPath, obj2, ScopedItemOptions.None);
                                        base.Context.EngineSessionState.SetVariable(variablePath, variableItem, false, CommandOrigin.Internal);
                                    }
                                    else
                                    {
                                        variableItem.Value = obj2;
                                    }
                                }
                            }
                            else
                            {
                                base.WriteObject(obj2);
                            }
                        }
                        catch (RuntimeException exception3)
                        {
                            throw PSTraceSource.NewInvalidOperationException(exception3, "ImportLocalizedData", "ErrorLoadingDataFile", new object[] { filePath, exception3.Message });
                        }
                    }
                }
            }
        }
コード例 #29
0
ファイル: CommandProcessorBase.cs プロジェクト: nickchal/pash
 protected static void ValidateCompatibleLanguageMode(ScriptBlock scriptBlock, PSLanguageMode languageMode, InvocationInfo invocationInfo)
 {
     if (scriptBlock.LanguageMode.HasValue)
     {
         PSLanguageMode? nullable2 = scriptBlock.LanguageMode;
         PSLanguageMode mode = languageMode;
         if (((((PSLanguageMode) nullable2.GetValueOrDefault()) != mode) || !nullable2.HasValue) && ((languageMode == PSLanguageMode.RestrictedLanguage) || (languageMode == PSLanguageMode.ConstrainedLanguage)))
         {
             ErrorRecord errorRecord = new ErrorRecord(new NotSupportedException(DiscoveryExceptions.DotSourceNotSupported), "DotSourceNotSupported", ErrorCategory.InvalidOperation, null);
             errorRecord.SetInvocationInfo(invocationInfo);
             throw new CmdletInvocationException(errorRecord);
         }
     }
 }
コード例 #30
0
        /// <summary>
        /// Creates a workflow activity based on the provided Xaml and returns PowerShell script that will
        /// run the workflow.
        /// </summary>
        /// <param name="name">Workflow name</param>
        /// <param name="xaml">Workflow Xaml definition</param>
        /// <param name="requiredAssemblies">Required assemblies</param>
        /// <param name="dependentWorkflows">Dependent workflows</param>
        /// <param name="dependentAssemblyPath">Path for dependent assemblies</param>
        /// <param name="parameterValidation">Workflow parameters</param>
        /// <param name="modulePath">Module path</param>
        /// <param name="scriptWorkflow">True if this is script workflow</param>
        /// <param name="workflowAttributes">the attribute string to use for the workflow, should be '[CmdletBinding()]'</param>
        /// <param name="scriptContent">File path containing script content.</param>
        /// <param name="fullScript">Full source script.</param>
        /// <param name="rootWorkflowName">Only root Workflow will be compiled</param>
        /// <param name="sourceLanguageMode">Language mode of source that is creating the workflow</param>
        /// <param name="attributeAstCollection">Optional collection of parameter attribute Asts</param>
        /// <returns></returns>
        public static string CreateFunctionFromXaml(
            string name,
            string xaml,
            Dictionary<string, string> requiredAssemblies,
            string[] dependentWorkflows,
            string dependentAssemblyPath,
            Dictionary<string, ParameterAst> parameterValidation,
            string modulePath,
            bool scriptWorkflow,
            string workflowAttributes,
            string scriptContent,
            string fullScript,
            string rootWorkflowName,
            PSLanguageMode? sourceLanguageMode,
            ReadOnlyCollection<AttributeAst> attributeAstCollection
            )
        {
            // check to see if the specified name is allowed
            if (!Regex.IsMatch(name, functionNamePattern))
            {
                throw new PSArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.WorkflowNameInvalid, name));
            }

            WorkflowJobDefinition definition = null;
            Activity workflow = null;

            if (scriptWorkflow)
            {
                workflow = DefinitionCache.Instance.GetActivityFromCache(xaml, out definition);
            }

            if (workflow == null)
            {
                definition = new WorkflowJobDefinition(typeof(WorkflowJobSourceAdapter), name, null, modulePath, dependentWorkflows, dependentAssemblyPath, requiredAssemblies, xaml);
                definition.IsScriptWorkflow = scriptWorkflow;
                bool windowsWorkflow;
                workflow = DefinitionCache.Instance.CompileActivityAndSaveInCache(definition, null, requiredAssemblies,
                                                                                 out windowsWorkflow, rootWorkflowName);
            }

            definition.WorkflowScriptFile = scriptContent;
            definition.WorkflowFullScript = fullScript;

            // this can throw exceptions if the xaml is malformed.
            DynamicActivity daBody = workflow as DynamicActivity;

            StringBuilder innerParamDefinitions = new StringBuilder();
            StringBuilder outerParamDefinitions = new StringBuilder();
            string workflowGuid = definition.InstanceId.ToString();
            Tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "Generating function for name: {0}, WFGuid: {1}", name, workflowGuid));

            // String to hold any updates we do for parameter defaults
            List<string> parametersWithDefaults = new List<string>();
            string defaultUpdates = "";

            // If the workflow is a DynamicActivity, we can use the Properties
            // property to retrieve parameters to the workflow and synthesize
            // PowerShell parameter declarations.
            if (daBody != null)
            {
                foreach (var p in daBody.Properties)
                {
                    // Skip out arguments
                    if (typeof(System.Activities.OutArgument).IsAssignableFrom(p.Type))
                    {
                        continue;
                    }

                    // If the parameter name is one of the expected collisions, don't add it to the list. 
                    if (p.Name.Equals(Constants.ComputerName, StringComparison.OrdinalIgnoreCase) || p.Name.Equals(Constants.PrivateMetadata, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    if (p.Name.Equals("InputObject", StringComparison.OrdinalIgnoreCase) || p.Name.Equals("AsJob", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    string paramTypeName = (string)LanguagePrimitives.ConvertTo(p.Type.GetGenericArguments()[0],
                        typeof(string), CultureInfo.InvariantCulture);

                    string mandatory = "";
                    string parameterDefault = "";

                    // If we got specific validations to add, add those
                    // We only get these in script-based workflow case, but not in XAML case.
                    if ((parameterValidation != null) && parameterValidation.ContainsKey(p.Name))
                    {
                        ParameterAst parameter = parameterValidation[p.Name];

                        foreach (AttributeBaseAst attribute in parameter.Attributes)
                        {
                            innerParamDefinitions.Append(attribute.ToString());
                            innerParamDefinitions.Append("\n                    ");

                            var attributeAst = attribute as AttributeAst;
                            if (attributeAst == null || !string.Equals(attribute.TypeName.Name, "Parameter", StringComparison.OrdinalIgnoreCase))
                            {
                                // If we have a Credential Attribute, it has been added to the inner function, it does not need to be added to the outer definition.
                                // This will prevent prompting for the cred twice.
                                if (!string.Equals(attribute.TypeName.FullName, "System.Management.Automation.CredentialAttribute", StringComparison.OrdinalIgnoreCase))
                                {
                                    outerParamDefinitions.Append(attribute.ToString());
                                    outerParamDefinitions.Append("\n                    ");
                                }

                                continue;
                            }

                            string updatedAttribute = "[Parameter(";
                            bool first = true;
                            foreach (var namedAttribute in attributeAst.NamedArguments)
                            {
                                if (string.Equals(namedAttribute.ArgumentName, "Mandatory",
                                                  StringComparison.OrdinalIgnoreCase))
                                    continue;
                                if (string.Equals(namedAttribute.ArgumentName, "ValueFromPipeline", StringComparison.OrdinalIgnoreCase)
                                    && string.Equals(namedAttribute.Argument.Extent.Text, "$true", StringComparison.OrdinalIgnoreCase))
                                {
                                    throw new PSInvalidOperationException(Resources.ValueFromPipelineNotSupported);
                                }

                                if (!first) updatedAttribute += ",";
                                first = false;
                                updatedAttribute += namedAttribute.ToString();
                            }
                            updatedAttribute += ")]";
                            outerParamDefinitions.Append(updatedAttribute);
                            outerParamDefinitions.Append("\n                    ");
                        }

                        if (parameter.DefaultValue != null)
                        {
                            parameterDefault = " = " + parameter.DefaultValue.ToString();
                            parametersWithDefaults.Add("'" + p.Name + "'");
                        }
                    }
                    // Otherwise, add our default treatment
                    // XAML workflows only go through this code path.
                    // Scriptworkflow ALSO comes through this path.
                    else
                    {
                        // If the parameter is an In parameter with the RequiredArgument attribute then make it mandatory
                        if (typeof(System.Activities.InArgument).IsAssignableFrom(p.Type))
                        {
                            if (p.Attributes != null)
                            {
                                foreach (var attribute in p.Attributes)
                                {
                                    // Check the type of the attribute 
                                    if (attribute.TypeId.GetType() == typeof(RequiredArgumentAttribute))
                                    {
                                        mandatory = "[Parameter(Mandatory=$true)] ";
                                    }
                                }
                            }
                        }
                    }

                    innerParamDefinitions.Append(String.Format(CultureInfo.InvariantCulture,
                        "{0}[{1}] ${2}{3},\n                ",
                            mandatory, paramTypeName, p.Name, parameterDefault));
                    outerParamDefinitions.Append(String.Format(CultureInfo.InvariantCulture,
                        "[{0}] ${1}{2},\n                ",
                            paramTypeName, p.Name, parameterDefault));
                }

                if (parametersWithDefaults.Count > 0)
                {
                    defaultUpdates = @"
                        # Update any parameters that had default values in the workflow
                        $parametersWithDefaults = @(" + String.Join(", ", parametersWithDefaults.ToArray()) + ")\n";
                }
                else
                {
                    defaultUpdates = @"
                    # None of the workflow parameters had default values
                    $parametersWithDefaults = @()";
                }

                // Add code into the function to handle PSParameterCollection parameter if present.
                defaultUpdates += @"
                    trap { break }
                    $parameterCollectionProcessed = $false
                    $PSParameterCollectionDefaultsMember = $null
                    $suspendOnError = $false

                    if ($PSBoundParameters.ContainsKey('PSParameterCollection'))
                    {
                        # validate parameters used with PSParameterCollection
                        foreach ($pa in $PSBoundParameters.Keys)
                        {
                            if ($pa -eq 'JobName' -or $pa -eq 'AsJob' -or $pa -eq 'InputObject' -or $pa -eq 'PSParameterCollection')
                            {
                                continue
                            }
                            $msg = [Microsoft.PowerShell.Commands.ImportWorkflowCommand]::InvalidPSParameterCollectionAdditionalErrorMessage;
                            throw (New-Object System.Management.Automation.ErrorRecord $msg, StartWorkflow.InvalidArgument, InvalidArgument, $PSParameterCollection)
                        }
                        $parameterCollectionProcessed = $true

                        # See if there is a defaults collection, indicated by '*'
                        foreach ($collection in $PSParameterCollection)
                        {
                            if ($collection['" + Constants.ComputerName + @"'] -eq '*' )
                            {
                                if ($PSParameterCollectionDefaultsMember -ne $null)
                                {
                                    $msg = [Microsoft.PowerShell.Commands.ImportWorkflowCommand]::ParameterErrorMessage;
                                    throw ( New-Object System.Management.Automation.ErrorRecord $msg, StartWorkflow.InvalidArgument, InvalidArgument, $PSParameterCollection)
                                }
                                $PSParameterCollectionDefaultsMember = $collection;
                                foreach($parameter in $parametersWithDefaults)
                                {
                                    if(! $collection.ContainsKey($parameter))
                                    {
                                        $collection[$parameter] = (Get-Variable $parameter).Value
                                    }
                                }
                            }
                        }

                        $PSParameterCollection = [Microsoft.PowerShell.Commands.ImportWorkflowCommand]::MergeParameterCollection(
                                        $PSParameterCollection, $PSParameterCollectionDefaultsMember)

                        # canonicalize each collection...
                        $PSParameterCollection = foreach ( $c in $PSParameterCollection) {
                            if($c.containskey('AsJob') -or $c.containsKey('JobName') -or $c.containsKey('PSParameterCollection') -or $c.containsKey('InputObject'))
                            {
                                    $msg = [Microsoft.PowerShell.Commands.ImportWorkflowCommand]::InvalidPSParameterCollectionEntryErrorMessage;
                                    throw ( New-Object System.Management.Automation.ErrorRecord $msg, StartWorkflow.InvalidArgument, InvalidArgument, $PSParameterCollection)
                            }

                            if ($c['" + Constants.ErrorAction + @"'] -eq ""Suspend"")
                            {
                                $suspendOnError = $true
                                $c['" + Constants.ErrorAction + @"'] = ""Continue""
                            }

                            $validated = & """ + name + @""" @c
                            $validated['" + Constants.PSSuspendOnError + @"'] = $suspendOnError
                            $validated
                        }

                        # If there was no '*' collection, added the parameter defaults
                        # to each individual collection if the parameter isn't already there... 
                        if (-not $PSParameterCollectionDefaultsMember)
                        {
                            foreach ($collection in $PSParameterCollection)
                            {
                                foreach($parameter in $parametersWithDefaults)
                                {
                                    if(! $collection.ContainsKey($parameter))
                                    {
                                        $collection[$parameter] = (Get-Variable $parameter).Value
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if ($PSBoundParameters['" + Constants.ErrorAction + @"'] -eq ""Suspend"")
                        {
                            $errorActionPreference = ""Continue""
                            $suspendOnError = $true
                            $PSBoundParameters['" + Constants.ErrorAction + @"'] = ""Continue""
                        }

                        $PSBoundParameters = & """ + name + @""" @PSBoundParameters

                        # no PSParameterCollection so add the default values to PSBoundParameters
                        foreach($parameter in $parametersWithDefaults)
                        {
                            if(! $PSBoundParameters.ContainsKey($parameter))
                            {
                                $PSBoundParameters[$parameter] = (Get-Variable $parameter).Value
                            }
                        }
                    }
                    ";
            }

            // Escaping the single quotes from the module path
            modulePath = CodeGeneration.EscapeSingleQuotedStringContent(modulePath);

            //Generate the PowerShell function template
            string functionPrefixTemplate = AddCommonWfParameters(false, workflowAttributes);
            string validationFunctionPrefixTemplate = AddCommonWfParameters(true, workflowAttributes);

            string outerParamDefinitionsString = outerParamDefinitions.ToString();
            outerParamDefinitionsString = CodeGeneration.EscapeFormatStringContent(outerParamDefinitionsString);
            string functionPrefix = String.Format(CultureInfo.InvariantCulture, functionPrefixTemplate, outerParamDefinitionsString);

            // Generate the param block for the synthesized function
            string innerParamDefinitionsString = innerParamDefinitions.ToString();
            innerParamDefinitionsString = CodeGeneration.EscapeFormatStringContent(innerParamDefinitionsString);
            // For the parameter validation function, add an extra param definition for $PSInputCollection
            string validationFunctionPrefix = String.Format(CultureInfo.InvariantCulture, validationFunctionPrefixTemplate, innerParamDefinitionsString + "$PSInputCollection");

            StringBuilder completeFunctionDefinitionTemplate = new StringBuilder();
            completeFunctionDefinitionTemplate.AppendLine(functionPrefix);
            completeFunctionDefinitionTemplate.AppendLine("        begin {{");
            completeFunctionDefinitionTemplate.AppendLine("                function " + name + "  {{");
            completeFunctionDefinitionTemplate.AppendLine(validationFunctionPrefix);
            completeFunctionDefinitionTemplate.AppendLine("                     $PSBoundParameters");
            completeFunctionDefinitionTemplate.AppendLine("              }}");
            completeFunctionDefinitionTemplate.AppendLine(FunctionBodyTemplate);

            // Mark the function definition with sourceLanguageMode (language mode that function can run under, i.e.,
            // as trusted or not trusted), unless the workflow script is marked with the "SecurityCritical" attribute in 
            // which case the function will always be run under the current system lock down setting.
            bool isSecurityCritical = ContainsSecurityCriticalAttribute(attributeAstCollection);
            string sourceLanguageModeStr = (!isSecurityCritical && (sourceLanguageMode != null)) ? sourceLanguageMode.ToString() : string.Empty;

            // Combine the pieces to create the complete function
            string functionDefinition = String.Format(CultureInfo.InvariantCulture, completeFunctionDefinitionTemplate.ToString(),
                     defaultUpdates, workflowGuid, modulePath, sourceLanguageModeStr);

#if DEBUG
            // Verify that the generated function is valid powershell. This is only an issue when changing the
            // generation code so it's debug only...
            Collection<PSParseError> templateErrors = null;
            System.Management.Automation.PSParser.Tokenize(functionDefinition, out templateErrors);
            if (templateErrors != null && templateErrors.Count > 0)
            {
                StringBuilder message = new StringBuilder();
                foreach (PSParseError parseErr in templateErrors)
                {
                    message.Append(parseErr.Token.Content).Append(':').Append(parseErr.Message).Append("\n");
                }
                message.Append("`nFunction code:`n").Append(functionDefinition);
                throw new InvalidOperationException(message.ToString());
            }
#endif
            workflow = null;
            daBody = null;

            // strip the comments in fre build
#if !DEBUG
            functionDefinition = System.Text.RegularExpressions.Regex.Replace(functionDefinition, "^ *\\#.*$", "", RegexOptions.Multiline);
#endif
            return functionDefinition;
        }
 // Token: 0x060013D2 RID: 5074 RVA: 0x00046180 File Offset: 0x00044380
 internal ExchangeRunspaceConfigurationSettings(Uri connectionUri, ExchangeRunspaceConfigurationSettings.ExchangeApplication clientApplication, string tenantOrganization, ExchangeRunspaceConfigurationSettings.SerializationLevel serializationLevel, PSLanguageMode languageMode, ExchangeRunspaceConfigurationSettings.ProxyMethod proxyMethod, bool proxyFullSerialization, bool encodeDecodeKey, bool isProxy, ExchangeRunspaceConfigurationSettings.ExchangeUserType user, IEnumerable <KeyValuePair <string, string> > additionalConstraints)
 {
     this.clientApplication      = clientApplication;
     this.serializationLevel     = serializationLevel;
     this.tenantOrganization     = tenantOrganization;
     this.languageMode           = languageMode;
     this.originalConnectionUri  = connectionUri;
     this.proxyMethod            = proxyMethod;
     this.proxyFullSerialization = proxyFullSerialization;
     this.EncodeDecodeKey        = encodeDecodeKey;
     this.IsProxy  = isProxy;
     this.UserType = user;
     this.additionalConstraints = additionalConstraints;
 }
コード例 #32
0
ファイル: Debugger.cs プロジェクト: modulexcite/pash-1
        private void OnDebuggerStop(InvocationInfo invocationInfo, List <Breakpoint> breakpoints)
        {
            LocalRunspace currentRunspace = this._context.CurrentRunspace as LocalRunspace;

            if ((currentRunspace.PulsePipeline != null) && (currentRunspace.PulsePipeline == currentRunspace.GetCurrentlyRunningPipeline()))
            {
                this._context.EngineHostInterface.UI.WriteWarningLine((breakpoints.Count > 0) ? string.Format(CultureInfo.CurrentCulture, DebuggerStrings.WarningBreakpointWillNotBeHit, new object[] { breakpoints[0] }) : new InvalidOperationException().Message);
            }
            else
            {
                this._steppingMode = SteppingMode.None;
                EventHandler <DebuggerStopEventArgs> debuggerStop = this.DebuggerStop;
                if (debuggerStop != null)
                {
                    this.InBreakpoint = true;
                    this._context.SetVariable(SpecialVariables.PSDebugContextVarPath, new PSDebugContext(invocationInfo, breakpoints));
                    FunctionInfo baseObject = null;
                    bool         flag       = false;
                    try
                    {
                        Collection <PSObject> collection = this._context.SessionState.InvokeProvider.Item.Get(@"function:\prompt");
                        if ((collection != null) && (collection.Count > 0))
                        {
                            baseObject = collection[0].BaseObject as FunctionInfo;
                            if (string.Equals(baseObject.Definition, InitialSessionState.DefaultPromptString, StringComparison.OrdinalIgnoreCase))
                            {
                                flag = true;
                            }
                        }
                    }
                    catch (ItemNotFoundException)
                    {
                    }
                    if (flag)
                    {
                        string script = "\"[DBG]: PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) \"";
                        baseObject.Update(ScriptBlock.Create(script), true, ScopedItemOptions.Unspecified);
                    }
                    PSLanguageMode languageMode = this._context.LanguageMode;
                    PSLanguageMode?nullable     = null;
                    if (this._context.UseFullLanguageModeInDebugger && (this._context.LanguageMode != PSLanguageMode.FullLanguage))
                    {
                        nullable = new PSLanguageMode?(this._context.LanguageMode);
                        this._context.LanguageMode = PSLanguageMode.FullLanguage;
                    }
                    else if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
                    {
                        nullable = new PSLanguageMode?(this._context.LanguageMode);
                        this._context.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                    }
                    RunspaceAvailability runspaceAvailability = this._context.CurrentRunspace.RunspaceAvailability;
                    this._context.CurrentRunspace.UpdateRunspaceAvailability((this._context.CurrentRunspace.GetCurrentlyRunningPipeline() != null) ? RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available, true);
                    try
                    {
                        this._context._debuggingMode = -1;
                        if (this._callStack.Any <CallStackInfo>())
                        {
                            this._callStack.Last <CallStackInfo>().TopFrameAtBreakpoint = true;
                        }
                        DebuggerStopEventArgs e = new DebuggerStopEventArgs(invocationInfo, breakpoints);
                        debuggerStop(this, e);
                        this.ResumeExecution(e.ResumeAction);
                    }
                    finally
                    {
                        this._context._debuggingMode = 1;
                        if (this._callStack.Any <CallStackInfo>())
                        {
                            this._callStack.Last <CallStackInfo>().TopFrameAtBreakpoint = false;
                        }
                        this._context.CurrentRunspace.UpdateRunspaceAvailability(runspaceAvailability, true);
                        if (nullable.HasValue)
                        {
                            this._context.LanguageMode = nullable.Value;
                        }
                        this._context.EngineSessionState.RemoveVariable("PSDebugContext");
                        if (flag)
                        {
                            baseObject.Update(ScriptBlock.Create(InitialSessionState.DefaultPromptString), true, ScopedItemOptions.Unspecified);
                        }
                        this.InBreakpoint = false;
                    }
                }
            }
        }
コード例 #33
0
        /// <summary>
        /// Creates a local runspace with the autoloading turned on.
        /// </summary>
        /// <returns></returns>
        internal static Runspace CreateLocalActivityRunspace(PSLanguageMode? languageMode = null, bool useCurrentThreadForExecution = true)
        {
            InitialSessionState iss = GetInitialSessionStateWithSharedTypesAndNoFormat();
            if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
            {
                iss.LanguageMode = PSLanguageMode.ConstrainedLanguage;
            }

            if (languageMode != null && languageMode.HasValue)
            {
                iss.LanguageMode = languageMode.Value;
            }

            // Add a variable indicating that we're in Workflow endpoint. This enables the
            // autoloading feature.
            SessionStateVariableEntry ssve = new SessionStateVariableEntry("RunningInPSWorkflowEndpoint",
                true, "True if we're in a Workflow Endpoint", ScopedItemOptions.Constant);
            iss.Variables.Add(ssve);
            Runspace runspace = RunspaceFactory.CreateRunspace(iss);

            if (useCurrentThreadForExecution)
                runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;

            return runspace;
        }
コード例 #34
0
ファイル: ActivityHostProcess.cs プロジェクト: 40a/PowerShell
 internal ActivityHostProcess(int activityHostTimeoutSec, PSLanguageMode? languageMode)
 {
     _languageMode = languageMode;
     _useJobIPCProcess = true;
     _tracer.WriteMessage("BEGIN Creating new PowerShell process instance");
     _processInstance = new PowerShellProcessInstance();
     _tracer.WriteMessage("END Creating new PowerShell process instance ");
     _runspace = CreateRunspace();
     _tracer.WriteMessage("New runspace created ", _runspace.InstanceId.ToString());
     _timer = new Timer {AutoReset = false, Interval = TimeOut};
     _timer.Elapsed += TimerElapsed;
     _timer.Interval = activityHostTimeoutSec > 0 ? activityHostTimeoutSec*1000 : TimeOut;
     _perfCountersMgr.UpdateCounterByValue(
         PSWorkflowPerformanceCounterSetInfo.CounterSetId,
         PSWorkflowPerformanceCounterIds.ActivityHostMgrCreatedProcessesCount);
 }
コード例 #35
0
 protected override void ProcessRecord()
 {
     ProviderInfo provider = null;
     PSDriveInfo info2;
     FileStream stream;
     StreamWriter writer;
     FileInfo info3;
     string filePath = base.SessionState.Path.GetUnresolvedProviderPathFromPSPath(this.path, out provider, out info2);
     if (!provider.NameEquals(base.Context.ProviderNames.FileSystem) || !filePath.EndsWith(".pssc", StringComparison.OrdinalIgnoreCase))
     {
         InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, this.path));
         ErrorRecord errorRecord = new ErrorRecord(exception, "InvalidPSSessionConfigurationFilePath", ErrorCategory.InvalidArgument, this.path);
         base.ThrowTerminatingError(errorRecord);
     }
     PathUtils.MasterStreamOpen(this, filePath, "unicode", false, false, false, false, out stream, out writer, out info3, false);
     try
     {
         StringBuilder builder = new StringBuilder();
         builder.Append("@{");
         builder.Append(writer.NewLine);
         builder.Append(writer.NewLine);
         builder.Append(ConfigFragment(ConfigFileContants.SchemaVersion, RemotingErrorIdStrings.DISCSchemaVersionComment, QuoteName(this.schemaVersion.ToString()), writer));
         builder.Append(ConfigFragment(ConfigFileContants.Guid, RemotingErrorIdStrings.DISCGUIDComment, QuoteName(this.guid.ToString()), writer));
         builder.Append(ConfigFragment(ConfigFileContants.ExecutionPolicy, RemotingErrorIdStrings.DISCExecutionPolicyComment, QuoteName(this.executionPolicy), writer));
         if (!this.isLanguageModeSpecified && (this.initialSessionState == System.Management.Automation.Remoting.SessionType.Default))
         {
             this.languageMode = PSLanguageMode.FullLanguage;
         }
         builder.Append(ConfigFragment(ConfigFileContants.LanguageMode, RemotingErrorIdStrings.DISCLanguageModeComment, QuoteName(this.languageMode), writer));
         builder.Append(ConfigFragment(ConfigFileContants.SessionType, RemotingErrorIdStrings.DISCInitialSessionStateComment, QuoteName(this.initialSessionState.ToString()), writer));
         if (this.environmentVariables == null)
         {
             builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, string.Empty, writer));
         }
         else
         {
             string environmentVariables = this.environmentVariables as string;
             if (environmentVariables != null)
             {
                 builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, environmentVariables, writer));
             }
             else
             {
                 Hashtable table = this.environmentVariables as Hashtable;
                 if (table != null)
                 {
                     builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, this.CombineHashtable(table, writer), writer));
                 }
                 else
                 {
                     builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, string.Empty, writer));
                 }
             }
         }
         if (string.IsNullOrEmpty(this.author))
         {
             this.author = Environment.UserName;
         }
         builder.Append(ConfigFragment(ConfigFileContants.Author, RemotingErrorIdStrings.DISCAuthorComment, QuoteName(this.author), writer));
         if (string.IsNullOrEmpty(this.companyName))
         {
             this.companyName = Modules.DefaultCompanyName;
         }
         builder.Append(ConfigFragment(ConfigFileContants.CompanyName, RemotingErrorIdStrings.DISCCompanyNameComment, QuoteName(this.companyName), writer));
         if (string.IsNullOrEmpty(this.copyright))
         {
             this.copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, DateTime.Now.Year, this.author);
         }
         builder.Append(ConfigFragment(ConfigFileContants.Copyright, RemotingErrorIdStrings.DISCCopyrightComment, QuoteName(this.copyright), writer));
         builder.Append(ConfigFragment(ConfigFileContants.Description, RemotingErrorIdStrings.DISCDescriptionComment, string.IsNullOrEmpty(this.description) ? string.Empty : QuoteName(this.description), writer));
         builder.Append(ConfigFragment(ConfigFileContants.PowerShellVersion, RemotingErrorIdStrings.DISCPowerShellVersionComment, (this.powerShellVersion != null) ? QuoteName(this.powerShellVersion.ToString()) : string.Empty, writer));
         builder.Append(ConfigFragment(ConfigFileContants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, (this.modulesToImport != null) ? this.CombineHashTableOrStringArray(this.modulesToImport, writer) : string.Empty, writer));
         builder.Append(ConfigFragment(ConfigFileContants.AssembliesToLoad, RemotingErrorIdStrings.DISCAssembliesToLoadComment, (this.assembliesToLoad != null) ? this.CombineStringArray(this.assembliesToLoad) : string.Empty, writer));
         builder.Append(ConfigFragment(ConfigFileContants.VisibleAliases, RemotingErrorIdStrings.DISCVisibleAliasesComment, this.GetVisibilityDefault(this.visibleAliases), writer));
         builder.Append(ConfigFragment(ConfigFileContants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment, this.GetVisibilityDefault(this.visibleCmdlets), writer));
         builder.Append(ConfigFragment(ConfigFileContants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment, this.GetVisibilityDefault(this.visibleFunctions), writer));
         builder.Append(ConfigFragment(ConfigFileContants.VisibleProviders, RemotingErrorIdStrings.DISCVisibleProvidersComment, this.GetVisibilityDefault(this.visibleProviders), writer));
         builder.Append(ConfigFragment(ConfigFileContants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment, (this.aliasDefinitions != null) ? this.CombineHashtableArray(this.aliasDefinitions, writer) : string.Empty, writer));
         if (this.functionDefinitions == null)
         {
             builder.Append(ConfigFragment(ConfigFileContants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment, string.Empty, writer));
         }
         else
         {
             Hashtable[] tables = DISCPowerShellConfiguration.TryGetHashtableArray(this.functionDefinitions);
             if (tables != null)
             {
                 builder.Append(ConfigFragment(ConfigFileContants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment, this.CombineHashtableArray(tables, writer), writer));
                 foreach (Hashtable hashtable2 in tables)
                 {
                     if (!hashtable2.ContainsKey(ConfigFileContants.FunctionNameToken))
                     {
                         PSArgumentException exception2 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.FunctionDefinitions, ConfigFileContants.FunctionNameToken, this.path }));
                         base.ThrowTerminatingError(exception2.ErrorRecord);
                     }
                     if (!hashtable2.ContainsKey(ConfigFileContants.FunctionValueToken))
                     {
                         PSArgumentException exception3 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.FunctionDefinitions, ConfigFileContants.FunctionValueToken, this.path }));
                         base.ThrowTerminatingError(exception3.ErrorRecord);
                     }
                     if (!(hashtable2[ConfigFileContants.FunctionValueToken] is ScriptBlock))
                     {
                         PSArgumentException exception4 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock, new object[] { ConfigFileContants.FunctionValueToken, ConfigFileContants.FunctionDefinitions, this.path }));
                         base.ThrowTerminatingError(exception4.ErrorRecord);
                     }
                     foreach (string str4 in hashtable2.Keys)
                     {
                         if ((!string.Equals(str4, ConfigFileContants.FunctionNameToken, StringComparison.OrdinalIgnoreCase) && !string.Equals(str4, ConfigFileContants.FunctionValueToken, StringComparison.OrdinalIgnoreCase)) && !string.Equals(str4, ConfigFileContants.FunctionOptionsToken, StringComparison.OrdinalIgnoreCase))
                         {
                             PSArgumentException exception5 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, new object[] { str4, ConfigFileContants.FunctionDefinitions, this.path }));
                             base.ThrowTerminatingError(exception5.ErrorRecord);
                         }
                     }
                 }
             }
             else
             {
                 PSArgumentException exception6 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, ConfigFileContants.FunctionDefinitions, filePath));
                 base.ThrowTerminatingError(exception6.ErrorRecord);
             }
         }
         if (this.variableDefinitions == null)
         {
             builder.Append(ConfigFragment(ConfigFileContants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, string.Empty, writer));
         }
         else
         {
             string variableDefinitions = this.variableDefinitions as string;
             if (variableDefinitions != null)
             {
                 builder.Append(ConfigFragment(ConfigFileContants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, variableDefinitions, writer));
             }
             else
             {
                 Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.variableDefinitions);
                 if (hashtableArray2 != null)
                 {
                     builder.Append(ConfigFragment(ConfigFileContants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, this.CombineHashtableArray(hashtableArray2, writer), writer));
                     foreach (Hashtable hashtable3 in hashtableArray2)
                     {
                         if (!hashtable3.ContainsKey(ConfigFileContants.VariableNameToken))
                         {
                             PSArgumentException exception7 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.VariableDefinitions, ConfigFileContants.VariableNameToken, this.path }));
                             base.ThrowTerminatingError(exception7.ErrorRecord);
                         }
                         if (!hashtable3.ContainsKey(ConfigFileContants.VariableValueToken))
                         {
                             PSArgumentException exception8 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.VariableDefinitions, ConfigFileContants.VariableValueToken, this.path }));
                             base.ThrowTerminatingError(exception8.ErrorRecord);
                         }
                         foreach (string str6 in hashtable3.Keys)
                         {
                             if (!string.Equals(str6, ConfigFileContants.VariableNameToken, StringComparison.OrdinalIgnoreCase) && !string.Equals(str6, ConfigFileContants.VariableValueToken, StringComparison.OrdinalIgnoreCase))
                             {
                                 PSArgumentException exception9 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, new object[] { str6, ConfigFileContants.VariableDefinitions, this.path }));
                                 base.ThrowTerminatingError(exception9.ErrorRecord);
                             }
                         }
                     }
                 }
                 else
                 {
                     PSArgumentException exception10 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, ConfigFileContants.VariableDefinitions, filePath));
                     base.ThrowTerminatingError(exception10.ErrorRecord);
                 }
             }
         }
         builder.Append(ConfigFragment(ConfigFileContants.TypesToProcess, RemotingErrorIdStrings.DISCTypesToProcessComment, (this.typesToProcess != null) ? this.CombineStringArray(this.typesToProcess) : string.Empty, writer));
         builder.Append(ConfigFragment(ConfigFileContants.FormatsToProcess, RemotingErrorIdStrings.DISCFormatsToProcessComment, (this.formatsToProcess != null) ? this.CombineStringArray(this.formatsToProcess) : string.Empty, writer));
         builder.Append(ConfigFragment(ConfigFileContants.ScriptsToProcess, RemotingErrorIdStrings.DISCScriptsToProcessComment, (this.scriptsToProcess != null) ? this.CombineStringArray(this.scriptsToProcess) : string.Empty, writer));
         builder.Append("}");
         builder.Append(writer.NewLine);
         builder.Append(writer.NewLine);
         writer.Write(builder.ToString());
     }
     finally
     {
         writer.Close();
     }
 }
コード例 #36
0
ファイル: PSScriptCmdlet.cs プロジェクト: modulexcite/pash-1
        private void RunClause(Action <FunctionContext> clause, object dollarUnderbar, object inputToProcess)
        {
            Pipe           shellFunctionErrorOutputPipe = base.Context.ShellFunctionErrorOutputPipe;
            PSLanguageMode?nullable  = null;
            PSLanguageMode?nullable2 = null;

            if (this._scriptBlock.LanguageMode.HasValue)
            {
                PSLanguageMode?languageMode = this._scriptBlock.LanguageMode;
                PSLanguageMode mode         = base.Context.LanguageMode;
                if ((((PSLanguageMode)languageMode.GetValueOrDefault()) != mode) || !languageMode.HasValue)
                {
                    nullable  = new PSLanguageMode?(base.Context.LanguageMode);
                    nullable2 = this._scriptBlock.LanguageMode;
                }
            }
            try
            {
                try
                {
                    this.EnterScope();
                    if (this._commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output)
                    {
                        base.Context.RedirectErrorPipe(this._commandRuntime.OutputPipe);
                    }
                    else if (this._commandRuntime.ErrorOutputPipe.IsRedirected)
                    {
                        base.Context.RedirectErrorPipe(this._commandRuntime.ErrorOutputPipe);
                    }
                    if (dollarUnderbar != AutomationNull.Value)
                    {
                        this._localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, base.Context);
                    }
                    if (inputToProcess != AutomationNull.Value)
                    {
                        this._localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, base.Context);
                    }
                    if (nullable2.HasValue)
                    {
                        base.Context.LanguageMode = nullable2.Value;
                    }
                    clause(this._functionContext);
                }
                catch (TargetInvocationException exception)
                {
                    throw exception.InnerException;
                }
                finally
                {
                    base.Context.RestoreErrorPipe(shellFunctionErrorOutputPipe);
                    if (nullable.HasValue)
                    {
                        base.Context.LanguageMode = nullable.Value;
                    }
                    this.ExitScope();
                }
            }
            catch (ExitException exception2)
            {
                if (!this._fromScriptFile || this._rethrowExitException)
                {
                    throw;
                }
                this._exitWasCalled = true;
                int argument = (int)exception2.Argument;
                base.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, argument);
                if (argument != 0)
                {
                    this._commandRuntime.PipelineProcessor.ExecutionFailed = true;
                }
            }
            catch (TerminateException)
            {
                throw;
            }
            catch (RuntimeException)
            {
                throw;
            }
            catch (Exception exception3)
            {
                CommandProcessorBase.CheckForSevereException(exception3);
                throw;
            }
        }
コード例 #37
0
        private bool isValidSession(PSSession session, CmdletProviderContext context, out PSLanguageMode? languageMode)
        {
            // session == null is validated by the parameter binding
            if (session.Availability != RunspaceAvailability.Available)
            {
                context.WriteError(new ErrorRecord(
                                    new InvalidOperationException(
                                        String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                            SessionStateStrings.CopyItemSessionProperties,
                                            "Availability", session.Availability)),
                                            "SessionIsNotAvailable",
                                        ErrorCategory.InvalidOperation,
                                        session.Availability));

                languageMode = null;
                return false;
            }

            languageMode = session.Runspace.SessionStateProxy.LanguageMode;

            return true;
        }
コード例 #38
0
        protected override void ProcessRecord()
        {
            ProviderInfo provider = null;
            PSDriveInfo  info2;
            FileStream   stream;
            StreamWriter writer;
            FileInfo     info3;
            string       filePath = base.SessionState.Path.GetUnresolvedProviderPathFromPSPath(this.path, out provider, out info2);

            if (!provider.NameEquals(base.Context.ProviderNames.FileSystem) || !filePath.EndsWith(".pssc", StringComparison.OrdinalIgnoreCase))
            {
                InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, this.path));
                ErrorRecord errorRecord             = new ErrorRecord(exception, "InvalidPSSessionConfigurationFilePath", ErrorCategory.InvalidArgument, this.path);
                base.ThrowTerminatingError(errorRecord);
            }
            PathUtils.MasterStreamOpen(this, filePath, "unicode", false, false, false, false, out stream, out writer, out info3, false);
            try
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("@{");
                builder.Append(writer.NewLine);
                builder.Append(writer.NewLine);
                builder.Append(ConfigFragment(ConfigFileContants.SchemaVersion, RemotingErrorIdStrings.DISCSchemaVersionComment, QuoteName(this.schemaVersion.ToString()), writer));
                builder.Append(ConfigFragment(ConfigFileContants.Guid, RemotingErrorIdStrings.DISCGUIDComment, QuoteName(this.guid.ToString()), writer));
                builder.Append(ConfigFragment(ConfigFileContants.ExecutionPolicy, RemotingErrorIdStrings.DISCExecutionPolicyComment, QuoteName(this.executionPolicy), writer));
                if (!this.isLanguageModeSpecified && (this.initialSessionState == System.Management.Automation.Remoting.SessionType.Default))
                {
                    this.languageMode = PSLanguageMode.FullLanguage;
                }
                builder.Append(ConfigFragment(ConfigFileContants.LanguageMode, RemotingErrorIdStrings.DISCLanguageModeComment, QuoteName(this.languageMode), writer));
                builder.Append(ConfigFragment(ConfigFileContants.SessionType, RemotingErrorIdStrings.DISCInitialSessionStateComment, QuoteName(this.initialSessionState.ToString()), writer));
                if (this.environmentVariables == null)
                {
                    builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, string.Empty, writer));
                }
                else
                {
                    string environmentVariables = this.environmentVariables as string;
                    if (environmentVariables != null)
                    {
                        builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, environmentVariables, writer));
                    }
                    else
                    {
                        Hashtable table = this.environmentVariables as Hashtable;
                        if (table != null)
                        {
                            builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, this.CombineHashtable(table, writer), writer));
                        }
                        else
                        {
                            builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, string.Empty, writer));
                        }
                    }
                }
                if (string.IsNullOrEmpty(this.author))
                {
                    this.author = Environment.UserName;
                }
                builder.Append(ConfigFragment(ConfigFileContants.Author, RemotingErrorIdStrings.DISCAuthorComment, QuoteName(this.author), writer));
                if (string.IsNullOrEmpty(this.companyName))
                {
                    this.companyName = Modules.DefaultCompanyName;
                }
                builder.Append(ConfigFragment(ConfigFileContants.CompanyName, RemotingErrorIdStrings.DISCCompanyNameComment, QuoteName(this.companyName), writer));
                if (string.IsNullOrEmpty(this.copyright))
                {
                    this.copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, DateTime.Now.Year, this.author);
                }
                builder.Append(ConfigFragment(ConfigFileContants.Copyright, RemotingErrorIdStrings.DISCCopyrightComment, QuoteName(this.copyright), writer));
                builder.Append(ConfigFragment(ConfigFileContants.Description, RemotingErrorIdStrings.DISCDescriptionComment, string.IsNullOrEmpty(this.description) ? string.Empty : QuoteName(this.description), writer));
                builder.Append(ConfigFragment(ConfigFileContants.PowerShellVersion, RemotingErrorIdStrings.DISCPowerShellVersionComment, (this.powerShellVersion != null) ? QuoteName(this.powerShellVersion.ToString()) : string.Empty, writer));
                builder.Append(ConfigFragment(ConfigFileContants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, (this.modulesToImport != null) ? this.CombineHashTableOrStringArray(this.modulesToImport, writer) : string.Empty, writer));
                builder.Append(ConfigFragment(ConfigFileContants.AssembliesToLoad, RemotingErrorIdStrings.DISCAssembliesToLoadComment, (this.assembliesToLoad != null) ? this.CombineStringArray(this.assembliesToLoad) : string.Empty, writer));
                builder.Append(ConfigFragment(ConfigFileContants.VisibleAliases, RemotingErrorIdStrings.DISCVisibleAliasesComment, this.GetVisibilityDefault(this.visibleAliases), writer));
                builder.Append(ConfigFragment(ConfigFileContants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment, this.GetVisibilityDefault(this.visibleCmdlets), writer));
                builder.Append(ConfigFragment(ConfigFileContants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment, this.GetVisibilityDefault(this.visibleFunctions), writer));
                builder.Append(ConfigFragment(ConfigFileContants.VisibleProviders, RemotingErrorIdStrings.DISCVisibleProvidersComment, this.GetVisibilityDefault(this.visibleProviders), writer));
                builder.Append(ConfigFragment(ConfigFileContants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment, (this.aliasDefinitions != null) ? this.CombineHashtableArray(this.aliasDefinitions, writer) : string.Empty, writer));
                if (this.functionDefinitions == null)
                {
                    builder.Append(ConfigFragment(ConfigFileContants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment, string.Empty, writer));
                }
                else
                {
                    Hashtable[] tables = DISCPowerShellConfiguration.TryGetHashtableArray(this.functionDefinitions);
                    if (tables != null)
                    {
                        builder.Append(ConfigFragment(ConfigFileContants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment, this.CombineHashtableArray(tables, writer), writer));
                        foreach (Hashtable hashtable2 in tables)
                        {
                            if (!hashtable2.ContainsKey(ConfigFileContants.FunctionNameToken))
                            {
                                PSArgumentException exception2 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.FunctionDefinitions, ConfigFileContants.FunctionNameToken, this.path }));
                                base.ThrowTerminatingError(exception2.ErrorRecord);
                            }
                            if (!hashtable2.ContainsKey(ConfigFileContants.FunctionValueToken))
                            {
                                PSArgumentException exception3 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.FunctionDefinitions, ConfigFileContants.FunctionValueToken, this.path }));
                                base.ThrowTerminatingError(exception3.ErrorRecord);
                            }
                            if (!(hashtable2[ConfigFileContants.FunctionValueToken] is ScriptBlock))
                            {
                                PSArgumentException exception4 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock, new object[] { ConfigFileContants.FunctionValueToken, ConfigFileContants.FunctionDefinitions, this.path }));
                                base.ThrowTerminatingError(exception4.ErrorRecord);
                            }
                            foreach (string str4 in hashtable2.Keys)
                            {
                                if ((!string.Equals(str4, ConfigFileContants.FunctionNameToken, StringComparison.OrdinalIgnoreCase) && !string.Equals(str4, ConfigFileContants.FunctionValueToken, StringComparison.OrdinalIgnoreCase)) && !string.Equals(str4, ConfigFileContants.FunctionOptionsToken, StringComparison.OrdinalIgnoreCase))
                                {
                                    PSArgumentException exception5 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, new object[] { str4, ConfigFileContants.FunctionDefinitions, this.path }));
                                    base.ThrowTerminatingError(exception5.ErrorRecord);
                                }
                            }
                        }
                    }
                    else
                    {
                        PSArgumentException exception6 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, ConfigFileContants.FunctionDefinitions, filePath));
                        base.ThrowTerminatingError(exception6.ErrorRecord);
                    }
                }
                if (this.variableDefinitions == null)
                {
                    builder.Append(ConfigFragment(ConfigFileContants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, string.Empty, writer));
                }
                else
                {
                    string variableDefinitions = this.variableDefinitions as string;
                    if (variableDefinitions != null)
                    {
                        builder.Append(ConfigFragment(ConfigFileContants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, variableDefinitions, writer));
                    }
                    else
                    {
                        Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.variableDefinitions);
                        if (hashtableArray2 != null)
                        {
                            builder.Append(ConfigFragment(ConfigFileContants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, this.CombineHashtableArray(hashtableArray2, writer), writer));
                            foreach (Hashtable hashtable3 in hashtableArray2)
                            {
                                if (!hashtable3.ContainsKey(ConfigFileContants.VariableNameToken))
                                {
                                    PSArgumentException exception7 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.VariableDefinitions, ConfigFileContants.VariableNameToken, this.path }));
                                    base.ThrowTerminatingError(exception7.ErrorRecord);
                                }
                                if (!hashtable3.ContainsKey(ConfigFileContants.VariableValueToken))
                                {
                                    PSArgumentException exception8 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.VariableDefinitions, ConfigFileContants.VariableValueToken, this.path }));
                                    base.ThrowTerminatingError(exception8.ErrorRecord);
                                }
                                foreach (string str6 in hashtable3.Keys)
                                {
                                    if (!string.Equals(str6, ConfigFileContants.VariableNameToken, StringComparison.OrdinalIgnoreCase) && !string.Equals(str6, ConfigFileContants.VariableValueToken, StringComparison.OrdinalIgnoreCase))
                                    {
                                        PSArgumentException exception9 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, new object[] { str6, ConfigFileContants.VariableDefinitions, this.path }));
                                        base.ThrowTerminatingError(exception9.ErrorRecord);
                                    }
                                }
                            }
                        }
                        else
                        {
                            PSArgumentException exception10 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, ConfigFileContants.VariableDefinitions, filePath));
                            base.ThrowTerminatingError(exception10.ErrorRecord);
                        }
                    }
                }
                builder.Append(ConfigFragment(ConfigFileContants.TypesToProcess, RemotingErrorIdStrings.DISCTypesToProcessComment, (this.typesToProcess != null) ? this.CombineStringArray(this.typesToProcess) : string.Empty, writer));
                builder.Append(ConfigFragment(ConfigFileContants.FormatsToProcess, RemotingErrorIdStrings.DISCFormatsToProcessComment, (this.formatsToProcess != null) ? this.CombineStringArray(this.formatsToProcess) : string.Empty, writer));
                builder.Append(ConfigFragment(ConfigFileContants.ScriptsToProcess, RemotingErrorIdStrings.DISCScriptsToProcessComment, (this.scriptsToProcess != null) ? this.CombineStringArray(this.scriptsToProcess) : string.Empty, writer));
                builder.Append("}");
                builder.Append(writer.NewLine);
                builder.Append(writer.NewLine);
                writer.Write(builder.ToString());
            }
            finally
            {
                writer.Close();
            }
        }
コード例 #39
0
        /// <summary>
        ///
        /// </summary>
        protected override void ProcessRecord()
        {
            Debug.Assert(!String.IsNullOrEmpty(_path));

            ProviderInfo provider = null;
            PSDriveInfo drive;
            string filePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_path, out provider, out drive);

            if (!provider.NameEquals(Context.ProviderNames.FileSystem) || !filePath.EndsWith(StringLiterals.PowerShellDISCFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                string message = StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, _path);
                InvalidOperationException ioe = new InvalidOperationException(message);
                ErrorRecord er = new ErrorRecord(ioe, "InvalidPSSessionConfigurationFilePath",
                    ErrorCategory.InvalidArgument, _path);
                ThrowTerminatingError(er);
            }

            FileStream fileStream;
            StreamWriter streamWriter;
            FileInfo readOnlyFileInfo;

            // Now open the output file...
            PathUtils.MasterStreamOpen(
                this,
                filePath,
                EncodingConversion.Unicode,
                /* defaultEncoding */ false,
                /* Append */ false,
                /* Force */ false,
                /* NoClobber */ false,
                out fileStream,
                out streamWriter,
                out readOnlyFileInfo,
                false
            );

            try
            {
                StringBuilder result = new StringBuilder();

                result.Append("@{");
                result.Append(streamWriter.NewLine);
                result.Append(streamWriter.NewLine);

                // Schema version
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.SchemaVersion, RemotingErrorIdStrings.DISCSchemaVersionComment,
                    SessionConfigurationUtils.QuoteName(_schemaVersion), streamWriter, false));

                // Guid
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Guid, RemotingErrorIdStrings.DISCGUIDComment, SessionConfigurationUtils.QuoteName(_guid), streamWriter, false));

                // Author
                if (String.IsNullOrEmpty(_author))
                {
                    _author = Environment.UserName;
                }
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Author, RemotingErrorIdStrings.DISCAuthorComment,
                    SessionConfigurationUtils.QuoteName(_author), streamWriter, false));

                // Description
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Description, RemotingErrorIdStrings.DISCDescriptionComment,
                    SessionConfigurationUtils.QuoteName(_description), streamWriter, String.IsNullOrEmpty(_description)));

                // Company name
                if (ShouldGenerateConfigurationSnippet("CompanyName"))
                {
                    if (String.IsNullOrEmpty(_companyName))
                    {
                        _companyName = Modules.DefaultCompanyName;
                    }
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.CompanyName, RemotingErrorIdStrings.DISCCompanyNameComment,
                        SessionConfigurationUtils.QuoteName(_companyName), streamWriter, false));
                }

                // Copyright
                if (ShouldGenerateConfigurationSnippet("Copyright"))
                {
                    if (String.IsNullOrEmpty(_copyright))
                    {
                        _copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, DateTime.Now.Year, _author);
                    }
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Copyright, RemotingErrorIdStrings.DISCCopyrightComment,
                        SessionConfigurationUtils.QuoteName(_copyright), streamWriter, false));
                }

                // Session type
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.SessionType, RemotingErrorIdStrings.DISCInitialSessionStateComment,
                    SessionConfigurationUtils.QuoteName(_sessionType), streamWriter, false));

                string resultData = null;

                // Transcript directory
                resultData = String.IsNullOrEmpty(_transcriptDirectory) ? "'C:\\Transcripts\\'" : SessionConfigurationUtils.QuoteName(_transcriptDirectory);
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.TranscriptDirectory, RemotingErrorIdStrings.DISCTranscriptDirectoryComment,
                    resultData, streamWriter, String.IsNullOrEmpty(_transcriptDirectory)));

                // Run as virtual account
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RunAsVirtualAccount, RemotingErrorIdStrings.DISCRunAsVirtualAccountComment,
                    SessionConfigurationUtils.WriteBoolean(true), streamWriter, RunAsVirtualAccount == false));

                // Run as virtual account groups
                if (ShouldGenerateConfigurationSnippet("RunAsVirtualAccountGroups"))
                {
                    bool haveVirtualAccountGroups = (RunAsVirtualAccountGroups != null) && (RunAsVirtualAccountGroups.Length > 0);
                    resultData = (haveVirtualAccountGroups) ? SessionConfigurationUtils.CombineStringArray(RunAsVirtualAccountGroups) : "'Remote Desktop Users', 'Remote Management Users'";
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RunAsVirtualAccountGroups, RemotingErrorIdStrings.DISCRunAsVirtualAccountGroupsComment,
                        resultData, streamWriter, !haveVirtualAccountGroups));
                }

                // Mount user drive
                if (ShouldGenerateConfigurationSnippet("MountUserDrive"))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.MountUserDrive, RemotingErrorIdStrings.DISCMountUserDriveComment,
                        SessionConfigurationUtils.WriteBoolean(true), streamWriter, MountUserDrive == false));
                }

                // User drive maximum size
                if (ShouldGenerateConfigurationSnippet("UserDriveMaximumSize"))
                {
                    long userDriveMaxSize = (UserDriveMaximumSize > 0) ? UserDriveMaximumSize : 50000000;
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.UserDriveMaxSize, RemotingErrorIdStrings.DISCUserDriveMaxSizeComment,
                        SessionConfigurationUtils.WriteLong(userDriveMaxSize), streamWriter, (UserDriveMaximumSize <= 0)));
                }

                // Temporarily removed until script input parameter validation is implemented.
                /*
                // Enforce input parameter validation
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.EnforceInputParameterValidation, RemotingErrorIdStrings.DISCEnforceInputParameterValidation,
                    SessionConfigurationUtils.WriteBoolean(true), streamWriter, EnforceInputParameterValidation == false));
                */

                // Group Managed Service Account Name
                if (ShouldGenerateConfigurationSnippet("GroupManagedServiceAccount"))
                {
                    bool haveGMSAAccountName = !string.IsNullOrEmpty(GroupManagedServiceAccount);
                    resultData = (!haveGMSAAccountName) ? "'CONTOSO\\GroupManagedServiceAccount'" : SessionConfigurationUtils.QuoteName(GroupManagedServiceAccount);
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.GMSAAccount, RemotingErrorIdStrings.DISCGMSAComment,
                        resultData, streamWriter, !haveGMSAAccountName));
                }

                // Scripts to process
                resultData = (_scriptsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_scriptsToProcess) : "'C:\\ConfigData\\InitScript1.ps1', 'C:\\ConfigData\\InitScript2.ps1'";
                result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ScriptsToProcess, RemotingErrorIdStrings.DISCScriptsToProcessComment,
                    resultData, streamWriter, (_scriptsToProcess.Length == 0)));

                // Role definitions
                if (_roleDefinitions == null)
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RoleDefinitions, RemotingErrorIdStrings.DISCRoleDefinitionsComment,
                        "@{ 'CONTOSO\\SqlAdmins' = @{ RoleCapabilities = 'SqlAdministration' }; 'CONTOSO\\ServerMonitors' = @{ VisibleCmdlets = 'Get-Process' } } ", streamWriter, true));
                }
                else
                {
                    DISCUtils.ValidateRoleDefinitions(_roleDefinitions);

                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RoleDefinitions, RemotingErrorIdStrings.DISCRoleDefinitionsComment,
                        SessionConfigurationUtils.CombineHashtable(_roleDefinitions, streamWriter), streamWriter, false));
                }

                // Required groups
                if (ShouldGenerateConfigurationSnippet("RequiredGroups"))
                {
                    if (_requiredGroups == null)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RequiredGroups, RemotingErrorIdStrings.DISCRequiredGroupsComment,
                            "@{ And = @{ Or = 'CONTOSO\\SmartCard-Logon1', 'CONTOSO\\SmartCard-Logon2' }, 'Administrators' }", streamWriter, true));
                    }
                    else
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RequiredGroups, RemotingErrorIdStrings.DISCRequiredGroupsComment,
                            SessionConfigurationUtils.CombineRequiredGroupsHash(_requiredGroups), streamWriter, false));
                    }
                }

                // PSLanguageMode languageMode
                if (ShouldGenerateConfigurationSnippet("LanguageMode"))
                {
                    if (!_isLanguageModeSpecified)
                    {
                        if (_sessionType == SessionType.Default)
                        {
                            _languageMode = PSLanguageMode.FullLanguage;
                        }
                    }
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.LanguageMode, RemotingErrorIdStrings.DISCLanguageModeComment,
                        SessionConfigurationUtils.QuoteName(_languageMode), streamWriter, false));
                }

                // ExecutionPolicy executionPolicy
                if (ShouldGenerateConfigurationSnippet("ExecutionPolicy"))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ExecutionPolicy, RemotingErrorIdStrings.DISCExecutionPolicyComment,
                        SessionConfigurationUtils.QuoteName(_executionPolicy), streamWriter, false));
                }

                // PowerShell version
                bool isExample = false;

                if (ShouldGenerateConfigurationSnippet("PowerShellVersion"))
                {
                    if (_powerShellVersion == null)
                    {
                        isExample = true;
                        _powerShellVersion = PSVersionInfo.PSVersion;
                    }
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.PowerShellVersion, RemotingErrorIdStrings.DISCPowerShellVersionComment,
                        SessionConfigurationUtils.QuoteName(_powerShellVersion), streamWriter, isExample));
                }

                // Modules to import
                if (_modulesToImport == null)
                {
                    if (Full)
                    {
                        string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }";
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, exampleModulesToImport, streamWriter, true));
                    }
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment,
                        SessionConfigurationUtils.CombineHashTableOrStringArray(_modulesToImport, streamWriter, this), streamWriter, false));
                }

                // Visible aliases
                if (ShouldGenerateConfigurationSnippet("VisibleAliases"))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleAliases, RemotingErrorIdStrings.DISCVisibleAliasesComment,
                        SessionConfigurationUtils.GetVisibilityDefault(_visibleAliases, streamWriter, this), streamWriter, _visibleAliases.Length == 0));
                }

                // Visible cmdlets
                if ((_visibleCmdlets == null) || (_visibleCmdlets.Length == 0))
                {
                    if (Full)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment,
                            "'Invoke-Cmdlet1', @{ Name = 'Invoke-Cmdlet2'; Parameters = @{ Name = 'Parameter1'; ValidateSet = 'Item1', 'Item2' }, @{ Name = 'Parameter2'; ValidatePattern = 'L*' } }", streamWriter, true));
                    }
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment,
                        SessionConfigurationUtils.GetVisibilityDefault(_visibleCmdlets, streamWriter, this), streamWriter, false));
                }

                // Visible functions
                if ((_visibleFunctions == null) || (_visibleFunctions.Length == 0))
                {
                    if (Full)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment,
                            "'Invoke-Function1', @{ Name = 'Invoke-Function2'; Parameters = @{ Name = 'Parameter1'; ValidateSet = 'Item1', 'Item2' }, @{ Name = 'Parameter2'; ValidatePattern = 'L*' } }", streamWriter, true));
                    }
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment,
                        SessionConfigurationUtils.GetVisibilityDefault(_visibleFunctions, streamWriter, this), streamWriter, _visibleFunctions.Length == 0));
                }

                // Visible external commands (scripts, executables)
                if (ShouldGenerateConfigurationSnippet("VisibleExternalCommands"))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleExternalCommands, RemotingErrorIdStrings.DISCVisibleExternalCommandsComment,
                        SessionConfigurationUtils.GetVisibilityDefault(_visibleExternalCommands, streamWriter, this), streamWriter, _visibleExternalCommands.Length == 0));
                }

                // Visible providers
                if (ShouldGenerateConfigurationSnippet("VisibleProviders"))
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleProviders, RemotingErrorIdStrings.DISCVisibleProvidersComment,
                        SessionConfigurationUtils.GetVisibilityDefault(_visibleProviders, streamWriter, this), streamWriter, _visibleProviders.Length == 0));
                }

                // Alias definitions
                if ((_aliasDefinitions == null) || (_aliasDefinitions.Length == 0))
                {
                    if (Full)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment,
                           "@{ Name = 'Alias1'; Value = 'Invoke-Alias1'}, @{ Name = 'Alias2'; Value = 'Invoke-Alias2'}", streamWriter, true));
                    }
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment,
                        SessionConfigurationUtils.CombineHashtableArray(_aliasDefinitions, streamWriter), streamWriter, false));
                }

                // Function definitions
                if (_functionDefinitions == null)
                {
                    if (Full)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment,
                            "@{ Name = 'MyFunction'; ScriptBlock = { param($MyInput) $MyInput } }", streamWriter, true));
                    }
                }
                else
                {
                    Hashtable[] funcHash = DISCPowerShellConfiguration.TryGetHashtableArray(_functionDefinitions);

                    if (funcHash != null)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment,
                            SessionConfigurationUtils.CombineHashtableArray(funcHash, streamWriter), streamWriter, false));

                        foreach (Hashtable hashtable in funcHash)
                        {
                            if (!hashtable.ContainsKey(ConfigFileConstants.FunctionNameToken))
                            {
                                PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey,
                                    ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionNameToken, _path));
                                ThrowTerminatingError(e.ErrorRecord);
                            }

                            if (!hashtable.ContainsKey(ConfigFileConstants.FunctionValueToken))
                            {
                                PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey,
                                    ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionValueToken, _path));
                                ThrowTerminatingError(e.ErrorRecord);
                            }

                            if ((hashtable[ConfigFileConstants.FunctionValueToken] as ScriptBlock) == null)
                            {
                                PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock,
                                    ConfigFileConstants.FunctionValueToken, ConfigFileConstants.FunctionDefinitions, _path));
                                ThrowTerminatingError(e.ErrorRecord);
                            }

                            foreach (string functionKey in hashtable.Keys)
                            {
                                if (!String.Equals(functionKey, ConfigFileConstants.FunctionNameToken, StringComparison.OrdinalIgnoreCase) &&
                                    !String.Equals(functionKey, ConfigFileConstants.FunctionValueToken, StringComparison.OrdinalIgnoreCase) &&
                                    !String.Equals(functionKey, ConfigFileConstants.FunctionOptionsToken, StringComparison.OrdinalIgnoreCase))
                                {
                                    PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey,
                                        functionKey, ConfigFileConstants.FunctionDefinitions, _path));
                                    ThrowTerminatingError(e.ErrorRecord);
                                }
                            }
                        }
                    }
                    else
                    {
                        PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray,
                            ConfigFileConstants.FunctionDefinitions, filePath));
                        ThrowTerminatingError(e.ErrorRecord);
                    }
                }

                // Variable definitions
                if (_variableDefinitions == null)
                {
                    if (Full)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment,
                            "@{ Name = 'Variable1'; Value = { 'Dynamic' + 'InitialValue' } }, @{ Name = 'Variable2'; Value = 'StaticInitialValue' }", streamWriter, true));
                    }
                }
                else
                {
                    string varString = _variableDefinitions as string;

                    if (varString != null)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment,
                            varString, streamWriter, false));
                    }
                    else
                    {
                        Hashtable[] varHash = DISCPowerShellConfiguration.TryGetHashtableArray(_variableDefinitions);

                        if (varHash != null)
                        {
                            result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment,
                                SessionConfigurationUtils.CombineHashtableArray(varHash, streamWriter), streamWriter, false));

                            foreach (Hashtable hashtable in varHash)
                            {
                                if (!hashtable.ContainsKey(ConfigFileConstants.VariableNameToken))
                                {
                                    PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey,
                                        ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableNameToken, _path));
                                    ThrowTerminatingError(e.ErrorRecord);
                                }

                                if (!hashtable.ContainsKey(ConfigFileConstants.VariableValueToken))
                                {
                                    PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey,
                                        ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableValueToken, _path));
                                    ThrowTerminatingError(e.ErrorRecord);
                                }

                                foreach (string variableKey in hashtable.Keys)
                                {
                                    if (!String.Equals(variableKey, ConfigFileConstants.VariableNameToken, StringComparison.OrdinalIgnoreCase) &&
                                        !String.Equals(variableKey, ConfigFileConstants.VariableValueToken, StringComparison.OrdinalIgnoreCase))
                                    {
                                        PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey,
                                            variableKey, ConfigFileConstants.VariableDefinitions, _path));
                                        ThrowTerminatingError(e.ErrorRecord);
                                    }
                                }
                            }
                        }
                        else
                        {
                            PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray,
                                ConfigFileConstants.VariableDefinitions, filePath));
                            ThrowTerminatingError(e.ErrorRecord);
                        }
                    }
                }

                // Environment variables
                if (_environmentVariables == null)
                {
                    if (Full)
                    {
                        result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment,
                            "@{ Variable1 = 'Value1'; Variable2 = 'Value2' }",
                            streamWriter, true));
                    }
                }
                else
                {
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment,
                        SessionConfigurationUtils.CombineHashtable(_environmentVariables, streamWriter), streamWriter, false));
                }

                // Types to process
                if (ShouldGenerateConfigurationSnippet("TypesToProcess"))
                {
                    resultData = (_typesToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_typesToProcess) : "'C:\\ConfigData\\MyTypes.ps1xml', 'C:\\ConfigData\\OtherTypes.ps1xml'";
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.TypesToProcess, RemotingErrorIdStrings.DISCTypesToProcessComment,
                        resultData, streamWriter, (_typesToProcess.Length == 0)));
                }

                // Formats to process
                if (ShouldGenerateConfigurationSnippet("FormatsToProcess"))
                {
                    resultData = (_formatsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_formatsToProcess) : "'C:\\ConfigData\\MyFormats.ps1xml', 'C:\\ConfigData\\OtherFormats.ps1xml'";
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FormatsToProcess, RemotingErrorIdStrings.DISCFormatsToProcessComment,
                        resultData, streamWriter, (_formatsToProcess.Length == 0)));
                }

                // Assemblies to load
                if (ShouldGenerateConfigurationSnippet("AssembliesToLoad"))
                {
                    isExample = false;
                    if ((_assembliesToLoad == null) || (_assembliesToLoad.Length == 0))
                    {
                        isExample = true;
                        _assembliesToLoad = new string[] { "System.Web", "System.OtherAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" };
                    }
                    result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AssembliesToLoad, RemotingErrorIdStrings.DISCAssembliesToLoadComment,
                        SessionConfigurationUtils.CombineStringArray(_assembliesToLoad), streamWriter, isExample));
                }

                result.Append("}");

                streamWriter.Write(result.ToString());
            }
            finally
            {
                streamWriter.Dispose();
            }
        }
コード例 #40
0
        /// <summary>
        /// The main processing loop of the command.
        /// </summary>
        protected override void ProcessRecord()
        {
            string path = GetFilePath();

            if (path == null)
            {
                return;
            }

            if (!File.Exists(path))
            {
                InvalidOperationException ioe =
                    PSTraceSource.NewInvalidOperationException(
                        ImportLocalizedDataStrings.FileNotExist,
                        path);
                WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.ObjectNotFound, path));
                return;
            }

            // Prevent additional commands in ConstrainedLanguage mode
            if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
            {
                if (_setSupportedCommand)
                {
                    NotSupportedException nse =
                        PSTraceSource.NewNotSupportedException(
                            ImportLocalizedDataStrings.CannotDefineSupportedCommand);
                    ThrowTerminatingError(
                        new ErrorRecord(nse, "CannotDefineSupportedCommand", ErrorCategory.PermissionDenied, null));
                }
            }

            string script = GetScript(path);

            if (script == null)
            {
                return;
            }

            try
            {
                var scriptBlock = Context.Engine.ParseScriptBlock(script, false);
                scriptBlock.CheckRestrictedLanguage(SupportedCommand, null, false);
                object         result;
                PSLanguageMode oldLanguageMode = Context.LanguageMode;
                Context.LanguageMode = PSLanguageMode.RestrictedLanguage;
                try
                {
                    result = scriptBlock.InvokeReturnAsIs();
                    if (result == AutomationNull.Value)
                    {
                        result = null;
                    }
                }
                finally
                {
                    Context.LanguageMode = oldLanguageMode;
                }

                if (_bindingVariable != null)
                {
                    VariablePath variablePath = new(_bindingVariable);
                    if (variablePath.IsUnscopedVariable)
                    {
                        variablePath = variablePath.CloneAndSetLocal();
                    }

                    if (string.IsNullOrEmpty(variablePath.UnqualifiedPath))
                    {
                        InvalidOperationException ioe = PSTraceSource.NewInvalidOperationException(
                            ImportLocalizedDataStrings.IncorrectVariableName, _bindingVariable);
                        WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.InvalidArgument,
                                                   _bindingVariable));
                        return;
                    }

                    SessionStateScope scope    = null;
                    PSVariable        variable = SessionState.Internal.GetVariableItem(variablePath, out scope);

                    if (variable == null)
                    {
                        variable = new PSVariable(variablePath.UnqualifiedPath, result, ScopedItemOptions.None);
                        Context.EngineSessionState.SetVariable(variablePath, variable, false, CommandOrigin.Internal);
                    }
                    else
                    {
                        variable.Value = result;

                        if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                        {
                            // Mark untrusted values for assignments to 'Global:' variables, and 'Script:' variables in
                            // a module scope, if it's necessary.
                            ExecutionContext.MarkObjectAsUntrustedForVariableAssignment(variable, scope, Context.EngineSessionState);
                        }
                    }
                }

                // If binding variable is null, write the object to stream
                else
                {
                    WriteObject(result);
                }
            }
            catch (RuntimeException e)
            {
                PSInvalidOperationException ioe = PSTraceSource.NewInvalidOperationException(e,
                                                                                             ImportLocalizedDataStrings.ErrorLoadingDataFile,
                                                                                             path,
                                                                                             e.Message);

                throw ioe;
            }

            return;
        }
コード例 #41
0
        private void RunClause(Action <FunctionContext> clause, object dollarUnderbar, object inputToProcess)
        {
            ExecutionContext.CheckStackDepth();
            Pipe           shellFunctionErrorOutputPipe = base.Context.ShellFunctionErrorOutputPipe;
            PSLanguageMode?nullable  = null;
            PSLanguageMode?nullable2 = null;

            if (this._scriptBlock.LanguageMode.HasValue)
            {
                PSLanguageMode?languageMode = this._scriptBlock.LanguageMode;
                PSLanguageMode mode         = base.Context.LanguageMode;
                if ((((PSLanguageMode)languageMode.GetValueOrDefault()) != mode) || !languageMode.HasValue)
                {
                    nullable  = new PSLanguageMode?(base.Context.LanguageMode);
                    nullable2 = this._scriptBlock.LanguageMode;
                }
            }
            try
            {
                CommandOrigin scopeOrigin = base.Context.EngineSessionState.CurrentScope.ScopeOrigin;
                try
                {
                    base.Context.EngineSessionState.CurrentScope.ScopeOrigin = base._dontUseScopeCommandOrigin ? CommandOrigin.Internal : base.Command.CommandOrigin;
                    if (nullable2.HasValue)
                    {
                        base.Context.LanguageMode = nullable2.Value;
                    }
                    this.EnterScope();
                    if (base.commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output)
                    {
                        base.Context.RedirectErrorPipe(base.commandRuntime.OutputPipe);
                    }
                    else if (base.commandRuntime.ErrorOutputPipe.IsRedirected)
                    {
                        base.Context.RedirectErrorPipe(base.commandRuntime.ErrorOutputPipe);
                    }
                    if (dollarUnderbar != AutomationNull.Value)
                    {
                        this._localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, base._context);
                    }
                    if (inputToProcess != AutomationNull.Value)
                    {
                        if (inputToProcess == null)
                        {
                            inputToProcess = MshCommandRuntime.StaticEmptyArray.GetEnumerator();
                        }
                        else
                        {
                            IList list = inputToProcess as IList;
                            inputToProcess = (list != null) ? list.GetEnumerator() : LanguagePrimitives.GetEnumerator(inputToProcess);
                        }
                        this._localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, base._context);
                    }
                    clause(this._functionContext);
                }
                catch (TargetInvocationException exception)
                {
                    throw exception.InnerException;
                }
                finally
                {
                    base.Context.RestoreErrorPipe(shellFunctionErrorOutputPipe);
                    if (nullable.HasValue)
                    {
                        base.Context.LanguageMode = nullable.Value;
                    }
                    base.Context.EngineSessionState.CurrentScope.ScopeOrigin = scopeOrigin;
                }
            }
            catch (ExitException exception2)
            {
                if (!base.FromScriptFile || base._rethrowExitException)
                {
                    throw;
                }
                base._exitWasCalled = true;
                int argument = (int)exception2.Argument;
                base.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, argument);
                if (argument != 0)
                {
                    base.commandRuntime.PipelineProcessor.ExecutionFailed = true;
                }
            }
            catch (FlowControlException)
            {
                throw;
            }
            catch (RuntimeException exception3)
            {
                base.ManageScriptException(exception3);
                throw;
            }
            catch (Exception exception4)
            {
                CommandProcessorBase.CheckForSevereException(exception4);
                throw base.ManageInvocationException(exception4);
            }
        }
コード例 #42
0
        /// <summary>
        /// Load a workflow XAML file from the specified path and generate a PowerShell
        /// function from the file. The name of the generated function will be the basename
        /// of the XAML file.
        /// </summary>
        /// <param name="name">The name of workflow.</param>
        /// <param name="xaml">The xaml of workflow.</param>
        /// <param name="requiredAssemblies"></param>
        /// <param name="dependentWorkflows">Any workflows required by this workflow.</param>
        /// <param name="dependentAssemblyPath">Path to the dependent assembly.</param>
        /// <param name="resolvedPath">Resolved Path of the xaml</param>
        /// <param name="sourceLanguageMode">Language mode of source in which workflow should run</param>
        private static FunctionDetails GenerateFunctionFromXaml(
            string name, 
            string xaml, 
            Dictionary<string, string> requiredAssemblies, 
            string[] dependentWorkflows, 
            string dependentAssemblyPath, 
            string resolvedPath,
            PSLanguageMode sourceLanguageMode)
        {
            if (name == null)
            {
                ArgumentNullException argNullException = new ArgumentNullException("name");
                Tracer.TraceException(argNullException);
                throw argNullException;
            }

            string modulePath = System.IO.Path.GetDirectoryName(resolvedPath);
            string functionDefinition = CreateFunctionFromXaml(
                name, 
                xaml, 
                requiredAssemblies, 
                dependentWorkflows, 
                dependentAssemblyPath, 
                null, 
                modulePath, 
                false, 
                "[CmdletBinding()]",
                null,   /* scriptContent */
                null,   /* fullScript */
                null,   /* rootWorkflowName */
                sourceLanguageMode,
                null);

            FunctionDetails details = new FunctionDetails
                                          {Name = name, FunctionDefinition = functionDefinition, Xaml = xaml};

            return details;
        }
コード例 #43
0
        private void OnDebuggerStop(InvocationInfo invocationInfo, List <Breakpoint> breakpoints)
        {
            LocalRunspace currentRunspace = this._context.CurrentRunspace as LocalRunspace;

            if (currentRunspace.PulsePipeline != null && currentRunspace.PulsePipeline == currentRunspace.GetCurrentlyRunningPipeline())
            {
                if (breakpoints.Count > 0)
                {
                    this._context.EngineHostInterface.UI.WriteWarningLine(ResourceManagerCache.FormatResourceString("DebuggerStrings", "WarningBreakpointWillNotBeHit", (object)breakpoints[0]));
                }
                else
                {
                    this._context.EngineHostInterface.UI.WriteWarningLine(new InvalidOperationException().Message);
                }
            }
            else
            {
                this._steppingMode = Debugger.SteppingMode.None;
                EventHandler <DebuggerStopEventArgs> debuggerStop = this.DebuggerStop;
                if (debuggerStop == null)
                {
                    return;
                }
                this._inBreakpoint = true;
                if (invocationInfo != null)
                {
                    this._callStack.Push(new Debugger.CallStackInfo()
                    {
                        InvocationInfo = invocationInfo
                    });
                }
                this._context.SetVariable("PSDebugContext", (object)new PSDebugContext(invocationInfo, breakpoints));
                PSLanguageMode languageMode = this._context.LanguageMode;
                bool           flag         = languageMode != PSLanguageMode.FullLanguage && this._context.UseFullLanguageModeInDebugger;
                if (flag)
                {
                    this._context.LanguageMode = PSLanguageMode.FullLanguage;
                }
                RunspaceAvailability runspaceAvailability = this._context.CurrentRunspace.RunspaceAvailability;
                this._context.CurrentRunspace.UpdateRunspaceAvailability(this._context.CurrentRunspace.GetCurrentlyRunningPipeline() != null ? RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available, true);
                try
                {
                    DebuggerStopEventArgs e = new DebuggerStopEventArgs(invocationInfo, breakpoints);
                    debuggerStop((object)this, e);
                    this.ResumeExecution(e);
                }
                finally
                {
                    this._context.CurrentRunspace.UpdateRunspaceAvailability(runspaceAvailability, true);
                    if (flag)
                    {
                        this._context.LanguageMode = languageMode;
                    }
                    this._context.RemoveVariable("PSDebugContext");
                    if (invocationInfo != null)
                    {
                        this._callStack.Pop();
                    }
                    this._inBreakpoint = false;
                }
            }
        }