Exemple #1
0
 internal ClosureVariableProperty(PSVariable variable)
 {
     _variable = variable;
     SetMemberName(variable.Name);
 }
        /// <summary>
        /// BeginProcessing override.
        /// </summary>
        protected override void BeginProcessing()
        {
            try
            {
                // Set the sender address of the mail message
                _mMailMessage.From = new MailAddress(From);
            }
            catch (FormatException e)
            {
                ErrorRecord er = new ErrorRecord(e, "FormatException", ErrorCategory.InvalidType, From);
                ThrowTerminatingError(er);
            }

            // Set the recipient address of the mail message
            AddAddressesToMailMessage(To, "to");

            // Set the BCC address of the mail message
            if (Bcc != null)
            {
                AddAddressesToMailMessage(Bcc, "bcc");
            }

            // Set the CC address of the mail message
            if (Cc != null)
            {
                AddAddressesToMailMessage(Cc, "cc");
            }

            // Set the delivery notification
            _mMailMessage.DeliveryNotificationOptions = DeliveryNotificationOption;

            // Set the subject of the mail message
            _mMailMessage.Subject = Subject;

            // Set the body of the mail message
            _mMailMessage.Body = Body;

            // Set the subject and body encoding
            _mMailMessage.SubjectEncoding = Encoding;
            _mMailMessage.BodyEncoding    = Encoding;

            // Set the format of the mail message body as HTML
            _mMailMessage.IsBodyHtml = BodyAsHtml;

            // Set the priority of the mail message to normal
            _mMailMessage.Priority = Priority;

            // Get the PowerShell environment variable
            // globalEmailServer might be null if it is deleted by: PS> del variable:PSEmailServer
            PSVariable globalEmailServer = SessionState.Internal.GetVariable(SpecialVariables.PSEmailServer);

            if (SmtpServer == null && globalEmailServer != null)
            {
                SmtpServer = Convert.ToString(globalEmailServer.Value, CultureInfo.InvariantCulture);
            }

            if (string.IsNullOrEmpty(SmtpServer))
            {
                ErrorRecord er = new ErrorRecord(new InvalidOperationException(SendMailMessageStrings.HostNameValue), null, ErrorCategory.InvalidArgument, null);
                this.ThrowTerminatingError(er);
            }

            if (Port == 0)
            {
                _mSmtpClient = new SmtpClient(SmtpServer);
            }
            else
            {
                _mSmtpClient = new SmtpClient(SmtpServer, Port);
            }

            if (UseSsl)
            {
                _mSmtpClient.EnableSsl = true;
            }

            if (Credential != null)
            {
                _mSmtpClient.UseDefaultCredentials = false;
                _mSmtpClient.Credentials           = Credential.GetNetworkCredential();
            }
            else if (!UseSsl)
            {
                _mSmtpClient.UseDefaultCredentials = true;
            }
        }
 internal void NewVariable(PSVariable variable, bool force)
 {
     throw new NotImplementedException();
 }
Exemple #4
0
        private bool VariableAlreadyExists(PSVariable variable)
        {
            PSVariable originalVariable = SessionState.PSVariable.GetAtScope(variable.Name, Scope);

            return(originalVariable != null);
        }
Exemple #5
0
        /// <summary>
        /// Add objects received on the pipeline to an ArrayList of values, to
        /// take the place of the Value parameter if none was specified on the
        /// command line.
        /// </summary>
        protected override void ProcessRecord()
        {
            // If Force is not specified, see if the variable already exists
            // in the specified scope. If the scope isn't specified, then
            // check to see if it exists in the current scope.

            if (!Force)
            {
                PSVariable varFound = null;
                if (String.IsNullOrEmpty(Scope))
                {
                    varFound =
                        SessionState.PSVariable.GetAtScope(Name, "local");
                }
                else
                {
                    varFound =
                        SessionState.PSVariable.GetAtScope(Name, Scope);
                }

                if (varFound != null)
                {
                    SessionStateException sessionStateException =
                        new SessionStateException(
                            Name,
                            SessionStateCategory.Variable,
                            "VariableAlreadyExists",
                            SessionStateStrings.VariableAlreadyExists,
                            ErrorCategory.ResourceExists);

                    WriteError(
                        new ErrorRecord(
                            sessionStateException.ErrorRecord,
                            sessionStateException));
                    return;
                }
            }

            // Since the variable doesn't exist or -Force was specified,
            // Call should process to validate the set with the user.

            string action = VariableCommandStrings.NewVariableAction;

            string target = StringUtil.Format(VariableCommandStrings.NewVariableTarget, Name, Value);

            if (ShouldProcess(target, action))
            {
                PSVariable newVariable = new PSVariable(Name, Value, Option);

                if (_visibility != null)
                {
                    newVariable.Visibility = (SessionStateEntryVisibility)_visibility;
                }

                if (Description != null)
                {
                    newVariable.Description = Description;
                }

                try
                {
                    if (String.IsNullOrEmpty(Scope))
                    {
                        SessionState.Internal.NewVariable(newVariable, Force);
                    }
                    else
                    {
                        SessionState.Internal.NewVariableAtScope(newVariable, Scope, Force);
                    }
                }
                catch (SessionStateException sessionStateException)
                {
                    WriteError(
                        new ErrorRecord(
                            sessionStateException.ErrorRecord,
                            sessionStateException));
                    return;
                }
                catch (PSArgumentException argException)
                {
                    WriteError(
                        new ErrorRecord(
                            argException.ErrorRecord,
                            argException));
                    return;
                }

                if (_passThru)
                {
                    WriteObject(newVariable);
                }
            }
        }
