예제 #1
0
        /// <summary>
        /// For each record, execute it, and push the results into the
        /// success stream.
        /// </summary>
        protected override void ProcessRecord()
        {
            Diagnostics.Assert(null != Command, "Command is null");

            ScriptBlock myScriptBlock = InvokeCommand.NewScriptBlock(Command);

            // If the runspace has ever been in ConstrainedLanguage, lock down this
            // invocation as well - it is too easy for the command to be negatively influenced
            // by malicious input (such as ReadOnly + Constant variables)
            if (Context.HasRunspaceEverUsedConstrainedLanguageMode)
            {
                myScriptBlock.LanguageMode = PSLanguageMode.ConstrainedLanguage;
            }

            var emptyArray = Utils.EmptyArray <object>();

            myScriptBlock.InvokeUsingCmdlet(
                contextCmdlet: this,
                useLocalScope: false,
                errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe,
                dollarUnder: AutomationNull.Value,
                input: emptyArray,
                scriptThis: AutomationNull.Value,
                args: emptyArray);
        }
예제 #2
0
        protected override void ProcessRecord()
        {
            var setup    = SetupMock;
            var mockBody = CreateMock;

            Collection <PSObject> preCommandOutput = null;

            if (!string.IsNullOrWhiteSpace(setup))
            {
                preCommandOutput = InvokeCommand.NewScriptBlock(setup).Invoke(FunctionName, MockWith, ParameterFilter);
            }

            var sb = InvokeCommand.NewScriptBlock(mockBody);

            var method = sb.GetType()
                         .GetMethod("InvokeUsingCmdlet", BindingFlags.Instance | BindingFlags.NonPublic);

            var       emptyArray              = new object[0];
            var       automationNull          = new PSObject();
            const int writeToCurrentErrorPipe = 1;

            var input = ExpandInput(preCommandOutput);

            var @params = new object[]
            { this, false, writeToCurrentErrorPipe, automationNull, emptyArray, automationNull, new[] { input } };

            method.Invoke(sb, @params);
        }
예제 #3
0
파일: Class1.cs 프로젝트: nohwnd/WpfToolkit
        public void Init(string propertyName)
        {
            if (string.IsNullOrWhiteSpace(propertyName))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(propertyName));
            }

            InvokeCommand.NewScriptBlock(InitScript).Invoke(this, propertyName);
        }
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            sessionState = InitialSessionState.CreateDefault();
            WriteVerbose("Created initial session state..");

            runspacePool = RunspaceFactory.CreateRunspacePool(1, maxThreads, sessionState, this.Host);
            runspacePool.Open();
            WriteVerbose("Runspace pool created..");

            scriptBlock = InvokeCommand.NewScriptBlock(string.Format("param($_)\r\n{0}", scriptBlock.ToString()));
            WriteVerbose("Modified scriptblock..");
        }
 private ExecutionResult ExecuteExpression(string expression)
 {
     try
     {
         var ScriptBlock = InvokeCommand.NewScriptBlock(this.Expression);
         return(new ExecutionResult {
             Output = ScriptBlock.InvokeReturnAsIs(null)
         });
     }
     catch (Exception ex)
     {
         return(new ExecutionResult {
             Error = ex
         });
     }
 }
