Exemple #1
0
        /// <summary>
        /// Runs a Powershell script taking it's path and parameters.
        /// </summary>
        /// <param name="scriptFullPath">The full file path for the .ps1 file.</param>
        /// <param name="parameters">The parameters for the script, can be null.</param>
        /// <returns>The output from the Powershell execution.</returns>
        public static string ExecutePowerShellFile(PowerShellScript myScript, ICollection <CommandParameter> parameters = null)
        {
            string scriptFullPath = string.Format("{0}\\{1}", myScript.FilePath, myScript.FileName);
            var    runspace       = RunspaceFactory.CreateRunspace();

            runspace.Open();
            var pipeline = runspace.CreatePipeline();
            var cmd      = new Command(scriptFullPath);

            if (parameters != null)
            {
                foreach (var p in parameters)
                {
                    cmd.Parameters.Add(p);
                }
            }
            pipeline.Commands.Add(cmd);
            var results = pipeline.Invoke();

            pipeline.Dispose();
            runspace.Dispose();

            StringBuilder stringBuilder = new StringBuilder();

            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }

            //Get details information
            //results[0].BaseObject

            return(stringBuilder.ToString());
        }
        public ActionResult RunScript(PowerShellScript data)
        {
            string result = RunScriptLogic.RunScript(data.ScriptCommand);

            ViewBag.Result = result;
            return(View("Index"));
        }
Exemple #3
0
 public void ScriptParserTest()
 {
     using (var ps = new PowerShellScript(@"e:\devel\repos\Playnite\source\PlayniteUI\Scripts\PowerShell\ExportLibrary.ps1"))
     {
         Assert.IsNotNull(ps.Attributes);
         Assert.IsNotNull(ps.FunctionExports);
     }
 }
Exemple #4
0
 public virtual void WritePowerShellStep(CustomFileWriter writer, string arguments)
 {
     using (writer.WriteBlock("powerShell"))
     {
         writer.WriteLine($"scriptMode = file {{ path = {PowerShellScript.DoubleQuote()} }}");
         writer.WriteLine($"param(\"jetbrains_powershell_scriptArguments\", {arguments.DoubleQuote()})");
         writer.WriteLine("noProfile = true");
     }
 }
Exemple #5
0
        public void Should_Throw_When_FileNotFound()
        {
            var request = new PowerShellScript
            {
                FileName = string.Empty
            };

            var handler = new PowerShellScriptMonitor(_processStarter);

            handler.Handle(request);
        }
Exemple #6
0
        public void Should_Execute_PowerShellScript()
        {
            var request = new PowerShellScript
            {
                FileName = Path.Combine(_testContext.TestRunDirectory, "Out", "PowerShell.ps1")
            };

            var handler = new PowerShellScriptMonitor(_processStarter);

            handler.Handle(request);

            Assert.AreSame(State.Ok, request.State);
        }
Exemple #7
0
        public void Should_Throw_When_FileNotFound()
        {
            var powershell = new PowerShellScript
            {
                FileName = string.Empty
            };

            var handler = new PowerShellRunner(_processStarter);

            var request = HealthCheckRequest.Create(powershell);

            handler.Handle(request, CancellationToken.None);
        }
Exemple #8
0
        public void Should_Execute_PowerShellScript()
        {
            var powershell = new PowerShellScript
            {
                FileName = Path.Combine(_testContext.TestRunDirectory, "Out", "PowerShell.ps1")
            };

            var handler = new PowerShellRunner(_processStarter);

            var request = HealthCheckRequest.Create(powershell);

            handler.Handle(request, CancellationToken.None);

            Assert.AreSame(State.Ok, request.DataContext.State);
        }