Exemple #6
0
        protected override void ProcessRecord()
        {
            if (InputObject == null)
            {
                return;
            }
            PSObject newInputObject;

            if (NoClone.IsPresent)
            {
                newInputObject = Helpers.EnsureHasProperties(InputObject, Property);
            }
            else
            {
                newInputObject = Helpers.CloneObject(InputObject, Property);
            }

            bool       setValue = true;
            PSVariable matchVar = new PSVariable("Matches");

            if (whereIsScriptBlock)
            {
                var varList = new List <PSVariable>();
                varList.Add(new PSVariable("_", InputObject));
                varList.Add(matchVar);
                var whereResult = whereAsScriptBlock.InvokeWithContext(null, varList, null);
                setValue = LanguagePrimitives.IsTrue(whereResult);
            }
            else if (whereIsString)
            {
                setValue = false;
                var whereProperty = newInputObject.Properties[whereAsString];
                if (Match != null && whereProperty != null && whereProperty.Value != null)
                {
                    var matchResult = matchRegex.Match(whereProperty.Value.ToString());
                    setValue = matchResult.Success;
                    Hashtable matches = new Hashtable(StringComparer.CurrentCultureIgnoreCase);
                    foreach (string groupName in matchGroupNames)
                    {
                        System.Text.RegularExpressions.Group g = matchResult.Groups[groupName];
                        if (g.Success)
                        {
                            int keyInt;
                            if (Int32.TryParse(groupName, out keyInt))
                            {
                                matches.Add(keyInt, g.ToString());
                            }
                            else
                            {
                                matches.Add(groupName, g.ToString());
                            }
                        }
                    }
                    matchVar.Value = matches;
                }
                else
                {
                    setValue = whereProperty != null && LanguagePrimitives.IsTrue(whereProperty.Value);
                }
            }
            if (!setValue)
            {
                WriteObject(newInputObject);
                return;
            }

            object newValue = Value;

            if (valueIsScriptBlock)
            {
                var varList = new List <PSVariable>();
                varList.Add(new PSVariable("_", InputObject));
                varList.Add(matchVar);
                var scriptResult = valueAsScriptBlock.InvokeWithContext(null, varList, null);
                if (scriptResult.Count == 1)
                {
                    newValue = scriptResult[0];
                }
                else
                {
                    newValue = scriptResult;
                }
            }

            foreach (string property in Property)
            {
                if (!IfUnset.IsPresent || Helpers.IsPropertyNullOrWhiteSpace(newInputObject, property))
                {
                    if (JoinWith != null)
                    {
                        var enumValue = LanguagePrimitives.ConvertTo <string[]>(newValue);
                        newValue = string.Join(JoinWith, enumValue);
                    }
                    newInputObject.Properties.Add(new PSNoteProperty(property, newValue));
                }
            }

            WriteObject(newInputObject);
        }
        /// <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 VariablePath(_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;
                    }
                } // end _bindingvariable != null

                // 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;
        } // ProcessRecord
Exemple #8
0
        private void CreateVariable(string name, object value, ScopedItemOptions options = ScopedItemOptions.None)
        {
            var variable = new PSVariable(name, value, options);

            ExecutionContext.SessionState.PSVariable.Set(variable);
        }
Exemple #9
0
 public void Set(PSVariable variable) => this.sessionState.SetVariable(variable, false, CommandOrigin.Internal);
Exemple #10
0
 internal void SetPipelineVariable(PSVariable pipelineVariable)
 {
     _pipelineVariableObject = pipelineVariable;
 }
Exemple #11
0
 internal void RemovePipelineVariable()
 {
     if (_pipelineVariableObject != null)
     {
         _pipelineVariableObject.Value = null;
         _pipelineVariableObject = null;
     }
 }