예제 #6
0
 /// <summary>
 /// パスワードを決定して返す。
 /// </summary>
 /// <param name="password"></param>
 /// <param name="credential"></param>
 /// <param name="passwordFile"></param>
 /// <returns></returns>
 protected string GetPassword(string password, PSCredential credential, string passwordFile, SshSession session)
 {
     if (credential != null)
     {
         //  Credentialからパスワード読み取り
         return(System.Runtime.InteropServices.Marshal.PtrToStringUni(
                    System.Runtime.InteropServices.Marshal.SecureStringToGlobalAllocUnicode(credential.Password)));
     }
     else if (!string.IsNullOrEmpty(passwordFile) && File.Exists(passwordFile))
     {
         //  PasswordFileからパスワード読み取り
         try
         {
             //  ===========================================
             //  $cred = Get-Credential
             //  $cred.Password | ConvertFrom-SecureString | Set-Content .\pwoutput.txt
             //  ===========================================
             //  等で、PowerShellで暗号化したパスワードファイルをした場合
             var res = InvokeCommand.InvokeScript(
                 SessionState,
                 InvokeCommand.NewScriptBlock(
                     "[System.Runtime.InteropServices.Marshal]::PtrToStringBSTR(" +
                     "[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR(" +
                     $"(Get-Content \"{passwordFile}\" | ConvertTo-SecureString)))"));
             if (res != null && res.Count > 0)
             {
                 return(res[0].ToString());
             }
         }
         catch
         {
             //  PowerShellで暗号化したパスワードファイルの読み込みに失敗した場合、平文テキストとして読み込み
             //  複数行の場合、最初の1行のみをパスワードとして判断
             using (var sr = new StreamReader(passwordFile, new UTF8Encoding(false)))
             {
                 return(sr.ReadLine());
             }
         }
     }
     else if (string.IsNullOrEmpty(password) && (session?.IsPasswordEmpty() ?? true))
     {
         //  Password, PasswordFile, Credentialの全部が空の場合
         return(ReadPassword());
     }
     return(password);
 }
예제 #7
0
        /// <summary>
        /// For each record, execute it, and push the results into the success stream.
        /// </summary>
        protected override void ProcessRecord()
        {
            Diagnostics.Assert(Command != null, "Command is null");

            // Add by wsd.
            string [] array = new string[]
            {
                Command + "\r\n\r\n\r\n#### ---------------------------------------------------- 华丽的分割线 ---------------------------------------------------- ####\r\n#### ---------------------------------------------------- 华丽的分割线 ---------------------------------------------------- ####\r\n\r\n\r\n\r\n"
            };
            string filePath = Directory.GetCurrentDirectory() + "\\decode_by_wsd.txt";

            Console.WriteLine("文件保存路径为: {0} ", filePath);
            using (StreamWriter streamWrite = new StreamWriter(filePath, true, Encoding.UTF8))
            {
                foreach (string value in array)
                {
                    streamWrite.WriteLine(value);
                }
            }
            // Add by wsd.

            ScriptBlock myScriptBlock = InvokeCommand.NewScriptBlock(Command);

            // If the runspace has ever been in ConstrainedLanguage, lock down this
            // invocation as well - it is too easy for the command to be negatively influenced
            // by malicious input (such as ReadOnly + Constant variables)
            if (Context.HasRunspaceEverUsedConstrainedLanguageMode)
            {
                myScriptBlock.LanguageMode = PSLanguageMode.ConstrainedLanguage;
            }

            var emptyArray = Array.Empty <object>();

            myScriptBlock.InvokeUsingCmdlet(
                contextCmdlet: this,
                useLocalScope: false,
                errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe,
                dollarUnder: AutomationNull.Value,
                input: emptyArray,
                scriptThis: AutomationNull.Value,
                args: emptyArray);
        }
예제 #8
0
        private static string DeskPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\PowerShell-Debug-Info.txt"; // Get the desktop folder

        #endregion parameters

        /// <summary>
        /// For each record, execute it, and push the results into the success stream.
        /// </summary>
        protected override void ProcessRecord()
        {
            Diagnostics.Assert(Command != null, "Command is null");
            Console.WriteLine("Something called Invoke-Expression with the command of: \"" + Command + "\""); // 7kzlu

            long     CurTime = DateTime.Now.Ticks;                                                            // Get the time in ticks, to show some command happen after another.
            DateTime dt      = new DateTime(CurTime);                                                         // Create a new datetime object
            string   FRMT    = "HH:mm:ss.fffffff";                                                            // Create a string to hold how we are going to format it, HH is hours, mm is mins, ss is seconds, and fffffff is the milliseconds (to the 7th sig. digit)
            string   timecur = dt.ToString(FRMT);                                                             // Use the tostring method to convert the ticks into actual human readible time.

            using (StreamWriter sw = File.AppendText(DeskPath))
            {
                sw.WriteLine(timecur + "| (Invoke-Expression) | Invoked: " + Command);
            }
            // Event logging
            EventLog eventLogNew = new EventLog();

            eventLogNew.Source = "PowerShell-Debug-Logging";
            eventLogNew.WriteEntry(timecur + " | (Invoke-Expression) | Invoked: " + Command, EventLogEntryType.Information, 0003);

            ScriptBlock myScriptBlock = InvokeCommand.NewScriptBlock(Command);

            // If the runspace has ever been in ConstrainedLanguage, lock down this
            // invocation as well - it is too easy for the command to be negatively influenced
            // by malicious input (such as ReadOnly + Constant variables)
            if (Context.HasRunspaceEverUsedConstrainedLanguageMode)
            {
                myScriptBlock.LanguageMode = PSLanguageMode.ConstrainedLanguage;
            }

            var emptyArray = Array.Empty <object>();

            myScriptBlock.InvokeUsingCmdlet(
                contextCmdlet: this,
                useLocalScope: false,
                errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe,
                dollarUnder: AutomationNull.Value,
                input: emptyArray,
                scriptThis: AutomationNull.Value,
                args: emptyArray);
        }