Exemple #9
0
        /// <summary>
        /// Applies a function (if given) to content and returns the
        /// modified content.
        /// </summary>
        /// <param name="function">A function specification, for example "replace:a:b"</param>
        /// <param name="content">The usual variable content</param>
        /// <param name="context">ApplicationJob context for referencing values of other variables</param>
        private static string ReplaceFunction(string function, string content, ApplicationJob context = null)
        {
            function = function.TrimStart(':');
            if (string.IsNullOrEmpty(function))
            {
                return(content);
            }

            string[] parts = SplitEscaped(function, ':');
            if (parts.Length == 0)
            {
                return(content);
            }

            switch (parts[0])
            {
            case "runpowershell":
            case "ps":
                try
                {
                    if (context != null && !context.CanBeShared)
                    {
                        LogDialog.Log(context, "PowerShell command of downloaded application is not executed for security reasons.");
                        return(string.Empty);
                    }

                    PowerShellScript psScript = new PowerShellScript(content);
                    psScript.Execute(context);
                    return(psScript.LastOutput);
                }
                catch
                {
                    return(string.Empty);
                }

            case "empty":
                // Useful, if you want to load, but not use a variable
                return(string.Empty);

            case "ifempty":
                if (string.IsNullOrEmpty(content) && context != null && parts.Length > 1)
                {
                    return(context.Variables.ReplaceAllInString("{" + parts[1] + "}"));
                }

                return(content);

            case "ifemptythenerror":
                if (string.IsNullOrEmpty(content))
                {
                    throw new VariableIsEmptyException();
                }
                return(content);

            case "regexreplace":
                try
                {
                    if (parts.Length > 2)
                    {
                        Regex regex = new Regex(parts[1], RegexOptions.Singleline | RegexOptions.IgnoreCase);
                        return(regex.Replace(content, delegate(Match match) {
                            string result = parts[2];
                            for (int i = 0; i < match.Groups.Count; i++)
                            {
                                result = result.Replace("$" + i, match.Groups[i].Value);
                            }
                            return result;
                        }));
                    }
                }
                catch (ArgumentException ex)
                {
                    LogDialog.Log("Could not process the function 'regexreplace'.", ex);
                }
                return(string.Empty);

            case "multireplace":
            case "multireplacei":
                if (parts.Length > 3)
                {
                    if (string.IsNullOrEmpty(parts[1]))
                    {
                        break;
                    }

                    // Exmaple: multireplace:,:a,b,c:1,2,3
                    char delimiter = parts[1][0];

                    string[] search  = parts[2].Split(delimiter);
                    string[] replace = parts[3].Split(delimiter);
                    for (int i = 0; i < search.Length; i++)
                    {
                        string replaceValue = (replace.Length > i) ? replace[i] : string.Empty;
                        content = parts[0] == "multireplacei" ? ReplaceEx(content, search[i], replaceValue) : content.Replace(search[i], replaceValue);
                    }

                    return(content);
                }
                break;

            case "regex":
                try
                {
                    Regex regex = new Regex(parts[1], RegexOptions.Singleline);
                    Match match = regex.Match(content);
                    if (parts.Length > 2)
                    {
                        int groupNum = Conversion.ToInt(parts[2]);
                        if (groupNum >= 0 && groupNum < match.Groups.Count)
                        {
                            return(match.Groups[groupNum].Value);
                        }
                    }
                    return((match.Success) ? match.Value : string.Empty);
                }
                catch (ArgumentException ex)
                {
                    LogDialog.Log("Could not process the function 'regex'.", ex);
                    return(string.Empty);
                }

            case "regexrandom":
                try
                {
                    Regex           regex   = new Regex(parts[1], RegexOptions.Singleline);
                    MatchCollection matches = regex.Matches(content);
                    if (matches.Count > 0)
                    {
                        int randomPos = random.Next(0, matches.Count - 1);
                        int groupNum  = (parts.Length > 2) ? Conversion.ToInt(parts[2]) : -1;

                        if (groupNum >= 0 && groupNum < matches[randomPos].Groups.Count)
                        {
                            return(matches[randomPos].Groups[groupNum].Value);
                        }
                        else
                        {
                            return(matches[randomPos].Value);
                        }
                    }
                    return(string.Empty);
                }
                catch (ArgumentException ex)
                {
                    LogDialog.Log("Could not process the function 'regex'.", ex);
                    return(string.Empty);
                }

            case "ext":
                return(Path.GetExtension(content).TrimStart('.'));

            case "basefile":
                return(Path.GetFileNameWithoutExtension(content));

            case "directory":
                try
                {
                    if (content.StartsWith("\"") && content.EndsWith("\""))
                    {
                        return("\"" + Path.GetDirectoryName(content.Trim('"')) + "\"");
                    }
                    else
                    {
                        return(Path.GetDirectoryName(content.Trim('"')));
                    }
                }
                catch
                {
                    return(content);
                }

            case "filename":
                try
                {
                    return(Path.GetFileName(content));
                }
                catch
                {
                    return(content);
                }

            case "filenameWithoutExtension":
                try
                {
                    return(Path.GetFileNameWithoutExtension(content));
                }
                catch
                {
                    return(content);
                }

            case "toupper":
                return(content.ToUpper());

            case "tolower":
                return(content.ToLower());

            case "split":
                if (parts.Length >= 3)
                {
                    string[] contentParts = content.Split(parts[1][0]);
                    int      partNum;
                    if (Int32.TryParse(parts[2], out partNum))
                    {
                        if (partNum < 0)
                        {
                            // Negative number: Count from the end
                            partNum = contentParts.Length + partNum;
                        }
                        if (partNum >= 0 && partNum < contentParts.Length)
                        {
                            return(contentParts[partNum]);
                        }
                    }
                }
                break;

            case "trim":
                if (parts.Length >= 2)
                {
                    return(content.Trim(parts[1].ToCharArray()));
                }
                else
                {
                    return(content.Trim());
                }

            case "padleft":
                if (parts.Length == 3)
                {
                    return(content.PadLeft(Conversion.ToInt(parts[1]), parts[2][0]));
                }
                else if (parts.Length == 2)
                {
                    return(content.PadLeft(Conversion.ToInt(parts[1]), ' '));
                }

                return(content);

            case "padright":
                if (parts.Length == 3)
                {
                    return(content.PadRight(Conversion.ToInt(parts[1]), parts[2][0]));
                }
                else if (parts.Length == 2)
                {
                    return(content.PadRight(Conversion.ToInt(parts[1]), ' '));
                }

                return(content);

            case "trimend":
                if (parts.Length >= 2)
                {
                    return(content.TrimEnd(parts[1].ToCharArray()));
                }
                else
                {
                    return(content.TrimEnd());
                }

            case "trimstart":
                if (parts.Length >= 2)
                {
                    return(content.TrimStart(parts[1].ToCharArray()));
                }
                else
                {
                    return(content.TrimStart());
                }

            case "replace":
                if (parts.Length >= 3)
                {
                    return(content.Replace(parts[1], parts[2]));
                }
                break;

            case "formatfilesize":
                return(FormatFileSize.Format(Conversion.ToLong(content)));

            case "startuppath":
                return(Application.StartupPath);

            case "urldecode":
                return(HttpUtility.UrlDecode(content));

            case "urlencode":
                return(HttpUtility.UrlEncode(content));
            }

            return(content);
        }