Exemple #12
0
        protected override void ProcessRecord()
        {
            PSVariable token = new PSVariable(Properties.Resources.TokenVariable, Token);

            SessionState.PSVariable.Set(token);
        }
        private void SetVariable(string[] varNames, object varValue)
        {
            CommandOrigin commandOrigin = base.MyInvocation.CommandOrigin;

            foreach (string str in varNames)
            {
                List <PSVariable> list = new List <PSVariable>();
                bool wasFiltered       = false;
                if (!string.IsNullOrEmpty(base.Scope))
                {
                    list = base.GetMatchingVariables(str, base.Scope, out wasFiltered, false);
                }
                else
                {
                    list = base.GetMatchingVariables(str, "LOCAL", out wasFiltered, false);
                }
                if ((list.Count == 0) && !wasFiltered)
                {
                    try
                    {
                        ScopedItemOptions none = ScopedItemOptions.None;
                        if (!string.IsNullOrEmpty(base.Scope) && string.Equals("private", base.Scope, StringComparison.OrdinalIgnoreCase))
                        {
                            none = ScopedItemOptions.Private;
                        }
                        if (this.options.HasValue)
                        {
                            none |= (ScopedItemOptions)this.options.Value;
                        }
                        object obj2 = varValue;
                        if (obj2 == AutomationNull.Value)
                        {
                            obj2 = null;
                        }
                        PSVariable variable = new PSVariable(str, obj2, none);
                        if (this.description == null)
                        {
                            this.description = string.Empty;
                        }
                        variable.Description = this.Description;
                        if (this._visibility.HasValue)
                        {
                            variable.Visibility = this.Visibility;
                        }
                        string setVariableAction = VariableCommandStrings.SetVariableAction;
                        string target            = StringUtil.Format(VariableCommandStrings.SetVariableTarget, str, obj2);
                        if (base.ShouldProcess(target, setVariableAction))
                        {
                            object sendToPipeline = null;
                            if (string.IsNullOrEmpty(base.Scope))
                            {
                                sendToPipeline = base.SessionState.Internal.SetVariable(variable, (bool)this.Force, commandOrigin);
                            }
                            else
                            {
                                sendToPipeline = base.SessionState.Internal.SetVariableAtScope(variable, base.Scope, (bool)this.Force, commandOrigin);
                            }
                            if (this.passThru && (sendToPipeline != null))
                            {
                                base.WriteObject(sendToPipeline);
                            }
                        }
                    }
                    catch (SessionStateException exception)
                    {
                        base.WriteError(new ErrorRecord(exception.ErrorRecord, exception));
                    }
                    catch (PSArgumentException exception2)
                    {
                        base.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2));
                    }
                }
                else
                {
                    foreach (PSVariable variable2 in list)
                    {
                        string action = VariableCommandStrings.SetVariableAction;
                        string str5   = StringUtil.Format(VariableCommandStrings.SetVariableTarget, variable2.Name, varValue);
                        if (base.ShouldProcess(str5, action))
                        {
                            object obj4 = null;
                            try
                            {
                                bool flag2 = false;
                                if ((this.Force != 0) && ((variable2.Options & ScopedItemOptions.ReadOnly) != ScopedItemOptions.None))
                                {
                                    variable2.SetOptions(variable2.Options & ~ScopedItemOptions.ReadOnly, true);
                                    flag2 = true;
                                }
                                if (varValue != AutomationNull.Value)
                                {
                                    variable2.Value = varValue;
                                }
                                if (this.description != null)
                                {
                                    variable2.Description = this.description;
                                }
                                if (this.options.HasValue)
                                {
                                    variable2.Options = this.options.Value;
                                }
                                else if (flag2)
                                {
                                    variable2.SetOptions(variable2.Options | ScopedItemOptions.ReadOnly, true);
                                }
                                if (this._visibility.HasValue)
                                {
                                    variable2.Visibility = this.Visibility;
                                }
                                obj4 = variable2;
                            }
                            catch (SessionStateException exception3)
                            {
                                base.WriteError(new ErrorRecord(exception3.ErrorRecord, exception3));
                                continue;
                            }
                            catch (PSArgumentException exception4)
                            {
                                base.WriteError(new ErrorRecord(exception4.ErrorRecord, exception4));
                                continue;
                            }
                            if (this.passThru && (obj4 != null))
                            {
                                base.WriteObject(obj4);
                            }
                        }
                    }
                }
            }
        }