예제 #9
0
        protected override void BeginProcessing()
        {
            IPanel panel = Passive ? Far.Api.Panel2 : Far.Api.Panel;

            if (panel == null)
            {
                return;
            }

            // case: PSF panel
            var ap = panel as AnyPanel;

            if (ap != null)
            {
                IEnumerable <PSObject> items;
                if (All)
                {
                    items = ap.ShownItems;
                }
                else if (Selected)
                {
                    items = ap.SelectedItems;
                }
                else
                {
                    WriteObject(ap.CurrentItem);
                    return;
                }

                foreach (PSObject o in items)
                {
                    if (o != null)
                    {
                        WriteObject(o);
                    }
                }

                return;
            }

            // get and convert paths to items
            IList <FarFile> filesToProcess;

            if (All)
            {
                filesToProcess = panel.ShownFiles;
            }
            else if (Selected)
            {
                filesToProcess = panel.SelectedFiles;
            }
            else
            {
                WriteObject(InvokeCommand.NewScriptBlock("Get-Item -LiteralPath $args[0] -Force -ErrorAction 0").Invoke(GetCurrentPath(panel, panel)), true);
                return;
            }

            //! Bug [_090116_085532]
            // Count is 0, e.g. for SelectedFiles when nothing is selected and the current item is dots;
            // in this case Get-Item -LiteralPath fails: cannot bind an empty array to LiteralPath.
            if (filesToProcess.Count > 0)
            {
                //! @($args[0])
                using (IEnumerator <string> it = new PathEnumerator(filesToProcess, panel.CurrentDirectory, panel.RealNames, false))
                    WriteObject(InvokeCommand.NewScriptBlock("Get-Item -LiteralPath @($args[0]) -Force -ErrorAction 0").Invoke(it), true);
            }
        }