Exemple #14
0
        protected override void ProcessRecord()
        {
            if (this.Force == 0)
            {
                PSVariable atScope = null;
                if (string.IsNullOrEmpty(base.Scope))
                {
                    atScope = base.SessionState.PSVariable.GetAtScope(this.name, "local");
                }
                else
                {
                    atScope = base.SessionState.PSVariable.GetAtScope(this.name, base.Scope);
                }
                if (atScope != null)
                {
                    SessionStateException replaceParentContainsErrorRecordException = new SessionStateException(this.name, SessionStateCategory.Variable, "VariableAlreadyExists", SessionStateStrings.VariableAlreadyExists, ErrorCategory.ResourceExists, new object[0]);
                    base.WriteError(new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException));
                    return;
                }
            }
            string newVariableAction = VariableCommandStrings.NewVariableAction;
            string target            = StringUtil.Format(VariableCommandStrings.NewVariableTarget, this.Name, this.Value);

            if (base.ShouldProcess(target, newVariableAction))
            {
                PSVariable variable = new PSVariable(this.name, this._value, this.options);
                if (this._visibility.HasValue)
                {
                    variable.Visibility = this._visibility.Value;
                }
                if (this.description != null)
                {
                    variable.Description = this.description;
                }
                try
                {
                    if (string.IsNullOrEmpty(base.Scope))
                    {
                        base.SessionState.Internal.NewVariable(variable, (bool)this.Force);
                    }
                    else
                    {
                        base.SessionState.Internal.NewVariableAtScope(variable, base.Scope, (bool)this.Force);
                    }
                }
                catch (SessionStateException exception2)
                {
                    base.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2));
                    return;
                }
                catch (PSArgumentException exception3)
                {
                    base.WriteError(new ErrorRecord(exception3.ErrorRecord, exception3));
                    return;
                }
                if (this.passThru)
                {
                    base.WriteObject(variable);
                }
            }
        }
Exemple #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PSVariableWrapper{TValue}" /> class.
 /// </summary>
 /// <param name="variable">The <see cref="PSVariable" /> to wrap.</param>
 public PSVariableWrapper(PSVariable variable)
 {
     _wrappedVariable = variable;
 }
Exemple #16
0
 internal void SetAtScope(PSVariable variable, string scope) => this.sessionState.SetVariableAtScope(variable, scope, false, CommandOrigin.Internal);
Exemple #17
0
        /// <summary>
        /// Sets the specified variable by container variableReferenceId and variable name to the
        /// specified new value.  If the variable cannot be set or converted to that value this
        /// method will throw InvalidPowerShellExpressionException, ArgumentTransformationMetadataException, or
        /// SessionStateUnauthorizedAccessException.
        /// </summary>
        /// <param name="variableContainerReferenceId">The container (Autos, Local, Script, Global) that holds the variable.</param>
        /// <param name="name">The name of the variable prefixed with $.</param>
        /// <param name="value">The new string value.  This value must not be null.  If you want to set the variable to $null
        /// pass in the string "$null".</param>
        /// <returns>The string representation of the value the variable was set to.</returns>
        public async Task <string> SetVariableAsync(int variableContainerReferenceId, string name, string value)
        {
            Validate.IsNotNull(nameof(name), name);
            Validate.IsNotNull(nameof(value), value);

            this.logger.LogTrace($"SetVariableRequest for '{name}' to value string (pre-quote processing): '{value}'");

            // An empty or whitespace only value is not a valid expression for SetVariable.
            if (value.Trim().Length == 0)
            {
                throw new InvalidPowerShellExpressionException("Expected an expression.");
            }

            // Evaluate the expression to get back a PowerShell object from the expression string.
            PSCommand psCommand = new PSCommand();

            psCommand.AddScript(value);
            var errorMessages = new StringBuilder();
            var results       =
                await this.powerShellContext.ExecuteCommandAsync <object>(
                    psCommand,
                    errorMessages,
                    false,
                    false).ConfigureAwait(false);

            // Check if PowerShell's evaluation of the expression resulted in an error.
            object psobject = results.FirstOrDefault();

            if ((psobject == null) && (errorMessages.Length > 0))
            {
                throw new InvalidPowerShellExpressionException(errorMessages.ToString());
            }

            // If PowerShellContext.ExecuteCommand returns an ErrorRecord as output, the expression failed evaluation.
            // Ideally we would have a separate means from communicating error records apart from normal output.
            if (psobject is ErrorRecord errorRecord)
            {
                throw new InvalidPowerShellExpressionException(errorRecord.ToString());
            }

            // OK, now we have a PS object from the supplied value string (expression) to assign to a variable.
            // Get the variable referenced by variableContainerReferenceId and variable name.
            VariableContainerDetails variableContainer = null;

            await this.debugInfoHandle.WaitAsync().ConfigureAwait(false);

            try
            {
                variableContainer = (VariableContainerDetails)this.variables[variableContainerReferenceId];
            }
            finally
            {
                this.debugInfoHandle.Release();
            }

            VariableDetailsBase variable = variableContainer.Children[name];
            // Determine scope in which the variable lives. This is required later for the call to Get-Variable -Scope.
            string scope = null;

            if (variableContainerReferenceId == this.scriptScopeVariables.Id)
            {
                scope = "Script";
            }
            else if (variableContainerReferenceId == this.globalScopeVariables.Id)
            {
                scope = "Global";
            }
            else
            {
                // Determine which stackframe's local scope the variable is in.
                StackFrameDetails[] stackFrames = await this.GetStackFramesAsync().ConfigureAwait(false);

                for (int i = 0; i < stackFrames.Length; i++)
                {
                    var stackFrame = stackFrames[i];
                    if (stackFrame.LocalVariables.ContainsVariable(variable.Id))
                    {
                        scope = i.ToString();
                        break;
                    }
                }
            }

            if (scope == null)
            {
                // Hmm, this would be unexpected.  No scope means do not pass GO, do not collect $200.
                throw new Exception("Could not find the scope for this variable.");
            }

            // Now that we have the scope, get the associated PSVariable object for the variable to be set.
            psCommand.Commands.Clear();
            psCommand = new PSCommand();
            psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Get-Variable");
            psCommand.AddParameter("Name", name.TrimStart('$'));
            psCommand.AddParameter("Scope", scope);

            IEnumerable <PSVariable> result = await this.powerShellContext.ExecuteCommandAsync <PSVariable>(psCommand, sendErrorToHost : false).ConfigureAwait(false);

            PSVariable psVariable = result.FirstOrDefault();

            if (psVariable == null)
            {
                throw new Exception($"Failed to retrieve PSVariable object for '{name}' from scope '{scope}'.");
            }

            // We have the PSVariable object for the variable the user wants to set and an object to assign to that variable.
            // The last step is to determine whether the PSVariable is "strongly typed" which may require a conversion.
            // If it is not strongly typed, we simply assign the object directly to the PSVariable potentially changing its type.
            // Turns out ArgumentTypeConverterAttribute is not public. So we call the attribute through it's base class -
            // ArgumentTransformationAttribute.
            var argTypeConverterAttr =
                psVariable.Attributes
                .OfType <ArgumentTransformationAttribute>()
                .FirstOrDefault(a => a.GetType().Name.Equals("ArgumentTypeConverterAttribute"));

            if (argTypeConverterAttr != null)
            {
                // PSVariable is strongly typed. Need to apply the conversion/transform to the new value.
                psCommand.Commands.Clear();
                psCommand = new PSCommand();
                psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Get-Variable");
                psCommand.AddParameter("Name", "ExecutionContext");
                psCommand.AddParameter("ValueOnly");

                errorMessages.Clear();

                var getExecContextResults =
                    await this.powerShellContext.ExecuteCommandAsync <object>(
                        psCommand,
                        errorMessages,
                        sendErrorToHost : false).ConfigureAwait(false);

                EngineIntrinsics executionContext = getExecContextResults.OfType <EngineIntrinsics>().FirstOrDefault();

                var msg = $"Setting variable '{name}' using conversion to value: {psobject ?? "<null>"}";
                this.logger.LogTrace(msg);

                psVariable.Value = argTypeConverterAttr.Transform(executionContext, psobject);
            }
            else
            {
                // PSVariable is *not* strongly typed. In this case, whack the old value with the new value.
                var msg = $"Setting variable '{name}' directly to value: {psobject ?? "<null>"} - previous type was {psVariable.Value?.GetType().Name ?? "<unknown>"}";
                this.logger.LogTrace(msg);
                psVariable.Value = psobject;
            }

            // Use the VariableDetails.ValueString functionality to get the string representation for client debugger.
            // This makes the returned string consistent with the strings normally displayed for variables in the debugger.
            var tempVariable = new VariableDetails(psVariable);

            this.logger.LogTrace($"Set variable '{name}' to: {tempVariable.ValueString ?? "<null>"}");
            return(tempVariable.ValueString);
        }
Exemple #18
0
 public void Remove(PSVariable variable) => this.sessionState.RemoveVariable(variable);
Exemple #19
0
 /// <summary>
 /// Initializes an instance of the VariableDetails class from
 /// the details contained in a PSVariable instance.
 /// </summary>
 /// <param name="psVariable">
 /// The PSVariable instance from which variable details will be obtained.
 /// </param>
 public VariableDetails(PSVariable psVariable)
     : this(DollarPrefix + psVariable.Name, psVariable.Value)
 {
 }
Exemple #20
0
 internal void RemoveAtScope(PSVariable variable, string scope) => this.sessionState.RemoveVariableAtScope(variable, scope);
Exemple #21
0
 private bool IsExcluded(PSVariable variable)
 {
     return(variable.Visibility != SessionStateEntryVisibility.Public ||
            IsExcluded(variable.Name));
 }
 public static bool IsNotEmpty(this PSVariable psVariable)
 {
     return(psVariable.Value.ToString() != "");
 }
Exemple #23
0
        /// <summary>
        /// The implementation of the Clear-Variable command.
        /// </summary>
        protected override void ProcessRecord()
        {
            foreach (string varName in Name)
            {
                bool wasFiltered = false;

                List <PSVariable> matchingVariables =
                    GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false);

                if (matchingVariables.Count == 0 && !wasFiltered)
                {
                    // Since the variable wasn't found and no glob
                    // characters were specified, write an error.

                    ItemNotFoundException itemNotFound =
                        new ItemNotFoundException(
                            varName,
                            "VariableNotFound",
                            SessionStateStrings.VariableNotFound);

                    WriteError(
                        new ErrorRecord(
                            itemNotFound.ErrorRecord,
                            itemNotFound));

                    continue;
                }

                foreach (PSVariable matchingVariable in matchingVariables)
                {
                    // Since the variable doesn't exist or -Force was specified,
                    // Call should process to validate the set with the user.

                    string action = VariableCommandStrings.ClearVariableAction;

                    string target = StringUtil.Format(VariableCommandStrings.ClearVariableTarget, matchingVariable.Name);

                    if (ShouldProcess(target, action))
                    {
                        PSVariable result = matchingVariable;

                        try
                        {
                            if (_force &&
                                (matchingVariable.Options & ScopedItemOptions.ReadOnly) != 0)
                            {
                                // Remove the ReadOnly bit to set the value and then reapply

                                matchingVariable.SetOptions(matchingVariable.Options & ~ScopedItemOptions.ReadOnly, true);

                                result = ClearValue(matchingVariable);

                                matchingVariable.SetOptions(matchingVariable.Options | ScopedItemOptions.ReadOnly, true);
                            }
                            else
                            {
                                result = ClearValue(matchingVariable);
                            }
                        }
                        catch (SessionStateException sessionStateException)
                        {
                            WriteError(
                                new ErrorRecord(
                                    sessionStateException.ErrorRecord,
                                    sessionStateException));
                            continue;
                        }
                        catch (PSArgumentException argException)
                        {
                            WriteError(
                                new ErrorRecord(
                                    argException.ErrorRecord,
                                    argException));
                            continue;
                        }

                        if (_passThru)
                        {
                            WriteObject(result);
                        }
                    }
                }
            }
        }