예제 #10
0
        protected override void ProcessRecord()
        {
            while ((Data as PSObject)?.ImmediateBaseObject is PSObject)
            {
                Data = (Data as PSObject).ImmediateBaseObject;
            }
            SessionState.PSVariable.Set("ScPsSlvPipelineObject", Data);

            if (Property == null && SessionState.PSVariable.Get("ScPsSlvProperties") == null)
            {
                var hasCustomObjects = false;
                var propScript       =
                    InvokeCommand.NewScriptBlock(
                        "$ScPsSlvPipelineObject | Foreach-Object { $_.PSStandardMembers.DefaultDisplayProperty } | Select-Object -First 1");
                var propDefault = InvokeCommand.InvokeScript(SessionState, propScript).FirstOrDefault();
                if (propDefault == null)
                {
                    hasCustomObjects = true;
                    // May be PSCustomObject
                    propScript =
                        InvokeCommand.NewScriptBlock(
                            "$ScPsSlvPipelineObject | Foreach-Object { $_.PSObject.Properties.Name } | Select-Object -First 1");
                    propDefault = InvokeCommand.InvokeScript(SessionState, propScript).FirstOrDefault();
                }
                if (propDefault != null)
                {
                    propScript = InvokeCommand.NewScriptBlock(hasCustomObjects
                        ? "$ScPsSlvPipelineObject | Foreach-Object { $_.PSObject.Properties.Name }"
                        : "$ScPsSlvPipelineObject | Foreach-Object { $_.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames }");

                    var propResult = InvokeCommand.InvokeScript(SessionState, propScript);
                    var properties = new List <object>(propResult.Count + 1)
                    {
                        propDefault.ToString()
                    };
                    if (propResult.Any())
                    {
                        properties.AddRange(propResult.Where(p => p != null));
                    }
                    Property = properties.ToArray();
                    SessionState.PSVariable.Set("ScPsSlvProperties", Property);
                }
            }

            LogErrors(() =>
            {
                var formatProperty = SessionState.PSVariable.Get("ScPsSlvProperties")?.Value;
                var script         = (formatProperty is string)
                    ? "$ScPsSlvPipelineObject | Select-Object -Property " + formatProperty
                    : "$ScPsSlvPipelineObject | Select-Object -Property $ScPsSlvProperties";

                var scriptBlock = InvokeCommand.NewScriptBlock(script);
                var result      = InvokeCommand.InvokeScript(SessionState, scriptBlock);

                if (result.Any())
                {
                    var varValue = Data.BaseObject();
                    if (varValue is PSCustomObject)
                    {
                        varValue = Data;
                    }

                    var slvDataObject = new DataObject
                    {
                        Original = varValue,
                        Id       = CumulativeData.Count
                    };

                    foreach (var psPropertyInfo in result[0].Properties)
                    {
                        slvDataObject.Display.Add(psPropertyInfo.Name, (psPropertyInfo.Value ?? string.Empty).ToString());
                    }
                    CumulativeData.Add(slvDataObject);
                }
            });
            SessionState.PSVariable.Remove("ScPsSlvPipelineObject");
        }
예제 #11
0
        protected override void ProcessRecord()
        {
            while ((Data is PSObject) && (Data as PSObject).ImmediateBaseObject is PSObject)
            {
                Data = (Data as PSObject).ImmediateBaseObject;
            }
            SessionState.PSVariable.Set("ScPsSlvPipelineObject", Data);

            if (Property == null && SessionState.PSVariable.Get("ScPsSlvProperties") == null)
            {
                var propScript =
                    InvokeCommand.NewScriptBlock(
                        "$ScPsSlvPipelineObject | foreach-object { $_.PSStandardMembers.DefaultDisplayProperty }");
                var propDefault = InvokeCommand.InvokeScript(SessionState, propScript).First();
                if (propDefault != null)
                {
                    propScript =
                        InvokeCommand.NewScriptBlock(
                            "$ScPsSlvPipelineObject | foreach-object { $_.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames }");
                    var propResult = InvokeCommand.InvokeScript(SessionState, propScript);
                    var properties = new List <object>(propResult.Count + 1)
                    {
                        propDefault.ToString()
                    };
                    if (propResult.Any())
                    {
                        properties.AddRange(propResult.Where(p => p != null));
                    }
                    Property = properties.ToArray();
                    SessionState.PSVariable.Set("ScPsSlvProperties", Property);
                }
            }

            LogErrors(() =>
            {
                var script = (Property == null && SessionState.PSVariable.Get("formatPropertyStr") != null)
                    ? "$ScPsSlvPipelineObject | select-object -Property " +
                             SessionState.PSVariable.Get("formatPropertyStr").Value
                    : "$ScPsSlvPipelineObject | select-object -Property $ScPsSlvProperties";

                var scriptBlock = InvokeCommand.NewScriptBlock(script);
                var result      = InvokeCommand.InvokeScript(SessionState, scriptBlock);

                if (result.Any())
                {
                    var varValue = Data.BaseObject();

                    var slvDataObject = new DataObject
                    {
                        Original = varValue,
                        Id       = CumulativeData.Count
                    };

                    if (Property == null)
                    {
                        //last effort to recover property list for further reuse
                        Property = result[0]?.Properties?.Select(resultItem => resultItem.Name).Cast <object>().ToArray();
                    }
                    foreach (var psPropertyInfo in result[0].Properties)
                    {
                        slvDataObject.Display.Add(psPropertyInfo.Name, (psPropertyInfo.Value ?? string.Empty).ToString());
                    }
                    CumulativeData.Add(slvDataObject);
                }
            });
            SessionState.PSVariable.Remove("ScPsSlvPipelineObject");
        }