Exemple #24
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 });
                        }
                    }
                }
            }
        }
Exemple #25
0
        /// <summary>
        /// Sets the variables of the given names to the specified value.
        /// </summary>
        /// <param name="varNames">
        /// The name(s) of the variables to set.
        /// </param>
        /// <param name="varValue">
        /// The value to set the variable to.
        /// </param>
        private void SetVariable(string[] varNames, object varValue)
        {
            CommandOrigin origin = MyInvocation.CommandOrigin;

            foreach (string varName in varNames)
            {
                // First look for existing variables to set.

                List <PSVariable> matchingVariables = new List <PSVariable>();

                bool wasFiltered = false;

                if (!String.IsNullOrEmpty(Scope))
                {
                    // We really only need to find matches if the scope was specified.
                    // If the scope wasn't specified then we need to create the
                    // variable in the local scope.

                    matchingVariables =
                        GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false);
                }
                else
                {
                    // Since the scope wasn't specified, it doesn't matter if there
                    // is a variable in another scope, it only matters if there is a
                    // variable in the local scope.

                    matchingVariables =
                        GetMatchingVariables(
                            varName,
                            System.Management.Automation.StringLiterals.Local,
                            out wasFiltered,
                            false);
                }

                // We only want to create the variable if we are not filtering
                // the name.

                if (matchingVariables.Count == 0 &&
                    !wasFiltered)
                {
                    try
                    {
                        ScopedItemOptions newOptions = ScopedItemOptions.None;

                        if (!String.IsNullOrEmpty(Scope) &&
                            String.Equals("private", Scope, StringComparison.OrdinalIgnoreCase))
                        {
                            newOptions = ScopedItemOptions.Private;
                        }

                        if (_options != null)
                        {
                            newOptions |= (ScopedItemOptions)_options;
                        }

                        object newVarValue = varValue;
                        if (newVarValue == AutomationNull.Value)
                        {
                            newVarValue = null;
                        }

                        PSVariable varToSet =
                            new PSVariable(
                                varName,
                                newVarValue,
                                newOptions);

                        if (Description == null)
                        {
                            Description = String.Empty;
                        }
                        varToSet.Description = Description;

                        // If visibility was specified, set it on the variable
                        if (_visibility != null)
                        {
                            varToSet.Visibility = Visibility;
                        }

                        string action = VariableCommandStrings.SetVariableAction;

                        string target = StringUtil.Format(VariableCommandStrings.SetVariableTarget, varName, newVarValue);

                        if (ShouldProcess(target, action))
                        {
                            object result = null;

                            if (String.IsNullOrEmpty(Scope))
                            {
                                result =
                                    SessionState.Internal.SetVariable(varToSet, Force, origin);
                            }
                            else
                            {
                                result =
                                    SessionState.Internal.SetVariableAtScope(varToSet, Scope, Force, origin);
                            }

                            if (_passThru && result != null)
                            {
                                WriteObject(result);
                            }
                        }
                    }
                    catch (SessionStateException sessionStateException)
                    {
                        WriteError(
                            new ErrorRecord(
                                sessionStateException.ErrorRecord,
                                sessionStateException));
                        continue;
                    }
                    catch (PSArgumentException argException)
                    {
                        WriteError(
                            new ErrorRecord(
                                argException.ErrorRecord,
                                argException));
                        continue;
                    }
                }
                else
                {
                    foreach (PSVariable matchingVariable in matchingVariables)
                    {
                        string action = VariableCommandStrings.SetVariableAction;

                        string target = StringUtil.Format(VariableCommandStrings.SetVariableTarget, matchingVariable.Name, varValue);

                        if (ShouldProcess(target, action))
                        {
                            object result = null;

                            try
                            {
                                // Since the variable existed in the specified scope, or
                                // in the local scope if no scope was specified, use
                                // the reference returned to set the variable properties.

                                // If we want to force setting over a readonly variable
                                // we have to temporarily mark the variable writable.

                                bool wasReadOnly = false;
                                if (Force &&
                                    (matchingVariable.Options & ScopedItemOptions.ReadOnly) != 0)
                                {
                                    matchingVariable.SetOptions(matchingVariable.Options & ~ScopedItemOptions.ReadOnly, true);
                                    wasReadOnly = true;
                                }

                                // Now change the value, options, or description
                                // and set the variable

                                if (varValue != AutomationNull.Value)
                                {
                                    matchingVariable.Value = varValue;

                                    if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                                    {
                                        // In 'ConstrainedLanguage' we want to monitor untrusted values assigned to 'Global:' variables
                                        // and 'Script:' variables, because they may be set from 'ConstrainedLanguage' environment and
                                        // referenced within trusted script block, and thus result in security issues.
                                        // Here we are setting the value of an existing variable and don't know what scope this variable
                                        // is from, so we mark the value as untrusted, regardless of the scope.
                                        ExecutionContext.MarkObjectAsUntrusted(matchingVariable.Value);
                                    }
                                }

                                if (Description != null)
                                {
                                    matchingVariable.Description = Description;
                                }

                                if (_options != null)
                                {
                                    matchingVariable.Options = (ScopedItemOptions)_options;
                                }
                                else
                                {
                                    if (wasReadOnly)
                                    {
                                        matchingVariable.SetOptions(matchingVariable.Options | ScopedItemOptions.ReadOnly, true);
                                    }
                                }

                                // If visibility was specified, set it on the variable
                                if (_visibility != null)
                                {
                                    matchingVariable.Visibility = Visibility;
                                }

                                result = matchingVariable;
                            }
                            catch (SessionStateException sessionStateException)
                            {
                                WriteError(
                                    new ErrorRecord(
                                        sessionStateException.ErrorRecord,
                                        sessionStateException));
                                continue;
                            }
                            catch (PSArgumentException argException)
                            {
                                WriteError(
                                    new ErrorRecord(
                                        argException.ErrorRecord,
                                        argException));
                                continue;
                            }

                            if (_passThru && result != null)
                            {
                                WriteObject(result);
                            }
                        }
                    }
                }
            }
        }