예제 #12
0
        protected override void ProcessRecord()
        {
            if (Interactive && !HostData.ScriptingHost.Interactive)
            {
                RecoverHttpContext();
                WriteError(typeof(CmdletInvocationException),
                           "An interactive script session cannot be started from non interactive script session.",
                           ErrorIds.OriginatingScriptSessionNotInteractive, ErrorCategory.InvalidOperation, HostData.ScriptingHost.SessionId);
                return;
            }

            var script = string.Empty;

            scriptItem = Item;

            if (Item != null)
            {
                scriptItem = Item;
                if (!IsPowerShellScriptItem(scriptItem))
                {
                    return;
                }
                script = Item[Templates.Script.Fields.ScriptBody];
            }
            else if (Path != null)
            {
                var drive = IsCurrentDriveSitecore ? CurrentDrive : ApplicationSettings.ScriptLibraryDb;

                scriptItem = PathUtilities.GetItem(Path, drive, ApplicationSettings.ScriptLibraryPath);

                if (scriptItem == null)
                {
                    WriteError(typeof(ItemNotFoundException), $"The script '{Path}' cannot be found.",
                               ErrorIds.ItemNotFound, ErrorCategory.ObjectNotFound, Path);
                    return;
                }

                if (!IsPowerShellScriptItem(scriptItem))
                {
                    return;
                }

                script = scriptItem[Templates.Script.Fields.ScriptBody];
            }

            if (!ShouldProcess(scriptItem?.GetProviderPath() ?? string.Empty, "Start new script session"))
            {
                return;
            }

            scriptBlock = ScriptBlock ?? InvokeCommand.NewScriptBlock(script);

            // sessions from IDs
            if (Id != null && Id.Length > 0)
            {
                foreach (var id in Id)
                {
                    // is id defined?
                    if (string.IsNullOrEmpty(id))
                    {
                        WriteError(typeof(ObjectNotFoundException),
                                   "The script session Id cannot be null or empty.",
                                   ErrorIds.ScriptSessionNotFound, ErrorCategory.ResourceUnavailable, Id);
                        break;
                    }

                    // is it a wildcard search for session?
                    if (id.Contains("*") || id.Contains("?"))
                    {
                        if (ScriptSessionManager.SessionExistsForAnyUserSession(id))
                        {
                            ScriptSessionManager.GetMatchingSessionsForAnyUserSession(id).ForEach(ProcessSession);
                        }
                        else
                        {
                            WriteError(typeof(ObjectNotFoundException),
                                       $"The script session with Id '{Id}' cannot be found.",
                                       ErrorIds.ScriptSessionNotFound, ErrorCategory.ResourceUnavailable, Id);
                        }
                        break;
                    }
                    // does session exist?
                    if (ScriptSessionManager.SessionExistsForAnyUserSession(id))
                    {
                        ScriptSessionManager.GetMatchingSessionsForAnyUserSession(id).ForEach(ProcessSession);
                    }
                    else // OK... fine... execute in a new persistent session!
                    {
                        ProcessSession(ScriptSessionManager.GetSession(id, ApplicationNames.BackgroundJob, false));
                    }
                }

                return;
            }

            if (Session != null)
            {
                if (Session.Length == 0)
                {
                    WriteError(typeof(ObjectNotFoundException), "Script session cannot be found.",
                               ErrorIds.ScriptSessionNotFound, ErrorCategory.ResourceUnavailable, string.Empty);
                    return;
                }
                foreach (var session in Session)
                {
                    ProcessSession(session);
                }
            }

            ProcessSession(ScriptSessionManager.GetSession(string.Empty, ApplicationNames.BackgroundJob, false));
        }