Exemple #26
0
        //!STOP!
        // With 'Opened' state it is called from another thread.
        // Also, it can be broken, e.g. x86 build may fail on x64 machine.
        void OnRunspaceStateEvent(object sender, RunspaceStateEventArgs e)
        {
            //! Carefully process events other than 'Opened'.
            if (e.RunspaceStateInfo.State != RunspaceState.Opened)
            {
                // alive? do nothing, wait for other events
                if (e.RunspaceStateInfo.State != RunspaceState.Broken)
                {
                    return;
                }

                // broken; keep an error silently
                _errorFatal = e.RunspaceStateInfo.Reason;

                //! Set the broken flag, waiting threads may continue.
                //! The last code, Invoking() may be waiting for this.
                _isRunspaceOpenedOrBroken = true;
                return;
            }

            // Add the module path.
            // STOP: [_100127_182335 test]
            // *) Add before the profile, so that it can load modules.
            // *) Add after the core loading so that standard paths are added.
            // *) Check for already added, e.g. when starting from another Far.
            var modulePathAdd = string.Concat(AppHome, "\\Modules;");
            var modulePathNow = Environment.GetEnvironmentVariable(Word.PSModulePath);

            if (!modulePathNow.Contains(modulePathAdd))
            {
                Environment.SetEnvironmentVariable(Word.PSModulePath, modulePathAdd + modulePathNow);
            }

            //! If it is async then PS catches all and adds errors to $Error.
            //! Thus, we don't catch anything, because this is normally async.
            string message = null;

            try
            {
                //_090315_091325
                // Get engine once to avoid this: "A pipeline is already executing. Concurrent SessionStateProxy method call is not allowed."
                // Looks like a hack, but it works fine. Problem case: run Test-CallStack-.ps1, Esc -> the error above.
                // SVN tag 4.2.26
                _engine_ = Runspace.SessionStateProxy.PSVariable.GetValue(Word.ExecutionContext) as EngineIntrinsics;

                // get version
                try
                {
                    _PSVersion = (Version)((IDictionary)Runspace.SessionStateProxy.PSVariable.GetValue("PSVersionTable"))["PSVersion"];
                }
                catch
                {
                    throw new InvalidOperationException("Cannot get PowerShell version.");
                }

                // new variables
                var var1 = new PSVariable("Psf", this, ScopedItemOptions.AllScope | ScopedItemOptions.Constant)
                {
                    Description = "Exposes PowerShellFar."
                };
                var var2 = new PSVariable("Far", Far.Api, ScopedItemOptions.AllScope | ScopedItemOptions.Constant)
                {
                    Description = "Exposes FarNet."
                };
                Engine.SessionState.PSVariable.Set(var1);
                Engine.SessionState.PSVariable.Set(var2);

                // invoke profiles
                using (var ps = NewPowerShell())
                {
                    // internal profile (NB: there is trap in there)
                    ps.AddCommand(Path.Combine(A.Psf.AppHome, "PowerShellFar.ps1"), false).Invoke();

                    // user profile, separately for better diagnostics
                    var profile = Entry.RoamingData + "\\Profile.ps1";
                    if (File.Exists(profile))
                    {
                        ps.Commands.Clear();
                        try
                        {
                            ps.AddCommand(profile, false).Invoke();
                        }
                        catch (RuntimeException ex)
                        {
                            message = string.Format(null, @"
Error in the profile:
{0}

Error message:
{1}

See $Error for details.
", profile, ex.Message);
                        }
                    }
                }
            }
            finally
            {
                // GUI message
                if (message != null)
                {
                    Far.Api.Message(message, Res.Me, MessageOptions.Warning | MessageOptions.Gui | MessageOptions.Ok);
                }

                //! The last code, Invoking() may be waiting for this.
                _isRunspaceOpenedOrBroken = true;
            }
        }
 internal void RemoveVariable(PSVariable variable)
 {
     RemoveVariable(variable.Name);
 }
Exemple #28
0
 internal void SetPipelineVariable(PSVariable pipelineVariable)
 {
     _pipelineVariableObject = pipelineVariable;
 }
        protected override void ProcessRecord()
        {
            LogErrors(() =>
            {
                if (!CheckSessionCanDoInteractiveAction())
                {
                    WriteObject("cancel");
                    return;
                }

                AssertDefaultSize(500, 300);
                var message = new ShowMultiValuePromptMessage(Parameters, WidthString, HeightString, Title, Description,
                                                              Icon, OkButtonName, CancelButtonName, ShowHints, Validator, ValidatorParameters, CurrentSessionKey);


                foreach (Hashtable result in Parameters)
                {
                    var name = result["Name"] as string;

                    PSVariable variable = null;
                    if (!string.IsNullOrEmpty(name))
                    {
                        variable = SessionState.PSVariable.Get((string)result["Name"]);
                    }

                    if (result["Variable"] != null)
                    {
                        variable = (PSVariable)((PSObject)result["Variable"]).BaseObject;
                        result.Add("Name", variable.Name);
                        name = variable.Name;
                    }

                    if (variable != null)
                    {
                        if (!result.ContainsKey("Value"))
                        {
                            var varValue = variable.Value.BaseObject();

                            if (varValue is IEnumerable <object> )
                            {
                                varValue = (varValue as IEnumerable <object>).Select(p => p.BaseObject()).ToList();
                            }

                            result.Add("Value", varValue);
                        }
                        var varTitle = result["Title"];
                        if (varTitle == null)
                        {
                            result.Add("Title", string.IsNullOrEmpty(variable.Name) ? name : variable.Name);
                        }
                        var varDesc = result["Description"];
                        if (varDesc == null)
                        {
                            result.Add("Description", variable.Description);
                        }
                    }

                    if (result["Value"] == null)
                    {
                        if (result.ContainsKey("Value"))
                        {
                            result["Value"] = string.Empty;
                        }
                        else
                        {
                            result.Add("Value", string.Empty);
                        }
                    }
                }

                PutMessage(message);
                var results = (object[])message.GetResult();
                WriteObject(results != null ? "ok" : "cancel");
                if (results != null)
                {
                    foreach (Hashtable result in results)
                    {
                        var resultValue = result["Value"];
                        if (resultValue is Item)
                        {
                            resultValue = ItemShellExtensions.GetPsObject(SessionState, resultValue as Item);
                        }
                        if (resultValue is List <Item> )
                        {
                            resultValue =
                                (resultValue as List <Item>).Where(p => p != null)
                                .Select(p => ItemShellExtensions.GetPsObject(SessionState, p))
                                .ToArray();
                        }
                        SessionState.PSVariable.Set((string)result["Name"], resultValue);
                    }
                }
            });
        }
Exemple #30
0
 internal ClosureVariableProperty(string name)
 {
     _variable = new PSVariable(name);
     SetMemberName(name);
 }