Esempio n. 1
0
        public static (Collection <PSObject>, Collection <ErrorRecord>) InvokeJeaCommand(string computer, string command, string auth = "ntlm", string scheme = "HTTP", bool display = true)
        {
            Collection <PSObject>    result = new Collection <PSObject>();
            Collection <ErrorRecord> error  = new Collection <ErrorRecord>();
            var remoteComputer = new Uri(String.Format("{0}://{1}:5985/wsman", scheme, computer));
            var connection     = new WSManConnectionInfo(remoteComputer);

            connection.SkipRevocationCheck = true;
            connection.SkipCNCheck         = true;
            connection.SkipCACheck         = true;
            if (auth == "kerberos")
            {
                connection.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
            }
            else
            {
                connection.AuthenticationMechanism = AuthenticationMechanism.Negotiate;
            }
            try
            {
                using (Runspace runspace = RunspaceFactory.CreateRunspace(connection))
                {
                    runspace.Open();
                    using (var powershell = PowerShell.Create())
                    {
                        powershell.Runspace = runspace;
                        if (String.IsNullOrEmpty(command))
                        {
                            powershell.AddCommand("get-command").AddParameter("Name", "*");
                        }
                        else
                        {
                            powershell.AddCommand("get-command").AddParameter("Name", command).AddParameter("showcommandinfo");
                        }
                        result = powershell.Invoke();
                        error  = powershell.Streams.Error.ReadAll();
                    }
                }
            }
            catch (System.Management.Automation.Remoting.PSRemotingTransportException e) // Connecting to remote server 192.168.1.10 failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic
            {
                Console.WriteLine(String.Format("[-] Access is Denied on {0}", connection.ComputerName));
                throw e;
            }
            catch (System.Management.Automation.RemoteException e) //The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode
            {
                throw e;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw e;
            }
            if (display)
            {
                foreach (var err in error)
                {
                    Console.WriteLine(err);
                }
            }
            return(result, error);
        }
        /// <summary>
        /// Method to run the sample script and handle debugger events.
        /// </summary>
        public void Run()
        {
            Console.WriteLine("Starting PowerShell Debugger Sample");
            Console.WriteLine();

            // Create sample script file to debug.
            string fileName = "PowerShellSDKDebuggerSample.ps1";
            string filePath = System.IO.Path.Combine(Environment.CurrentDirectory, fileName);

            System.IO.File.WriteAllText(filePath, _script);

            using (Runspace runspace = RunspaceFactory.CreateRunspace())
            {
                // Open runspace and set debug mode to debug PowerShell scripts and
                // Workflow scripts.  PowerShell script debugging is enabled by default,
                // Workflow debugging is opt-in.
                runspace.Open();
                runspace.Debugger.SetDebugMode(DebugModes.LocalScript);

                using (PowerShell powerShell = PowerShell.Create())
                {
                    powerShell.Runspace = runspace;

                    // Set breakpoint update event handler.  The breakpoint update event is
                    // raised whenever a break point is added, removed, enabled, or disabled.
                    // This event is generally used to display current breakpoint information.
                    runspace.Debugger.BreakpointUpdated += HandlerBreakpointUpdatedEvent;

                    // Set debugger stop event handler.  The debugger stop event is raised
                    // whenever a breakpoint is hit, or for each script execution sequence point
                    // when the debugger is in step mode.  The debugger remains stopped at the
                    // current execution location until the event handler returns.  When the
                    // event handler returns it should set the DebuggerStopEventArgs.ResumeAction
                    // to indicate how the debugger should proceed:
                    //  - Continue      Continue execution until next breakpoint is hit.
                    //  - StepInto      Step into function.
                    //  - StepOut       Step out of function.
                    //  - StepOver      Step over function.
                    //  - Stop          Stop debugging.
                    runspace.Debugger.DebuggerStop += HandleDebuggerStopEvent;

                    // Set initial breakpoint on line 10 of script.  This breakpoint
                    // will be in the script workflow function.
                    powerShell.AddCommand("Set-PSBreakpoint").AddParameter("Script", filePath).AddParameter("Line", 10);
                    powerShell.Invoke();

                    Console.WriteLine("Starting script file: " + filePath);
                    Console.WriteLine();

                    // Run script file.
                    powerShell.Commands.Clear();
                    powerShell.AddScript(filePath).AddCommand("Out-String").AddParameter("Stream", true);
                    var scriptOutput = new PSDataCollection <PSObject>();
                    scriptOutput.DataAdded += (sender, args) =>
                    {
                        // Stream script output to console.
                        foreach (var item in scriptOutput.ReadAll())
                        {
                            Console.WriteLine(item);
                        }
                    };
                    powerShell.Invoke <PSObject>(null, scriptOutput);
                }
            }

            // Delete the sample script file.
            if (System.IO.File.Exists(filePath))
            {
                System.IO.File.Delete(filePath);
            }

            Console.WriteLine("PowerShell Debugger Sample Complete");
            Console.WriteLine();
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey(true);
        }
Esempio n. 3
0
        // clang -o <exe name> <bitcode file> / generates executable
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("| Usage: kts <source filepath> |");
                return;
            }

            string file = args[1];

            var fileinfo = new FileInfo(file);

            if (fileinfo.Exists)
            {
                if (Path.GetExtension(file) == ".kts")
                {
                    KTUSharpScanner scanner     = new KTUSharpScanner(file);
                    var             tokens      = scanner.ScanTokens();
                    KTUSharpParser  parser      = new KTUSharpParser(tokens);
                    var             statements  = parser.ParseTokens();
                    ASTTypeChecker  typeChecker = new ASTTypeChecker(statements);
                    typeChecker.ExecuteTypeCheck();

                    if (typeChecker.Failed)
                    {
                        return;
                    }

                    try
                    {
                        CodeGeneration.CodeGenerator gen = new CodeGeneration.CodeGenerator(file);
                        gen.GenerateBitcode(statements);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Crashed from bitcode generation.");
                        Console.WriteLine(e);
                    }

                    var fileWithoutExt = Path.GetFileNameWithoutExtension(file);
                    var exeFile        = fileWithoutExt + ".exe";
                    var bitcodeFile    = fileWithoutExt + ".bc";

                    var powershell = PowerShell.Create();
                    using var runspace = RunspaceFactory.CreateRunspace();
                    runspace.Open();

                    powershell.Runspace = runspace;
                    string command = $@"clang -o {exeFile} {bitcodeFile}";
                    powershell.AddScript(command);
                    var psout = powershell.Invoke();
                    if (powershell.Streams.Error.Count == 0)
                    {
                        var psOutString = new StringBuilder().AppendJoin(Environment.NewLine, psout);
                        Console.WriteLine(psOutString);
                    }
                    else
                    {
                        foreach (var err in powershell.Streams.Error)
                        {
                            Console.WriteLine(err.ToString());
                        }
                    }
                }
                else
                {
                    Console.WriteLine("| File does not have a .kts extension |");
                }
            }
            else
            {
                Console.WriteLine("| Bad source file path given | Maybe use absolute path? |");
            }
        }
Esempio n. 4
0
        public MainWindow()
        {
            var dock_panel = new DockPanel();

            var scroll_viewer = new ScrollViewer();

            var text_block = new TextBlock()
            {
                FontFamily = new FontFamily("Lucida Console"),
                Background = new SolidColorBrush(Color.FromRgb(1, 36, 86)),
                Foreground = new SolidColorBrush(Colors.WhiteSmoke)
            };

            scroll_viewer.Content = text_block;

            var text_box = new TextBox()
            {
                FontFamily = new FontFamily("Lucida Console"),
                Background = new SolidColorBrush(Color.FromRgb(1, 36, 86)),
                Foreground = new SolidColorBrush(Colors.WhiteSmoke)
            }.SetDock(Dock.Bottom);


            var runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());

            runspace.Open();

            void show_current_directory()
            {
                var ps = PowerShell.Create();

                ps.Runspace = runspace;

                var elts = ps.AddCommand("Get-Location").Invoke();

                if (elts.Count > 0)
                {
                    text_block.Inlines.Add(
                        new Label()
                    {
                        Content    = elts.First().ToString(),
                        Foreground = new SolidColorBrush(Colors.Yellow)
                    });

                    text_block.Inlines.Add(new LineBreak());
                }

                scroll_viewer.ScrollToBottom();
            }

            show_current_directory();

            text_box.KeyDown += (sender, event_args) =>
            {
                if (event_args.Key == Key.Return)
                {
                    var ps = PowerShell.Create();

                    ps.Runspace = runspace;

                    var result = ps.AddScript(text_box.Text).Invoke();

                    if (ps.HadErrors)
                    {
                        foreach (var elt in ps.Streams.Error)
                        {
                            text_block.Inlines.Add(new Label()
                            {
                                Content = elt.ToString(), Foreground = new SolidColorBrush(Colors.Red)
                            });

                            text_block.Inlines.Add(new LineBreak());
                        }
                    }
                    else
                    {
                        try
                        {
                            foreach (var elt in result)
                            {
                                if (elt.BaseObject is DirectoryInfo info)
                                {
                                    text_block.Inlines.Add(
                                        new Button()
                                    {
                                        Content     = info.Name,
                                        ContextMenu = new ContextMenu().AddItems(new MenuItem()
                                        {
                                            Header = "Explorer"
                                        }.AddClick((s, e) => System.Diagnostics.Process.Start(info.FullName)))
                                    }
                                        .AddClick((s, e) =>
                                    {
                                        var ps_ = PowerShell.Create();

                                        ps_.Runspace = runspace;

                                        ps_.AddScript(String.Format("cd '{0}'", info.FullName)).Invoke();

                                        show_current_directory();
                                    }));

                                    text_block.Inlines.Add(new LineBreak());
                                }
                                else if (elt.BaseObject is FileInfo file_info && (file_info.Extension == ".jpg" || file_info.Extension == ".png"))
                                {
                                    text_block.Inlines.Add(
                                        new Image()
                                    {
                                        Source    = new BitmapImage(new Uri(file_info.FullName)),
                                        MaxHeight = 100,
                                        MaxWidth  = 100
                                    });

                                    text_block.Inlines.Add(file_info.Name);

                                    text_block.Inlines.Add(new LineBreak());
                                }
                                else if (elt.BaseObject is System.Diagnostics.Process process)
                                {
                                    text_block.Inlines.Add(
                                        new Button()
                                    {
                                        Content     = process.ProcessName,
                                        ContextMenu = new ContextMenu().AddItems(new MenuItem()
                                        {
                                            Header = "Stop Process"
                                        }.AddClick((s, e) => process.Kill()))
                                    }
                                        .AddClick((s, e) => { }));

                                    text_block.Inlines.Add(new LineBreak());
                                }
                                else if (elt.BaseObject is System.ServiceProcess.ServiceController service_controller)
                                {
                                    text_block.Inlines.Add(
                                        new Button()
                                    {
                                        Content     = String.Format("{0} ({1})", service_controller.DisplayName, service_controller.Status.ToString()),
                                        ContextMenu = new ContextMenu().AddItems(
                                            new MenuItem()
                                        {
                                            Header = "Start Service"
                                        }.AddClick((s, e) => service_controller.Start()),
                                            new MenuItem()
                                        {
                                            Header = "Stop Service"
                                        }.AddClick((s, e) => service_controller.Stop()),
                                            new MenuItem()
                                        {
                                            Header = "Pause Service"
                                        }.AddClick((s, e) => service_controller.Pause()))
                                    }
                                        .AddClick((s, e) => { }));

                                    text_block.Inlines.Add(new LineBreak());
                                }
                                else
                                {
                                    var str = elt.ToString();

                                    text_block.Inlines.Add(str);

                                    text_block.Inlines.Add(new LineBreak());
                                }
                            }
                        }
Esempio n. 5
0
        static public int CheckUpdates(bool quiet = true, bool forceFetch = false)
        {
#if DEBUG
            int retCode = -1;
            using (var powerShell = PowerShell.Create())
            {
                powerShell.AddScript(string.Format(@"Set-Location {0}", Addin.SourceCodePath));
                powerShell.AddScript(@"git rev-parse --absolute-git-dir");
                var gitdir = powerShell.Invoke();
                if (powerShell.HadErrors)
                {
                    return(-1);
                }

                powerShell.AddScript(@"git rev-parse --abbrev-ref HEAD");
                var currentBranch = powerShell.Invoke();
                if (currentBranch.Count == 1)
                {
                    using
                    (
                        var taskDialog = new TaskDialog(MethodBase.GetCurrentMethod().DeclaringType.FullName)
                    {
                        Title = "Updates",
                        MainIcon = TaskDialogIcons.IconInformation,
                        TitleAutoPrefix = true,
                        AllowCancellation = true,
                        FooterText = Addin.SourceCodePath
                    }
                    )
                    {
                        // In quiet mode fetch just once per hour.
                        // if not in quiet mode forceFetch it's OK since the TaskDialog will stop execution for some time.
                        {
                            powerShell.Streams.Error.Clear();
                            string gitPath = Path.GetFullPath(Path.Combine(gitdir[0].ToString(), "FETCH_HEAD"));

                            if ((!quiet && forceFetch) || (DateTime.UtcNow - File.GetLastWriteTimeUtc(gitPath)).Hours > 0)
                            {
                                powerShell.AddScript(@"git fetch");
                                powerShell.Invoke();
                            }
                        }

                        if (forceFetch && powerShell.HadErrors)
                        {
                            taskDialog.MainIcon        = TaskDialogIcons.IconError;
                            taskDialog.MainInstruction = "Failed to fetch changes from the repository";

                            foreach (var f in powerShell.Streams.Error)
                            {
                                var line = f.ToString();
                                taskDialog.ExpandedContent += line + "\n";
                            }
                        }
                        else
                        {
                            powerShell.AddScript(string.Format(@"git log HEAD..origin/{0} --oneline .", currentBranch[0].ToString()));
                            var results = powerShell.Invoke();

                            retCode = results.Count;
                            if (retCode == 0)
                            {
                                taskDialog.MainInstruction = "You are up to date!!";
                            }
                            else
                            {
                                taskDialog.MainInstruction = string.Format("There are {0} changes in the repository", results.Count);

                                foreach (var result in results.Take(12))
                                {
                                    var line    = result.ToString();
                                    var comment = line.Substring(line.IndexOf(' ') + 1);
                                    taskDialog.ExpandedContent += "- " + comment + "\n";
                                }
                            }
                        }

                        if (!quiet)
                        {
                            taskDialog.Show();
                        }
                    }
                }
            }

            if (helpButton != null)
            {
                helpButton.LargeImage = retCode > 0 ? ImageBuilder.BuildLargeImage(retCode.ToString(), System.Drawing.Color.DarkRed) : ImageBuilder.BuildLargeImage("?");
                helpButton.ToolTip    = retCode > 0 ? string.Format("There are {0} changes in the repository", retCode) : string.Empty;
            }

            return(retCode);
#else
            Addin.IsExpired(quiet);

            if (helpButton != null)
            {
                helpButton.LargeImage = Addin.DaysUntilExpiration <= 15 ? ImageBuilder.BuildLargeImage(Addin.DaysUntilExpiration.ToString(), System.Drawing.Color.DarkRed) : ImageBuilder.BuildLargeImage("?");
                helpButton.ToolTip    = Addin.DaysUntilExpiration > 1 ? string.Format("This WIP build expires in {0} days", Addin.DaysUntilExpiration) : "This WIP build has expired";
            }

            return((Addin.DaysUntilExpiration < 1) ? 1 : 0);
#endif
        }
Esempio n. 6
0
 private void startScript()
 {
     ps = PowerShell.Create();
     ps.AddScript(textFromPsFile).Invoke();
 }
Esempio n. 7
0
        /// <summary>
        /// New job.
        /// </summary>
        /// <remarks>
        /// Keep seconds for UI-less jobs: 0 ~ hidden mode, in this case a job creates UI on errors, as it is not attended.
        /// Other UI-less jobs are completely owned creators.
        /// </remarks>
        internal Job(JobCommand command, object parameters, string name, bool ui, int keepSeconds)
        {
            JobCommand  = command;
            Parameters  = parameters;
            Name        = name;
            KeepSeconds = keepSeconds;

            // create/open runspace
            //! *) Do not catch, if we fail, we fail and there is nothing to repair yet (not open)
            //! *) Use existing configuration, it is faster! Most of *-Far* cmdlets should not be used,
            //! but some of them can be used, e.g. Update-FarDescription; also we want to use ETS types,
            //! e.g. FarDescription property.
            if (ui)
            {
                JobUI    = new JobUI();
                Runspace = RunspaceFactory.CreateRunspace(new FarHost(JobUI), Runspace.DefaultRunspace.InitialSessionState);
            }
            else
            {
                //! DefaultHost is created internally. Perhaps it is reasonable to live with it, not with a custom host.
                Runspace = RunspaceFactory.CreateRunspace(Runspace.DefaultRunspace.InitialSessionState);
            }
            Runspace.Open();

            // new shell with the command
            PowerShell          = PowerShell.Create();
            PowerShell.Runspace = Runspace;
            JobCommand.Add(PowerShell);

            // add command parameters
            if (parameters != null)
            {
                IDictionary namedParameters = parameters as IDictionary;
                IList       argumentList;
                if (namedParameters != null)
                {
                    PowerShell.AddParameters(namedParameters);
                }
                else if ((argumentList = parameters as IList) != null)
                {
                    PowerShell.AddParameters(argumentList);
                }
                else
                {
                    PowerShell.AddParameters(new object[] { parameters });
                }
            }

            // UI: Write all output, including errors.
            if (JobUI != null)
            {
                PowerShell.Commands.AddCommand(A.OutHostCommand);
            }
            // Hidden: Write output to "Out-Null" to avoid memory use.
            else if (keepSeconds <= 0)
            {
                //! User can use his Out-Null
                PowerShell.AddCommand("Out-Null");
            }
            // Output: create it once: it is cumulative
            else
            {
                Output = new PSDataCollection <PSObject>();
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Determine what kind of version bump should be applied to the common
        /// code library. We want to ensure that there were no breaking changes
        /// made to the common code to preserve backwards-compatibility.
        /// </summary>
        /// <returns>Version bump that should be applied to the common code library.</returns>
        public Version GetVersionBumpForCommonCode()
        {
            var outputModuleDirectory  = _fileHelper.OutputModuleDirectory;
            var galleryModuleDirectory = _fileHelper.GalleryModuleDirectory;

            Console.WriteLine("Saving Az.Accounts from the PowerShell Gallery to check common code changes. This will take a few seconds.");
            Version versionBump = Version.PATCH;
            var     issueLogger = _logger.CreateLogger <BreakingChangeIssue>("BreakingChangeIssues.csv");
            IEnumerable <string> commonAssemblies = null;

            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.AddScript("Save-Module -Name Az.Accounts -Repository PSGallery -Path " + outputModuleDirectory);
                var cmdletResult = powershell.Invoke();
            }

            var galleryModuleVersionDirectory = _fileHelper.GalleryModuleVersionDirectory;

            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.AddScript("$metadata = Test-ModuleManifest -Path " + Path.Combine(galleryModuleVersionDirectory, "Az.Accounts.psd1") + ";$metadata.RequiredAssemblies");
                var cmdletResult = powershell.Invoke();
                commonAssemblies = cmdletResult.Select(c => c.ToString().Substring(2)).Where(s => Regex.IsMatch(s, "Microsoft.*.Commands.*"));
            }

            try
            {
                foreach (var commonAssembly in commonAssemblies)
                {
                    var fullAssemblyPath = Path.Combine(outputModuleDirectory, commonAssembly);
                    var assemblyName     = Path.GetFileName(commonAssembly);
                    var oldAssemblyPath  = Directory.GetFiles(galleryModuleDirectory, assemblyName, SearchOption.AllDirectories).FirstOrDefault();
                    if (oldAssemblyPath == null)
                    {
                        throw new Exception("Could not find assembly " + assemblyName + " in the folder saved from the PowerShell Gallery for Az.Accounts.");
                    }

                    var oldAssembly = Assembly.LoadFrom(oldAssemblyPath);
                    CmdletLoader.ModuleMetadata = new ModuleMetadata();
                    var oldTypeMetadataDictionary = CmdletLoader.ModuleMetadata.TypeDictionary;
                    foreach (var oldType in oldAssembly.GetTypes())
                    {
                        if (oldType.Namespace == null)
                        {
                            // Sealed / private type
                            continue;
                        }

                        if (oldType.FullName != null && oldType.FullName.Contains("+"))
                        {
                            oldTypeMetadataDictionary[oldType.ToString()] = new TypeMetadata()
                            {
                                Name = oldType.ToString()
                            };
                        }

                        if (!oldTypeMetadataDictionary.ContainsKey(oldType.ToString()))
                        {
                            var oldTypeMetadata = new TypeMetadata(oldType);
                            oldTypeMetadataDictionary[oldType.ToString()] = oldTypeMetadata;
                        }
                    }

                    var newAssembly = Assembly.LoadFrom(fullAssemblyPath);
                    CmdletLoader.ModuleMetadata = new ModuleMetadata();
                    var newTypeMetadataDictionary = CmdletLoader.ModuleMetadata.TypeDictionary;
                    foreach (var newType in newAssembly.GetTypes())
                    {
                        if (newType.Namespace == null)
                        {
                            // Sealed / private type
                            continue;
                        }

                        if (newType.FullName != null && newType.FullName.Contains("+"))
                        {
                            newTypeMetadataDictionary[newType.ToString()] = new TypeMetadata()
                            {
                                Name = newType.ToString()
                            };
                        }

                        if (!newTypeMetadataDictionary.ContainsKey(newType.ToString()))
                        {
                            var newTypeMetadata = new TypeMetadata(newType);
                            newTypeMetadataDictionary[newType.ToString()] = newTypeMetadata;
                        }
                    }

                    issueLogger.Decorator.AddDecorator(a => a.AssemblyFileName = Path.GetFileName(commonAssembly), "AssemblyFileName");
                    CheckBreakingChangesInTypes(oldTypeMetadataDictionary, newTypeMetadataDictionary, issueLogger);
                    if (issueLogger.Records.Any())
                    {
                        return(Version.MAJOR);
                    }
                    else
                    {
                        foreach (var type in oldTypeMetadataDictionary.Keys)
                        {
                            if (!newTypeMetadataDictionary.ContainsKey(type))
                            {
                                continue;
                            }

                            var oldTypeMetadata = oldTypeMetadataDictionary[type];
                            var newTypeMetadata = newTypeMetadataDictionary[type];
                            if (!oldTypeMetadata.Equals(newTypeMetadata))
                            {
                                versionBump = Version.MINOR;
                            }
                        }

                        if (oldTypeMetadataDictionary.Keys.Count != newTypeMetadataDictionary.Keys.Count)
                        {
                            versionBump = Version.MINOR;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                var directories = Directory.GetDirectories(outputModuleDirectory, "Az.Accounts", SearchOption.TopDirectoryOnly);
                foreach (var directory in directories)
                {
                    try
                    {
                        Directory.Delete(directory, true);
                    }
                    catch (Exception ex)
                    {
                        var blank = ex.Message;
                    }
                }
            }

            Console.WriteLine("Found " + versionBump + " version bump for common code changes.");
            return(versionBump);
        }
Esempio n. 9
0
        /// <summary>
        /// Determine what version bump should be applied to a module version.
        /// This will compare the cmdlet assemblies in the output (built) module manifest with
        /// the corresponding deserialized module metadata from the JSON file.
        /// </summary>
        /// <param name="serialize">Whether or not the module metadata should be serialized.</param>
        /// <returns>Version enum representing the version bump to be applied.</returns>
        public Version GetVersionBumpUsingSerialized(bool serialize = true)
        {
            var outputModuleManifestPath   = _fileHelper.OutputModuleManifestPath;
            var outputModuleDirectory      = _fileHelper.OutputModuleDirectory;
            var outputDirectories          = _fileHelper.OutputDirectories;
            var serializedCmdletsDirectory = _fileHelper.SerializedCmdletsDirectory;
            var moduleName = _fileHelper.ModuleName;
            IEnumerable <string> nestedModules = null;

            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.AddScript("(Test-ModuleManifest -Path " + outputModuleManifestPath + ").NestedModules");
                var cmdletResult = powershell.Invoke();
                nestedModules = cmdletResult.Select(c => c.ToString() + ".dll");
            }

            Version versionBump = Version.PATCH;

            if (nestedModules.Any())
            {
                var           tempVersionBump = Version.PATCH;
                var           issueLogger     = _logger.CreateLogger <BreakingChangeIssue>("BreakingChangeIssues.csv");
                List <string> requiredModules = null;
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.AddScript("(Test-ModuleManifest -Path " + outputModuleManifestPath + ").RequiredModules");
                    var cmdletResult = powershell.Invoke();
                    requiredModules = cmdletResult.Select(c => c.ToString())
                                      .Join(outputDirectories,
                                            module => 1,
                                            directory => 1,
                                            (module, directory) => Path.Combine(directory, module))
                                      .Where(f => Directory.Exists(f))
                                      .ToList();
                }

                requiredModules.Add(outputModuleDirectory);
                foreach (var nestedModule in nestedModules)
                {
                    var assemblyPath         = Directory.GetFiles(outputModuleDirectory, nestedModule, SearchOption.AllDirectories).FirstOrDefault();
                    var proxy                = new CmdletLoader();
                    var newModuleMetadata    = proxy.GetModuleMetadata(assemblyPath, requiredModules);
                    var serializedCmdletName = nestedModule + ".json";
                    var serializedCmdletFile = Directory.GetFiles(serializedCmdletsDirectory, serializedCmdletName).FirstOrDefault();
                    if (serializedCmdletFile == null)
                    {
                        var currentColor = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine($"Warning: {nestedModule} does not have a previously serialized cmdlet for comparison.");
                        Console.ForegroundColor = currentColor;
                        var newCmdletFile = Path.Join(serializedCmdletsDirectory, serializedCmdletName);
                        SerializeCmdlets(newCmdletFile, newModuleMetadata);
                        continue;
                    }
                    var oldModuleMetadata = DeserializeCmdlets(serializedCmdletFile);
                    CmdletLoader.ModuleMetadata = oldModuleMetadata;
                    issueLogger.Decorator.AddDecorator(a => a.AssemblyFileName = assemblyPath, "AssemblyFileName");
                    CheckBreakingChangesInModules(oldModuleMetadata, newModuleMetadata, issueLogger);
                    if (issueLogger.Records.Any())
                    {
                        tempVersionBump = Version.MAJOR;
                    }
                    else if (!oldModuleMetadata.Equals(newModuleMetadata))
                    {
                        tempVersionBump = Version.MINOR;
                    }

                    if (tempVersionBump != Version.PATCH && serialize)
                    {
                        SerializeCmdlets(serializedCmdletFile, newModuleMetadata);
                    }

                    if (tempVersionBump == Version.MAJOR)
                    {
                        versionBump = Version.MAJOR;
                    }
                    else if (tempVersionBump == Version.MINOR && versionBump == Version.PATCH)
                    {
                        versionBump = Version.MINOR;
                    }
                }
            }
            else
            {
                return(Version.PATCH);
            }

            return(versionBump);
        }
Esempio n. 10
0
        protected override void ProcessRecord()
        {
            Guid runspId;
            var  runsp = PowerShell.Create(RunspaceMode.CurrentRunspace);

            runspId = runsp.Runspace.InstanceId;
            var con = (Connection)TokenCollection.Get(runspId);


            if (con == null)
            {
                throw new ArgumentException("No Active Connection");
            }

            if (string.IsNullOrEmpty(con.AccessToken))
            {
                throw new ArgumentException("No Valid Connection");
            }

            TenantService tenantService = new TenantService(con);



            try
            {
                Task <Result <List <Tenant> > > callTask = Task.Run(() => tenantService.GetByPlatformAsync(PlatformId));

                callTask.Wait();

                if (callTask.Result.Object != null)
                {
                    if (callTask.Result.Object.Count == 0)
                    {
                        Console.WriteLine("No Tenant existing");
                    }
                    else if (callTask.Result.Object.Count == 1)
                    {
                        tenant       = callTask.Result.Object.First();
                        con.TenantId = tenant.Id;


                        WriteObject(new ConnectionResult {
                            UserName = con.UserName, ApiUrl = con.ApiUrl, LogonUrl = con.LogonUrl, TenantId = con.TenantId
                        });
                    }
                    else
                    {
                        if (callTask.Result.Object.Any(x => x.Id == Id))
                        {
                            tenant       = callTask.Result.Object.First(x => x.Id == Id);
                            con.TenantId = tenant.Id;


                            WriteObject(new ConnectionResult {
                                UserName = con.UserName, ApiUrl = con.ApiUrl, LogonUrl = con.LogonUrl, TenantId = con.TenantId
                            });
                        }
                        else
                        {
                            Console.WriteLine("As multiple Tenant exists please Set Tenant focus.");

                            WriteObject(callTask.Result.Object);
                        }
                    }


                    using (runsp = PowerShell.Create(RunspaceMode.CurrentRunspace))
                    {
                        runspId = runsp.Runspace.InstanceId;
                        TokenCollection.Replace(runspId, con);
                    }
                }
                else if (callTask.Result.Error != null)
                {
                    throw new RemoteException("Conflict Error: " + callTask.Result.Error.ErrorType + "\r\n" + callTask.Result.Error.FaultyValues);
                }
                else
                {
                    throw new RemoteException("API returns: " + callTask.Result.Code.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }
Esempio n. 11
0
        public static void RunPSFile(string script)
        {
            PowerShell ps = PowerShell.Create();

            ps.AddScript(script).Invoke();
        }
Esempio n. 12
0
        public static List <AppDetail> GetAllAppNames(bool onlyDevApps)
        {
            var result = new List <AppDetail>();

            using (var ps = PowerShell.Create())
            {
                ps.AddScript("Get-AppxPackage");

                Collection <PSObject> psOutput = ps.Invoke();

                if (ps.Streams.Error.Count > 0)
                {
                    // error records were written to the error stream.
                    // do something with the items found.
                }

                // loop through each output object item
                foreach (PSObject outputItem in psOutput)
                {
                    // if null object was dumped to the pipeline during the script then a null
                    // object may be present here. check for null to prevent potential NRE.
                    if (outputItem != null)
                    {
                        var isDevMode = outputItem.Properties.Any(p => p.Name == "IsDevelopmentMode") &&
                                        (bool)outputItem.Properties["IsDevelopmentMode"].Value;

                        string displayName     = string.Empty;
                        string officialName    = string.Empty;
                        string installLocation = null;

                        foreach (var outputItemMember in outputItem.Members)
                        {
                            if (outputItemMember.Name == "InstallLocation")
                            {
                                try
                                {
                                    installLocation = outputItemMember.Value.ToString();
                                    Debug.WriteLine(installLocation);
                                }
                                catch (Exception e)
                                {
                                    Debug.WriteLine(e);
                                }

                                break;
                            }
                        }

                        if (installLocation != null && !installLocation.Contains("ShadowCache") && Directory.Exists(installLocation))
                        {
                            var manifestPath = Path.Combine(installLocation, "AppxManifest.xml");

                            if (File.Exists(manifestPath))
                            {
                                var manifest = File.ReadAllText(manifestPath);

                                var xml = new XmlDocument();
                                xml.LoadXml(manifest);

                                displayName  = xml.DocumentElement?.GetElementsByTagName("DisplayName")[0].InnerText ?? "*Unknown*";
                                officialName = outputItem.Properties["Name"].Value.ToString();

                                Debug.WriteLine(displayName);
                            }
                        }
                        else
                        {
                            displayName  = ((PSProperty)outputItem.Members["Name"]).Value.ToString();
                            officialName = ((PSProperty)outputItem.Members["PackageFullName"]).Value.ToString();
                        }

                        bool addToOutput;

                        if (onlyDevApps)
                        {
                            if (isDevMode && !string.IsNullOrWhiteSpace(installLocation) && !installLocation.Contains("ShadowCache"))
                            {
                                addToOutput = true;
                            }
                            else
                            {
                                addToOutput = false;
                            }
                        }
                        else
                        {
                            addToOutput = true;
                        }

                        if (addToOutput)
                        {
                            result.Add(new AppDetail(displayName, officialName, installLocation));
                        }
                    }
                }
            }

            return(result.OrderBy(a => a.DisplayName).ToList());
        }
        private void Initialize(HostDetails hostDetails, Runspace initialRunspace)
        {
            Validate.IsNotNull("initialRunspace", initialRunspace);

            this.SessionState = PowerShellContextState.NotStarted;

            this.initialRunspace = initialRunspace;
            this.currentRunspace = initialRunspace;

            this.currentRunspace.Debugger.BreakpointUpdated += OnBreakpointUpdated;
            this.currentRunspace.Debugger.DebuggerStop      += OnDebuggerStop;

            this.powerShell          = PowerShell.Create();
            this.powerShell.Runspace = this.currentRunspace;

            // TODO: Should this be configurable?
            this.SetExecutionPolicy(ExecutionPolicy.RemoteSigned);

            // Get the PowerShell runtime version
            this.PowerShellVersion = GetPowerShellVersion();

            // Write out the PowerShell version for tracking purposes
            Logger.Write(
                LogLevel.Normal,
                string.Format(
                    "PowerShell runtime version: {0}",
                    this.PowerShellVersion));

            if (PowerShellVersion >= new Version(5, 0))
            {
                this.versionSpecificOperations = new PowerShell5Operations();
            }
            else if (PowerShellVersion.Major == 4)
            {
                this.versionSpecificOperations = new PowerShell4Operations();
            }
            else if (PowerShellVersion.Major == 3)
            {
                this.versionSpecificOperations = new PowerShell3Operations();
            }
            else
            {
                throw new NotSupportedException(
                          "This computer has an unsupported version of PowerShell installed: " +
                          PowerShellVersion.ToString());
            }

            // Configure the runspace's debugger
            this.versionSpecificOperations.ConfigureDebugger(
                this.currentRunspace);

            // Set the $profile variable in the runspace
            this.profilePaths =
                this.SetProfileVariableInCurrentRunspace(
                    hostDetails);

            // Now that initialization is complete we can watch for InvocationStateChanged
            this.powerShell.InvocationStateChanged += powerShell_InvocationStateChanged;

            this.SessionState = PowerShellContextState.Ready;

            // Now that the runspace is ready, enqueue it for first use
            RunspaceHandle runspaceHandle = new RunspaceHandle(this.currentRunspace, this);

            this.runspaceWaitQueue.EnqueueAsync(runspaceHandle).Wait();
        }
Esempio n. 14
0
        public static (Collection <PSObject>, Collection <ErrorRecord>) InvokeCommand(string computer, string argument, bool AsSystem = false, string auth = "ntlm", string scheme = "HTTP", bool display = true, bool AmsiBypass = false, bool delegWalk = false)
        {
            Collection <PSObject>    result = new Collection <PSObject>();
            Collection <ErrorRecord> error  = new Collection <ErrorRecord>();
            var remoteComputer = new Uri(String.Format("{0}://{1}:5985/wsman", scheme, computer));
            var connection     = new WSManConnectionInfo(remoteComputer);

            connection.SkipRevocationCheck = true;
            connection.SkipCNCheck         = true;
            connection.SkipCACheck         = true;

            if (auth == "kerberos")
            {
                connection.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
            }
            else
            {
                connection.AuthenticationMechanism = AuthenticationMechanism.Negotiate;
            }
            if (AsSystem)
            {
                argument = PsFunction.RunAsSystem(argument);
            }
            if (delegWalk)
            {
                argument = PsFunction.RunDelegationWalk(argument);
            }
            try
            {
                using (Runspace runspace = RunspaceFactory.CreateRunspace(connection))
                {
                    runspace.Open();
                    using (var powershell = PowerShell.Create())
                    {
                        powershell.Runspace = runspace;
                        if (AmsiBypass)
                        {
                            string amsi = AmsiFail.GetPayload();
                            powershell.AddScript(amsi);
                            //powershell.AddScript("[Ref].Assembly.GetType('System.Management.Automation.' + ([char]65) + 'm' + 's' + ($PSHOmE[4]) + 'Utils').GetField('a' + 'm' + 's' + 'i' + 'InitFailed','NonPublic,Static').SetValue(0,[bool]1)");
                        }
                        powershell.AddScript(argument);
                        result = powershell.Invoke();
                        error  = powershell.Streams.Error.ReadAll();
                    }
                }
            }
            catch (System.Management.Automation.Remoting.PSRemotingTransportException e) // Connecting to remote server 192.168.1.10 failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic
            {
                Console.WriteLine(String.Format("[-] Access is Denied on {0}", connection.ComputerName));
                throw e;
            }
            catch (System.Management.Automation.RemoteException e) //The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode
            {
                if (e.Message.Contains("The syntax is not supported by this runspace"))
                {
                    Console.WriteLine(String.Format("[-] Jea Endpoint Detected on {0}", connection.ComputerName));
                }
                else
                {
                    Console.WriteLine(e.Message);
                }
                throw e;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw e;
            }
            if (display)
            {
                foreach (var err in error)
                {
                    Console.WriteLine(err);
                }
            }
            return(result, error);
        }
Esempio n. 15
0
        public ActionResult preFlightChecks()
        {
            var powerShell         = PowerShell.Create();
            var preReqInlineScript = "" +
                                     "$checksPassed = $null;" +
                                     "$checkADPowershell = (Get-Command Test-ADServiceAccount).ModuleName;" +
                                     "$iisDocRoot = \"C:\\inetpub\\wwwroot\\\";" +
                                     "$powerShellScriptRoot = \"C:\\inetpub\\wwwroot\\Powershell\\\";" +
                                     "If ($checkADPowershell -eq 'ActiveDirectory') " +
                                     "{Write-Output \"[PASS]  Active Directory RSAT Powershell Module Installed`n\"; " +
                                     "If ($checksPassed -eq $null) {$checksPassed = $TRUE;};} " +
                                     "Else " +
                                     "{Write-Output \"[FAIL]  Active Directory RSAT Powershell Module Missing\";" +
                                     "Write-Output \"        Please add dependency in Dockerfile or install the tools interactively on the Container`n\";" +
                                     "Write-Output \"        Dockerfile: RUN Add-WindowsFeature RSAT-AD-Powershell\";" +
                                     "If ($checksPassed -eq $null) {$checksPassed = $FALSE;}};" +
                                     "$checkIISDocRoot = Test-Path $iisDocRoot;" +
                                     "If ($checkIISDocRoot -eq $TRUE)" +
                                     "{Write-Output \"[PASS]  IIS Document Root found\";" +
                                     "Write-Output \"        $iisDocRoot`n\";" +
                                     "If ($checksPassed -eq $TRUE) {$checksPassed = $TRUE;}}" +
                                     "Else " +
                                     "{Write-Output \"[FAIL]  IIS Document Root is not correct\";" +
                                     "Write-Output \"        Please ensure that all WebApp Files are in the $iisDocRoot Folder`n\";" +
                                     "$checksPassed = $FALSE;};" +
                                     "$checkPowershellRoot = Test-Path $powerShellScriptRoot;" +
                                     "If ($checkPowershellRoot -eq $TRUE) " +
                                     "{Write-Output \"[PASS]  Powershell Scripts Folder found\";" +
                                     "Write-Output \"        $powerShellScriptRoot`n\";" +
                                     "If ($checksPassed -eq $TRUE) {$checksPassed = $TRUE;};} " +
                                     "Else " +
                                     "{Write-Output \"[FAIL]  Powershell Scripts Folder not found\";" +
                                     "Write-Output \"        Please ensure that all Powershell Scripts are in the $powerShellScriptRoot Folder`n\";" +
                                     "$checksPassed = $FALSE;};" +
                                     "$checkcontainerPS = Test-Path \"$powerShellScriptRoot\\containerDiag.ps1\";" +
                                     "If ($checkcontainerPS -eq $TRUE) " +
                                     "{Write-Output \"[PASS]  Container Diagnostic Script found\";" +
                                     "Write-Output \"        $powerShellScriptRoot\\containerDiag.ps1`n\";" +
                                     "If ($checksPassed -eq $TRUE) {$checksPassed = $TRUE;};}" +
                                     "Else " +
                                     "{Write-Output \"[FAIL]  Container Diagnostic Script not found\";" +
                                     "Write-Output \"        Please ensure that all Powershell Scripts are in the $powerShellScriptRoot Folder`n\";" +
                                     "$checksPassed = $FALSE;};" +
                                     "$checkdomainPS = Test-Path \"$powerShellScriptRoot\\domainDiag.ps1\";" +
                                     "If ($checkdomainPS -eq $TRUE) " +
                                     "{Write-Output \"[PASS]  Domain Diagnostic Script found\";" +
                                     "Write-Output \"        $powerShellScriptRoot\\domainDiag.ps1`n\";" +
                                     "If ($checksPassed -eq $TRUE) {$checksPassed = $TRUE;};}" +
                                     "Else" +
                                     "{Write-Output \"[FAIL]  Domain Diagnostic Script not found\";" +
                                     "Write-Output \"        Please ensure that all Powershell Scripts are in the $powerShellScriptRoot Folder`n\";" +
                                     "$checksPassed = $FALSE;};" +
                                     "If ($checksPassed -eq $TRUE) " +
                                     "{Write-Output \"[RES]   Result: PASS   All checks passed! Please proceed to run the different tests.\";}" +
                                     "Else" +
                                     "{Write-Output \"[RES]   Result: FAIL   One of more prerequisite checks failed. Please fix the issues and re-run the checks before proceeding\";}";

            powerShell.Commands.AddScript(preReqInlineScript);
            var psOutput = powerShell.Invoke();

            if (psOutput.Count > 0)
            {
                var strBuild = new StringBuilder();

                foreach (var psObject in psOutput)
                {
                    strBuild.Append(psObject.BaseObject.ToString() + "\r\n");
                }
                return(Content(strBuild.ToString()));
            }

            return(Json(""));
        }
Esempio n. 16
0
        /// <summary>
        /// Determine which version bump should be applied to a module version.
        /// This will compare the cmdlet assemblies in the output (built) module manifest with
        /// the cmdlet assemblies in the saved gallery folder.
        /// </summary>
        /// <returns>Version enum representing the version bump to be applied.</returns>
        public Version GetVersionBumpUsingGallery()
        {
            var outputModuleManifestPath      = _fileHelper.OutputModuleManifestPath;
            var outputModuleDirectory         = _fileHelper.OutputModuleDirectory;
            var outputDirectories             = _fileHelper.OutputDirectories;
            var serializedCmdletsDirectory    = _fileHelper.SerializedCmdletsDirectory;
            var galleryModuleVersionDirectory = _fileHelper.GalleryModuleVersionDirectory;
            var moduleName = _fileHelper.ModuleName;
            IEnumerable <string> nestedModules = null;

            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.AddScript("(Test-ModuleManifest -Path " + outputModuleManifestPath + ").NestedModules");
                var cmdletResult = powershell.Invoke();
                nestedModules = cmdletResult.Select(c => c.ToString() + ".dll");
            }

            Version versionBump = Version.PATCH;

            if (nestedModules.Any())
            {
                var           tempVersionBump        = Version.PATCH;
                var           issueLogger            = _logger.CreateLogger <BreakingChangeIssue>("BreakingChangeIssues.csv");
                List <string> requiredModules        = null;
                List <string> galleryRequiredModules = null;
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.AddScript("(Test-ModuleManifest -Path " + outputModuleManifestPath + ").RequiredModules");
                    var cmdletResult = powershell.Invoke();
                    requiredModules = cmdletResult.Select(c => c.ToString())
                                      .Join(outputDirectories,
                                            module => 1,
                                            directory => 1,
                                            (module, directory) => Path.Combine(directory, module))
                                      .Where(f => Directory.Exists(f))
                                      .ToList();
                    galleryRequiredModules = cmdletResult.Select(c => c.ToString())
                                             .Select(f => Directory.GetDirectories(outputModuleDirectory, f).FirstOrDefault())
                                             .Select(f => Directory.GetDirectories(f).FirstOrDefault())
                                             .ToList();
                }

                requiredModules.Add(outputModuleDirectory);
                galleryRequiredModules.Add(galleryModuleVersionDirectory);
                foreach (var nestedModule in nestedModules)
                {
                    var assemblyPath      = Directory.GetFiles(galleryModuleVersionDirectory, nestedModule).FirstOrDefault();
                    var proxy             = new CmdletLoader();
                    var oldModuleMetadata = proxy.GetModuleMetadata(assemblyPath, galleryRequiredModules);
                    assemblyPath = Directory.GetFiles(outputModuleDirectory, nestedModule).FirstOrDefault();
                    proxy        = new CmdletLoader();
                    var newModuleMetadata = proxy.GetModuleMetadata(assemblyPath, requiredModules);
                    CmdletLoader.ModuleMetadata = oldModuleMetadata;
                    issueLogger.Decorator.AddDecorator(a => a.AssemblyFileName = assemblyPath, "AssemblyFileName");
                    CheckBreakingChangesInModules(oldModuleMetadata, newModuleMetadata, issueLogger);
                    if (issueLogger.Records.Any())
                    {
                        tempVersionBump = Version.MAJOR;
                    }
                    else if (!oldModuleMetadata.Equals(newModuleMetadata))
                    {
                        tempVersionBump = Version.MINOR;
                    }

                    if (tempVersionBump == Version.MAJOR)
                    {
                        versionBump = Version.MAJOR;
                    }
                    else if (tempVersionBump == Version.MINOR && versionBump == Version.PATCH)
                    {
                        versionBump = Version.MINOR;
                    }
                }
            }
            else
            {
                throw new NullReferenceException("No nested modules found for " + moduleName);
            }

            return(versionBump);
        }
Esempio n. 17
0
        public void Run(string fileName)
        {
            var start = DateTime.Now;

            //We're gonna need to grant some permissions...just for this process

            try
            {
                var psInst = PowerShell.Create();
                psInst.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted");
                psInst.Invoke();
                psInst.AddScript(fileName);


                var output = new PSDataCollection <PSObject>();
                psInst.Streams.Error.DataAdded += (sender, args) =>
                {
                    var psData = (PSDataCollection <ErrorRecord>)sender;

                    var results = psData.ReadAll();

                    foreach (var result in results)
                    {
                        AddError(result.ToString());
                    }
                };

                psInst.Streams.Warning.DataAdded += (sender, args) =>
                {
                    var psData = (PSDataCollection <WarningRecord>)sender;

                    var results = psData.ReadAll();

                    foreach (var result in results)
                    {
                        AddWarning(result.ToString());
                    }
                };

                psInst.Streams.Information.DataAdded += (sender, args) =>
                {
                    var psData = (PSDataCollection <InformationRecord>)sender;

                    var results = psData.ReadAll();

                    foreach (var result in results)
                    {
                        AddInfo(result.ToString());
                    }
                };

                psInst.Streams.Debug.DataAdded += (sender, args) =>
                {
                    var psData = (PSDataCollection <DebugRecord>)sender;

                    var results = psData.ReadAll();

                    foreach (var result in results)
                    {
                        AddDebug(result.ToString());
                    }
                };

                // Invoke the pipeline asynchronously.
                var asyncResult = psInst.BeginInvoke();

                while (!asyncResult.IsCompleted)
                {
                    Application.DoEvents();
                    Thread.Sleep(100);
                }


                TimeSpan elapsed = DateTime.Now.Subtract(start);

                MessageBox.Show($"Done executing in {elapsed.ToReadableString()}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error Running Script: {ex.Message}", "MERP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 18
0
        /// <summary>
        /// The entry point for the Posh Host application that runs the embedded script
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            // Ps1 file into the Assembly Resource
            Assembly currentAss = Assembly.GetExecutingAssembly();

            // Only for testing purpose - display the name of all resources
            foreach (string resName in currentAss.GetManifestResourceNames())
            {
                // Console.WriteLine("*** " + resName);
            }

            // Creating a new PowerShell Host for "executing" the script
            PoshHost poshHost = new PoshHost(new PoshHostApplication());

            poshHost.UI.RawUI.ForegroundColor = ConsoleColor.Green;

            using (Runspace runSpace = RunspaceFactory.CreateRunspace(poshHost))
            {
                runSpace.ApartmentState = System.Threading.ApartmentState.STA;
                runSpace.Open();
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.Runspace = runSpace;
                    Assembly curAssembly = Assembly.GetExecutingAssembly();
                    // remember, the ps1 file is compressed so a litte decompression is necessary
                    string ps1Script = TextCompress.DecompressStream(curAssembly.GetManifestResourceStream("<<resourcename>>"));
                    // Console.WriteLine(ps1Script);
                    powershell.AddScript(ps1Script);
                    string pattern = @"(\w+):(.+)";
                    for (int i = 0; i < args.Length; i++)
                    {
                        // Console.WriteLine("*** Arg Nr. {0}: {1}", i, args[i]);
                        if (Regex.IsMatch(args[i], pattern))
                        {
                            Match m = Regex.Match(args[i], pattern);
                            // Console.WriteLine("Arg-Name: {0}, Arg-Value: {1}", m.Groups[1].Value, m.Groups[2].Value);
                            powershell.AddParameter(m.Groups[1].Value, m.Groups[2].Value);
                        }
                        else
                        {
                            powershell.AddParameter(null, args[i]);
                        }
                    }
                    // Pipeline must be written directly to the host window
                    // the output will be text not objects :(
                    powershell.AddCommand("Out-Host");
                    // Collect errors
                    powershell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                    Collection <PSObject> results = powershell.Invoke();
                    if (results.Count > 0)
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        foreach (PSObject result in results)
                        {
                            Console.WriteLine("*** {0}", result.ToString());
                        }
                        Console.ForegroundColor = ConsoleColor.Green;
                    }
                }
            }
        }
Esempio n. 19
0
        private async Task <string> ReadLine(bool isCommandLine, CancellationToken cancellationToken)
        {
            string            inputBeforeCompletion = null;
            string            inputAfterCompletion  = null;
            CommandCompletion currentCompletion     = null;

            int historyIndex = -1;
            Collection <PSObject> currentHistory = null;

            StringBuilder inputLine = new StringBuilder();

            int initialCursorCol = Console.CursorLeft;
            int initialCursorRow = Console.CursorTop;

            int initialWindowLeft = Console.WindowLeft;
            int initialWindowTop  = Console.WindowTop;

            int currentCursorIndex = 0;

            Console.TreatControlCAsInput = true;

            try
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    ConsoleKeyInfo keyInfo = await ReadKeyAsync(cancellationToken);

                    // Do final position calculation after the key has been pressed
                    // because the window could have been resized before then
                    int promptStartCol = initialCursorCol;
                    int promptStartRow = initialCursorRow;
                    int consoleWidth   = Console.WindowWidth;

                    if ((int)keyInfo.Key == 3 ||
                        keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
                    {
                        throw new PipelineStoppedException();
                    }
                    else if (keyInfo.Key == ConsoleKey.Tab && isCommandLine)
                    {
                        if (currentCompletion == null)
                        {
                            inputBeforeCompletion = inputLine.ToString();
                            inputAfterCompletion  = null;

                            // TODO: This logic should be moved to AstOperations or similar!

                            if (this.powerShellContext.IsDebuggerStopped)
                            {
                                PSCommand command = new PSCommand();
                                command.AddCommand("TabExpansion2");
                                command.AddParameter("InputScript", inputBeforeCompletion);
                                command.AddParameter("CursorColumn", currentCursorIndex);
                                command.AddParameter("Options", null);

                                var results =
                                    await this.powerShellContext.ExecuteCommand <CommandCompletion>(command, false, false);

                                currentCompletion = results.FirstOrDefault();
                            }
                            else
                            {
                                using (RunspaceHandle runspaceHandle = await this.powerShellContext.GetRunspaceHandle())
                                    using (PowerShell powerShell = PowerShell.Create())
                                    {
                                        powerShell.Runspace = runspaceHandle.Runspace;
                                        currentCompletion   =
                                            CommandCompletion.CompleteInput(
                                                inputBeforeCompletion,
                                                currentCursorIndex,
                                                null,
                                                powerShell);

                                        if (currentCompletion.CompletionMatches.Count > 0)
                                        {
                                            int replacementEndIndex =
                                                currentCompletion.ReplacementIndex +
                                                currentCompletion.ReplacementLength;

                                            inputAfterCompletion =
                                                inputLine.ToString(
                                                    replacementEndIndex,
                                                    inputLine.Length - replacementEndIndex);
                                        }
                                        else
                                        {
                                            currentCompletion = null;
                                        }
                                    }
                            }
                        }

                        CompletionResult completion =
                            currentCompletion?.GetNextResult(
                                !keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift));

                        if (completion != null)
                        {
                            currentCursorIndex =
                                this.InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    $"{completion.CompletionText}{inputAfterCompletion}",
                                    currentCursorIndex,
                                    insertIndex: currentCompletion.ReplacementIndex,
                                    replaceLength: inputLine.Length - currentCompletion.ReplacementIndex,
                                    finalCursorIndex: currentCompletion.ReplacementIndex + completion.CompletionText.Length);
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.LeftArrow)
                    {
                        currentCompletion = null;

                        if (currentCursorIndex > 0)
                        {
                            currentCursorIndex =
                                this.MoveCursorToIndex(
                                    promptStartCol,
                                    promptStartRow,
                                    consoleWidth,
                                    currentCursorIndex - 1);
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.Home)
                    {
                        currentCompletion = null;

                        currentCursorIndex =
                            this.MoveCursorToIndex(
                                promptStartCol,
                                promptStartRow,
                                consoleWidth,
                                0);
                    }
                    else if (keyInfo.Key == ConsoleKey.RightArrow)
                    {
                        currentCompletion = null;

                        if (currentCursorIndex < inputLine.Length)
                        {
                            currentCursorIndex =
                                this.MoveCursorToIndex(
                                    promptStartCol,
                                    promptStartRow,
                                    consoleWidth,
                                    currentCursorIndex + 1);
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.End)
                    {
                        currentCompletion = null;

                        currentCursorIndex =
                            this.MoveCursorToIndex(
                                promptStartCol,
                                promptStartRow,
                                consoleWidth,
                                inputLine.Length);
                    }
                    else if (keyInfo.Key == ConsoleKey.UpArrow && isCommandLine)
                    {
                        currentCompletion = null;

                        // TODO: Ctrl+Up should allow navigation in multi-line input

                        if (currentHistory == null)
                        {
                            historyIndex = -1;

                            PSCommand command = new PSCommand();
                            command.AddCommand("Get-History");

                            currentHistory =
                                await this.powerShellContext.ExecuteCommand <PSObject>(
                                    command,
                                    false,
                                    false) as Collection <PSObject>;

                            if (currentHistory != null)
                            {
                                historyIndex = currentHistory.Count;
                            }
                        }

                        if (currentHistory != null && currentHistory.Count > 0 && historyIndex > 0)
                        {
                            historyIndex--;

                            currentCursorIndex =
                                this.InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    (string)currentHistory[historyIndex].Properties["CommandLine"].Value,
                                    currentCursorIndex,
                                    insertIndex: 0,
                                    replaceLength: inputLine.Length);
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.DownArrow && isCommandLine)
                    {
                        currentCompletion = null;

                        // The down arrow shouldn't cause history to be loaded,
                        // it's only for navigating an active history array

                        if (historyIndex > -1 && historyIndex < currentHistory.Count &&
                            currentHistory != null && currentHistory.Count > 0)
                        {
                            historyIndex++;

                            if (historyIndex < currentHistory.Count)
                            {
                                currentCursorIndex =
                                    this.InsertInput(
                                        inputLine,
                                        promptStartCol,
                                        promptStartRow,
                                        (string)currentHistory[historyIndex].Properties["CommandLine"].Value,
                                        currentCursorIndex,
                                        insertIndex: 0,
                                        replaceLength: inputLine.Length);
                            }
                            else if (historyIndex == currentHistory.Count)
                            {
                                currentCursorIndex =
                                    this.InsertInput(
                                        inputLine,
                                        promptStartCol,
                                        promptStartRow,
                                        string.Empty,
                                        currentCursorIndex,
                                        insertIndex: 0,
                                        replaceLength: inputLine.Length);
                            }
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.Escape)
                    {
                        currentCompletion = null;
                        historyIndex      = currentHistory != null ? currentHistory.Count : -1;

                        currentCursorIndex =
                            this.InsertInput(
                                inputLine,
                                promptStartCol,
                                promptStartRow,
                                string.Empty,
                                currentCursorIndex,
                                insertIndex: 0,
                                replaceLength: inputLine.Length);
                    }
                    else if (keyInfo.Key == ConsoleKey.Backspace)
                    {
                        currentCompletion = null;

                        if (currentCursorIndex > 0)
                        {
                            currentCursorIndex =
                                this.InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    string.Empty,
                                    currentCursorIndex,
                                    insertIndex: currentCursorIndex - 1,
                                    replaceLength: 1,
                                    finalCursorIndex: currentCursorIndex - 1);
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.Delete)
                    {
                        currentCompletion = null;

                        if (currentCursorIndex < inputLine.Length)
                        {
                            currentCursorIndex =
                                this.InsertInput(
                                    inputLine,
                                    promptStartCol,
                                    promptStartRow,
                                    string.Empty,
                                    currentCursorIndex,
                                    replaceLength: 1,
                                    finalCursorIndex: currentCursorIndex);
                        }
                    }
                    else if (keyInfo.Key == ConsoleKey.Enter)
                    {
                        string completedInput = inputLine.ToString();
                        currentCompletion = null;
                        currentHistory    = null;

                        //if ((keyInfo.Modifiers & ConsoleModifiers.Shift) == ConsoleModifiers.Shift)
                        //{
                        //    // TODO: Start a new line!
                        //    continue;
                        //}

                        Parser.ParseInput(
                            completedInput,
                            out Token[] tokens,
                            out ParseError[] parseErrors);
        /// <summary>
        /// 使用 microsoft/mssql-server-windows-developer 建立測試用的 SQL Server.
        /// </summary>
        /// <param name="databaseIp">The database ip.</param>
        /// <param name="containerId">The container identifier.</param>
        private static void CreateSqlServerContainerOnWindows(out string databaseIp,
                                                              out string containerId)
        {
            var runSpacePool = RunspaceFactory.CreateRunspacePool(1, 5);

            runSpacePool.Open();

            using (runSpacePool)
            {
                var powerShellCommands       = new List <PowerShell>();
                var powerShellCommandResults = new List <IAsyncResult>();

                // 1.先停止並移除之前所建立的測試資料庫 sql-server
                var powerShellInstance1 = PowerShell.Create();
                powerShellInstance1.RunspacePool = runSpacePool;
                powerShellInstance1.AddScript($"docker stop {ContainerId}");
                powerShellCommands.Add(powerShellInstance1);
                powerShellCommandResults.Add(powerShellInstance1.BeginInvoke());

                // 2.使用 microsoft/mssql-server-windows-express 建立測試用資料庫
                var powerShellInstance2 = PowerShell.Create();
                powerShellInstance2.RunspacePool = runSpacePool;
                powerShellInstance2.AddScript($"docker run --rm -d -e SA_PASSWORD=1q2w3e4r5t_ -e ACCEPT_EULA=Y -ti -p {Port}:1433 microsoft/mssql-server-windows-developer");
                powerShellCommands.Add(powerShellInstance2);
                powerShellCommandResults.Add(powerShellInstance2.BeginInvoke());

                int    i       = 0;
                string message = string.Empty;

                foreach (var powerShellCommand in powerShellCommands)
                {
                    PSDataCollection <PSObject> results = powerShellCommand.EndInvoke(powerShellCommandResults[i]);
                    foreach (var result in results)
                    {
                        if (result != null)
                        {
                            message = result.BaseObject.ToString();
                        }
                    }

                    if (i.Equals(1))
                    {
                        ContainerId = message;
                    }

                    i++;
                }
            }

            // 3. 使用 docker logs 指令,查看在 container 的 sql-server 是否已經準備好

            int  retryTimes = 60;
            bool ready      = false;

            for (int i = 0; i < retryTimes; i++)
            {
                var powerShellInstance = PowerShell.Create();
                powerShellInstance.AddScript($"docker logs {ContainerId}");
                var executeResults = powerShellInstance.Invoke();
                foreach (var psObject in executeResults)
                {
                    if (psObject != null)
                    {
                        var message = psObject.BaseObject.ToString();
                        if (message.Contains("VERBOSE: Started SQL Server"))
                        {
                            ready = true;
                        }
                    }
                }

                if (ready.Equals(false))
                {
                    Thread.Sleep(1000);
                }
                else
                {
                    Console.WriteLine($"wait {i} second");
                    break;
                }
            }

            // 4. 取得新建立 container 的 內部 ip
            string containerInsideIp = "";

            using (PowerShell powerShellinstance = PowerShell.Create())
            {
                powerShellinstance.AddScript($"docker exec {ContainerId} ipconfig | findstr IPv4");
                powerShellinstance.Invoke();

                var psOutput = powerShellinstance.Invoke();
                foreach (var outputItem in psOutput)
                {
                    if (string.IsNullOrWhiteSpace(outputItem?.BaseObject.ToString()))
                    {
                        continue;
                    }

                    var serverIp = outputItem.BaseObject.ToString();
                    containerInsideIp = serverIp.Split(':')[1].Trim();
                }
            }

            databaseIp  = string.IsNullOrWhiteSpace(containerInsideIp) ? "" : containerInsideIp;
            containerId = string.IsNullOrWhiteSpace(ContainerId) ? "" : ContainerId;
        }
 public Test()
 {
     disposed = false;
     ps       = PowerShell.Create();
 }
        /// <summary>
        /// 使用 microsoft/mssql-server-linux 建立測試用的 SQL Server.
        /// </summary>
        /// <param name="databaseIp">The database ip.</param>
        /// <param name="containerId">The container identifier.</param>
        private static void CreateSqlServerContainerOnLinux(out string databaseIp,
                                                            out string containerId)
        {
            var runSpacePool = RunspaceFactory.CreateRunspacePool(1, 5);

            runSpacePool.Open();

            using (runSpacePool)
            {
                var powerShellCommands       = new List <PowerShell>();
                var powerShellCommandResults = new List <IAsyncResult>();

                // 1.先停止並移除之前所建立的測試資料庫 sql-server
                var powerShellInstance1 = PowerShell.Create();
                powerShellInstance1.RunspacePool = runSpacePool;
                powerShellInstance1.AddScript($"docker stop {ContainerId}");
                powerShellCommands.Add(powerShellInstance1);
                powerShellCommandResults.Add(powerShellInstance1.BeginInvoke());

                // 2.使用 microsoft/sql-server-linux 建立測試資料庫 sql-server
                var powerShellInstance2 = PowerShell.Create();
                powerShellInstance2.RunspacePool = runSpacePool;
                powerShellInstance2.AddScript($"docker run --rm -d -e SA_PASSWORD=1q2w3e4r5t_ -e ACCEPT_EULA=Y -ti -p {Port}:1433 microsoft/mssql-server-linux");
                powerShellCommands.Add(powerShellInstance2);
                powerShellCommandResults.Add(powerShellInstance2.BeginInvoke());

                int    i       = 0;
                string message = string.Empty;

                foreach (var powerShellCommand in powerShellCommands)
                {
                    PSDataCollection <PSObject> results = powerShellCommand.EndInvoke(powerShellCommandResults[i]);
                    foreach (var result in results)
                    {
                        if (result != null)
                        {
                            message = result.BaseObject.ToString();
                        }
                    }

                    if (i.Equals(1))
                    {
                        ContainerId = message;
                    }
                    i++;
                }
            }

            // 3. 使用 docker logs 指令,查看在 container 的 sql-server 是否已經準備好

            int  retryTimes = 30;
            bool ready      = false;

            for (int i = 0; i < retryTimes; i++)
            {
                var powerShellInstance = PowerShell.Create();
                powerShellInstance.AddScript($"docker logs {ContainerId}");
                var executeResults = powerShellInstance.Invoke();
                foreach (var psObject in executeResults)
                {
                    if (psObject != null)
                    {
                        var message = psObject.BaseObject.ToString();
                        if (message.Contains("The default language (LCID 0) has been set for engine and full-text services"))
                        {
                            ready = true;
                        }
                    }
                }

                if (ready.Equals(false))
                {
                    Thread.Sleep(1000);
                }
                else
                {
                    Console.WriteLine($"wait {i} second");
                    break;
                }
            }

            databaseIp  = $"127.0.0.1,{Port}";
            containerId = string.IsNullOrWhiteSpace(ContainerId) ? "" : ContainerId;
        }
Esempio n. 23
0
        public void Analyze(IEnumerable <string> cmdletProbingDirs,
                            Func <IEnumerable <string>, IEnumerable <string> > directoryFilter,
                            Func <string, bool> cmdletFilter,
                            IEnumerable <string> modulesToAnalyze)
        {
            var savedDirectory     = Directory.GetCurrentDirectory();
            var processedHelpFiles = new List <string>();
            var issueLogger        = Logger.CreateLogger <SignatureIssue>(signatureIssueReportLoggerName);

            List <string> probingDirectories = new List <string>();

            if (directoryFilter != null)
            {
                cmdletProbingDirs = directoryFilter(cmdletProbingDirs);
            }

            foreach (var baseDirectory in cmdletProbingDirs.Where(s => !s.Contains("ServiceManagement") &&
                                                                  !s.Contains("Stack") && Directory.Exists(Path.GetFullPath(s))))
            {
                //Add current directory for probing
                probingDirectories.Add(baseDirectory);
                probingDirectories.AddRange(Directory.EnumerateDirectories(Path.GetFullPath(baseDirectory)));

                foreach (var directory in probingDirectories)
                {
                    if (modulesToAnalyze != null &&
                        modulesToAnalyze.Any() &&
                        !modulesToAnalyze.Where(m => directory.EndsWith(m)).Any())
                    {
                        continue;
                    }

                    var service       = Path.GetFileName(directory);
                    var manifestFiles = Directory.EnumerateFiles(directory, "*.psd1").ToList();
                    if (manifestFiles.Count > 1)
                    {
                        manifestFiles = manifestFiles.Where(f => Path.GetFileName(f).IndexOf(service) >= 0).ToList();
                    }

                    if (!manifestFiles.Any())
                    {
                        continue;
                    }

                    var psd1            = manifestFiles.FirstOrDefault();
                    var parentDirectory = Directory.GetParent(psd1).FullName;
                    var psd1FileName    = Path.GetFileName(psd1);
                    IEnumerable <string> nestedModules   = null;
                    List <string>        requiredModules = null;
                    PowerShell           powershell      = PowerShell.Create();
                    powershell.AddScript("Import-LocalizedData -BaseDirectory " + parentDirectory +
                                         " -FileName " + psd1FileName +
                                         " -BindingVariable ModuleMetadata; $ModuleMetadata.NestedModules; $ModuleMetadata.RequiredModules | % { $_[\"ModuleName\"] };");
                    var cmdletResult = powershell.Invoke();
                    nestedModules   = cmdletResult.Where(c => c.ToString().StartsWith(".")).Select(c => c.ToString().Substring(2));
                    requiredModules = cmdletResult.Where(c => !c.ToString().StartsWith(".")).Select(c => c.ToString()).ToList();

                    if (nestedModules.Any())
                    {
                        Directory.SetCurrentDirectory(directory);

                        requiredModules = requiredModules.Join(cmdletProbingDirs,
                                                               module => 1,
                                                               dir => 1,
                                                               (module, dir) => Path.Combine(dir, module))
                                          .Where(f => Directory.Exists(f))
                                          .ToList();

                        requiredModules.Add(directory);

                        foreach (var nestedModule in nestedModules)
                        {
                            var assemblyFile = Directory.GetFiles(parentDirectory, nestedModule, SearchOption.AllDirectories).FirstOrDefault();
                            if (File.Exists(assemblyFile))
                            {
                                issueLogger.Decorator.AddDecorator(a => a.AssemblyFileName = assemblyFile, "AssemblyFileName");
                                processedHelpFiles.Add(assemblyFile);
                                var proxy =
#if !NETSTANDARD
                                    EnvironmentHelpers.CreateProxy <CmdletLoader>(directory, out _appDomain);
#else
                                    new CmdletLoader();
#endif
                                var module  = proxy.GetModuleMetadata(assemblyFile, requiredModules);
                                var cmdlets = module.Cmdlets;

                                if (cmdletFilter != null)
                                {
                                    cmdlets = cmdlets.Where <CmdletMetadata>((cmdlet) => cmdletFilter(cmdlet.Name)).ToList <CmdletMetadata>();
                                }

                                foreach (var cmdlet in cmdlets)
                                {
                                    Logger.WriteMessage("Processing cmdlet '{0}'", cmdlet.ClassName);
                                    string defaultRemediation = "Determine if the cmdlet should implement ShouldProcess and " +
                                                                "if so determine if it should implement Force / ShouldContinue";
                                    if (!cmdlet.SupportsShouldProcess && cmdlet.HasForceSwitch)
                                    {
                                        issueLogger.LogSignatureIssue(
                                            cmdlet: cmdlet,
                                            severity: 0,
                                            problemId: SignatureProblemId.ForceWithoutShouldProcessAttribute,
                                            description: string.Format("{0} Has  -Force parameter but does not set the SupportsShouldProcess " +
                                                                       "property to true in the Cmdlet attribute.", cmdlet.Name),
                                            remediation: defaultRemediation);
                                    }
                                    if (!cmdlet.SupportsShouldProcess && cmdlet.ConfirmImpact != ConfirmImpact.Medium)
                                    {
                                        issueLogger.LogSignatureIssue(
                                            cmdlet: cmdlet,
                                            severity: 2,
                                            problemId: SignatureProblemId.ConfirmLeveleWithNoShouldProcess,
                                            description:
                                            string.Format("{0} Changes the ConfirmImpact but does not set the " +
                                                          "SupportsShouldProcess property to true in the cmdlet attribute.",
                                                          cmdlet.Name),
                                            remediation: defaultRemediation);
                                    }
                                    if (!cmdlet.SupportsShouldProcess && cmdlet.IsShouldProcessVerb)
                                    {
                                        issueLogger.LogSignatureIssue(
                                            cmdlet: cmdlet,
                                            severity: 1,
                                            problemId: SignatureProblemId.ActionIndicatesShouldProcess,
                                            description:
                                            string.Format(
                                                "{0} Does not support ShouldProcess but the cmdlet verb {1} indicates that it should.",
                                                cmdlet.Name, cmdlet.VerbName),
                                            remediation: defaultRemediation);
                                    }
                                    if (cmdlet.ConfirmImpact != ConfirmImpact.Medium)
                                    {
                                        issueLogger.LogSignatureIssue(
                                            cmdlet: cmdlet,
                                            severity: 2,
                                            problemId: SignatureProblemId.ConfirmLevelChange,
                                            description:
                                            string.Format("{0} changes the confirm impact.  Please ensure that the " +
                                                          "change in ConfirmImpact is justified", cmdlet.Name),
                                            remediation:
                                            "Verify that ConfirmImpact is changed appropriately by the cmdlet. " +
                                            "It is very rare for a cmdlet to change the ConfirmImpact.");
                                    }
                                    if (!cmdlet.IsApprovedVerb)
                                    {
                                        issueLogger.LogSignatureIssue(
                                            cmdlet: cmdlet,
                                            severity: 1,
                                            problemId: SignatureProblemId.CmdletWithUnapprovedVerb,
                                            description:
                                            string.Format(
                                                "{0} uses the verb '{1}', which is not on the list of approved " +
                                                "verbs for PowerShell commands. Use the cmdlet 'Get-Verb' to see " +
                                                "the full list of approved verbs and consider renaming the cmdlet.",
                                                cmdlet.Name, cmdlet.VerbName),
                                            remediation: "Consider renaming the cmdlet to use an approved verb for PowerShell.");
                                    }

                                    if (!cmdlet.HasSingularNoun)
                                    {
                                        issueLogger.LogSignatureIssue(
                                            cmdlet: cmdlet,
                                            severity: 1,
                                            problemId: SignatureProblemId.CmdletWithPluralNoun,
                                            description:
                                            string.Format(
                                                "{0} uses the noun '{1}', which does not follow the enforced " +
                                                "naming convention of using a singular noun for a cmdlet name.",
                                                cmdlet.Name, cmdlet.NounName),
                                            remediation: "Consider using a singular noun for the cmdlet name.");
                                    }

                                    if (!cmdlet.OutputTypes.Any())
                                    {
                                        issueLogger.LogSignatureIssue(
                                            cmdlet: cmdlet,
                                            severity: 1,
                                            problemId: SignatureProblemId.CmdletWithNoOutputType,
                                            description:
                                            string.Format(
                                                "Cmdlet '{0}' has no defined output type.", cmdlet.Name),
                                            remediation: "Add an OutputType attribute that declares the type of the object(s) returned " +
                                            "by this cmdlet. If this cmdlet returns no output, please set the output " +
                                            "type to 'bool' and make sure to implement the 'PassThru' parameter.");
                                    }

                                    foreach (var parameter in cmdlet.GetParametersWithPluralNoun())
                                    {
                                        issueLogger.LogSignatureIssue(
                                            cmdlet: cmdlet,
                                            severity: 1,
                                            problemId: SignatureProblemId.ParameterWithPluralNoun,
                                            description:
                                            string.Format(
                                                "Parameter {0} of cmdlet {1} does not follow the enforced " +
                                                "naming convention of using a singular noun for a parameter name.",
                                                parameter.Name, cmdlet.Name),
                                            remediation: "Consider using a singular noun for the parameter name.");
                                    }

                                    foreach (var parameterSet in cmdlet.ParameterSets)
                                    {
                                        if (parameterSet.Name.Contains(" "))
                                        {
                                            issueLogger.LogSignatureIssue(
                                                cmdlet: cmdlet,
                                                severity: 1,
                                                problemId: SignatureProblemId.ParameterSetWithSpace,
                                                description:
                                                string.Format(
                                                    "Parameter set '{0}' of cmdlet '{1}' contains a space, which " +
                                                    "is discouraged for PowerShell parameter sets.",
                                                    parameterSet.Name, cmdlet.Name),
                                                remediation: "Remove the space(s) in the parameter set name.");
                                        }

                                        if (parameterSet.Parameters.Any(p => p.Position >= 4))
                                        {
                                            issueLogger.LogSignatureIssue(
                                                cmdlet: cmdlet,
                                                severity: 1,
                                                problemId: SignatureProblemId.ParameterWithOutOfRangePosition,
                                                description:
                                                string.Format(
                                                    "Parameter set '{0}' of cmdlet '{1}' contains at least one parameter " +
                                                    "with a position larger than four, which is discouraged.",
                                                    parameterSet.Name, cmdlet.Name),
                                                remediation: "Limit the number of positional parameters in a single parameter set to " +
                                                "four or fewer.");
                                        }
                                    }

                                    if (cmdlet.ParameterSets.Count() > 2 && cmdlet.DefaultParameterSetName == "__AllParameterSets")
                                    {
                                        issueLogger.LogSignatureIssue(
                                            cmdlet: cmdlet,
                                            severity: 1,
                                            problemId: SignatureProblemId.MultipleParameterSetsWithNoDefault,
                                            description:
                                            string.Format(
                                                "Cmdlet '{0}' has multiple parameter sets, but no defined default parameter set.",
                                                cmdlet.Name),
                                            remediation: "Define a default parameter set in the cmdlet attribute.");
                                    }
                                }

                                AppDomain.Unload(_appDomain);
                                issueLogger.Decorator.Remove("AssemblyFileName");
                            }
                        }
                        Directory.SetCurrentDirectory(savedDirectory);
                    }
                }
            }
        }
Esempio n. 24
0
        public async Task ListenerLoop()
        {
            while (!StopServer)
            {
                var context = await Listener.GetContextAsync();

                if (StopServer)
                {
                    break;
                }

                HttpListenerRequest  rawRequest  = context.Request;
                HttpListenerResponse rawResponse = context.Response;

                Log("request came in: " + rawRequest.HttpMethod + " " + rawRequest.RawUrl);

                PolarisRequest  request  = new PolarisRequest(rawRequest);
                PolarisResponse response = new PolarisResponse();

                string     route = rawRequest.Url.AbsolutePath.TrimEnd('/').TrimStart('/');
                PowerShell PowerShellInstance = PowerShell.Create();
                PowerShellInstance.RunspacePool = PowerShellPool;
                try
                {
                    // Set up PowerShell instance by making request and response global
                    PowerShellInstance.AddScript(PolarisHelperScripts.InitializeRequestAndResponseScript);
                    PowerShellInstance.AddParameter("req", request);
                    PowerShellInstance.AddParameter("res", response);

                    // Run middleware in the order in which it was added
                    foreach (PolarisMiddleware middleware in RouteMiddleware)
                    {
                        PowerShellInstance.AddScript(middleware.ScriptBlock);
                    }

                    PowerShellInstance.AddScript(ScriptBlockRoutes[route][rawRequest.HttpMethod]);

                    var res = PowerShellInstance.BeginInvoke <PSObject>(new PSDataCollection <PSObject>(), new PSInvocationSettings(), (result) => {
                        if (PowerShellInstance.InvocationStateInfo.State == PSInvocationState.Failed)
                        {
                            Log(PowerShellInstance.InvocationStateInfo.Reason.ToString());
                            response.Send(PowerShellInstance.InvocationStateInfo.Reason.ToString());
                            response.SetStatusCode(500);
                        }
                        Send(rawResponse, response);
                        PowerShellInstance.Dispose();
                    }, null);
                }
                catch (Exception e)
                {
                    if (e is KeyNotFoundException)
                    {
                        Send(rawResponse, System.Text.Encoding.UTF8.GetBytes("Not Found"), 404, "text/plain; charset=UTF-8");
                        Log("404 Not Found");
                    }
                    else
                    {
                        Log(e.Message);
                        throw e;
                    }
                }
            }

            Listener.Close();
            PowerShellPool.Dispose();
        }
        public static DscBreakpointCapability CheckForCapability(
            RunspaceDetails runspaceDetails,
            PowerShellContext powerShellContext,
            ILogger logger)
        {
            DscBreakpointCapability capability = null;

            // DSC support is enabled only for Windows PowerShell.
            if ((runspaceDetails.PowerShellVersion.Version.Major < 6) &&
                (runspaceDetails.Context != RunspaceContext.DebuggedRunspace))
            {
                using (PowerShell powerShell = PowerShell.Create())
                {
                    powerShell.Runspace = runspaceDetails.Runspace;

                    // Attempt to import the updated DSC module
                    powerShell.AddCommand("Import-Module");
                    powerShell.AddArgument(@"C:\Program Files\DesiredStateConfiguration\1.0.0.0\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.psd1");
                    powerShell.AddParameter("PassThru");
                    powerShell.AddParameter("ErrorAction", "Ignore");

                    PSObject moduleInfo = null;

                    try
                    {
                        moduleInfo = powerShell.Invoke().FirstOrDefault();
                    }
                    catch (CmdletInvocationException e)
                    {
                        logger.WriteException("Could not load the DSC module!", e);
                    }

                    if (moduleInfo != null)
                    {
                        logger.Write(LogLevel.Verbose, "Side-by-side DSC module found, gathering DSC resource paths...");

                        // The module was loaded, add the breakpoint capability
                        capability = new DscBreakpointCapability();
                        runspaceDetails.AddCapability(capability);

                        powerShell.Commands.Clear();
                        powerShell.AddScript("Write-Host \"Gathering DSC resource paths, this may take a while...\"");
                        powerShell.Invoke();

                        // Get the list of DSC resource paths
                        powerShell.Commands.Clear();
                        powerShell.AddCommand("Get-DscResource");
                        powerShell.AddCommand("Select-Object");
                        powerShell.AddParameter("ExpandProperty", "ParentPath");

                        Collection <PSObject> resourcePaths = null;

                        try
                        {
                            resourcePaths = powerShell.Invoke();
                        }
                        catch (CmdletInvocationException e)
                        {
                            logger.WriteException("Get-DscResource failed!", e);
                        }

                        if (resourcePaths != null)
                        {
                            capability.dscResourceRootPaths =
                                resourcePaths
                                .Select(o => (string)o.BaseObject)
                                .ToArray();

                            logger.Write(LogLevel.Verbose, $"DSC resources found: {resourcePaths.Count}");
                        }
                        else
                        {
                            logger.Write(LogLevel.Verbose, $"No DSC resources found.");
                        }
                    }
                    else
                    {
                        logger.Write(LogLevel.Verbose, $"Side-by-side DSC module was not found.");
                    }
                }
            }

            return(capability);
        }
Esempio n. 26
0
        protected void InitPowerShell()
        {
            Logger.LogInformation("***********************************************");
            Logger.LogInformation("Constructing PowerShell execution context");
            _posh = PowerShell.Create();

            // Need to create our own runspace so we can pass in our own custom PSHost
            // which ties the PowerShell context to our custom handler environment
            _posh.Runspace = RunspaceFactory.CreateRunspace(new Ps5CustomHost(Logger, name: "PS5Host"));
            _posh.Runspace.Open();

            // Register some context-supporting variables in scope
            _posh.AddCommand("Microsoft.PowerShell.Utility\\Set-Variable");
            _posh.AddParameter("Name", PS_VAR_HANDLER_LOGGER);
            _posh.AddParameter("Option", "ReadOnly");
            _posh.AddParameter("Description", "ILogger to be used by handler cmdlet");
            _posh.AddParameter("Value", new PsLogger(Logger));
            _posh.Invoke();
            _posh.Commands.Clear();

            // Register some context-supporting variables in scope
            _posh.AddCommand("Microsoft.PowerShell.Utility\\Set-Variable");
            _posh.AddParameter("Name", PS_VAR_HANDLER_APP_CONFIGURATION);
            _posh.AddParameter("Option", "ReadOnly");
            _posh.AddParameter("Description", "App-wide configuration (read-only)");
            _posh.AddParameter("Value", new ReadOnlyConfiguration(AppConfig));
            _posh.Invoke();
            _posh.Commands.Clear();

            // Set the CWD for the PowerShell cmdlets to run from
            _posh.AddCommand("Microsoft.PowerShell.Management\\Set-Location");
            _posh.AddArgument(_bootstrapFullpath);
            var result = _posh.Invoke();

            _posh.Commands.Clear();
            Logger.LogInformation("Relocated PWD for current execution context >>>>>>>>>>>>>>");
            foreach (var r in result)
            {
                Logger.LogWarning(">> " + r.ToString());
            }

            // If a bootstrap script was provided in the app settings
            // let's invoke it and capture the results for diagnostics
            if (BootstrapScript != null && BootstrapScript.Count() > 0)
            {
                Logger.LogInformation("Bootstrap Script found");
                Logger.LogDebug("--8<---------------------------------");
                foreach (var s in BootstrapScript)
                {
                    Logger.LogDebug(s);
                    _posh.AddScript(s);
                }
                Logger.LogDebug("--------------------------------->8--");
                result = _posh.Invoke();

                _posh.Commands.Clear();

                Logger.LogInformation("Bootstrap Script executed");
                Logger.LogDebug("--8<---------------------------------");
                foreach (var r in result)
                {
                    Logger.LogDebug(">> " + r.ToString());
                }
                Logger.LogDebug("--------------------------------->8--");
            }
        }
Esempio n. 27
0
 public static PowerShell CreateShell()
 {
     return(PowerShell.Create(RunspaceMode.CurrentRunspace));
 }
        public void process()
        {
            string password = "******";
            string userName = "******";

            System.Uri uri = new Uri("https://WIN-KURRR2QSDJ0.jnittech.com/powershell?serializationLevel=Full");
            System.Security.SecureString securePassword = String2SecureString(password);

            PSCredential creds = new PSCredential(userName, securePassword);

            Runspace runspace = RunspaceFactory.CreateRunspace();

            PowerShell powershell = PowerShell.Create();

            PSCommand command = new PSCommand();

            command.AddCommand("New-PSSession");
            command.AddParameter("ConfigurationName", "Microsoft.Exchange");
            command.AddParameter("ConnectionUri", uri);
            command.AddParameter("Credential", creds);
            command.AddParameter("Authentication", "Default");

            PSSessionOption sessionOption = new PSSessionOption();

            sessionOption.SkipCACheck         = true;
            sessionOption.SkipCNCheck         = true;
            sessionOption.SkipRevocationCheck = true;

            command.AddParameter("SessionOption", sessionOption);

            powershell.Commands = command;

            try
            {
                // open the remote runspace
                runspace.Open();

                // associate the runspace with powershell
                powershell.Runspace = runspace;

                // invoke the powershell to obtain the results
                Collection <PSSession> result = powershell.Invoke <PSSession>();

                foreach (ErrorRecord current in powershell.Streams.Error)
                {
                    Console.WriteLine("Exception: " + current.Exception.ToString());
                    Console.WriteLine("Inner Exception: " + current.Exception.InnerException);
                }

                if (result.Count != 1)
                {
                    throw new Exception("Unexpected number of Remote Runspace connections returned.");
                }

                // Set the runspace as a local variable on the runspace
                powershell = PowerShell.Create();
                command    = new PSCommand();
                command.AddCommand("Set-Variable");
                command.AddParameter("Name", "ra");
                command.AddParameter("Value", result[0]);
                powershell.Commands = command;
                powershell.Runspace = runspace;
                powershell.Invoke();

                // First import the cmdlets in the current runspace (using Import-PSSession)
                powershell = PowerShell.Create();
                command    = new PSCommand();
                command.AddScript("Import-PSSession -Session $ra");
                powershell.Commands = command;
                powershell.Runspace = runspace;
                powershell.Invoke();

                // Now run get-ExchangeServer
                System.Collections.ObjectModel.Collection <PSObject> results = new System.Collections.ObjectModel.Collection <PSObject>();

                powershell          = PowerShell.Create();
                powershell.Runspace = runspace;

                //Change the Path to the Script to suit your needs
                System.IO.StreamReader sr = new System.IO.StreamReader("C:\\GetIn\\Sudheer\\PowerShellScript-Own\\c#PowerShellScripts\\EX_QueuesBasedOnIdentity.ps1");
                string reportStream       = sr.ReadToEnd();
                powershell.AddScript(reportStream);
                powershell.AddParameter("identity", "WIN-KURRR2QSDJ0\\Submission");
                try
                {
                    results = powershell.Invoke();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                //powershell.Runspace.SessionStateProxy.SetVariable("server", "win-kurrr2qsdj0.jnittech.com");
                //powershell.Runspace.SessionStateProxy.SetVariable("mbx", "*MBX");



                if (powershell.Streams.Error.Count > 51)
                {
                    foreach (ErrorRecord er in powershell.Streams.Error)
                    {
                        Console.WriteLine(er.ErrorDetails);
                    }
                }
                else
                {
                    foreach (var ps in results)
                    {
                        Console.WriteLine(ps.Properties["RunspaceId"].Name.ToString() + ": " + ps.Properties["RunspaceId"].Value.ToString());
                        Console.WriteLine(ps.Properties["Identity"].Name.ToString() + ": " + ps.Properties["Identity"].Value.ToString());
                        Console.WriteLine(ps.Properties["DeliveryType"].Name.ToString() + ": " + ps.Properties["DeliveryType"].Value.ToString());
                    }
                }
            }
            finally
            {
                // dispose the runspace and enable garbage collection
                runspace.Dispose();
                runspace = null;

                // Finally dispose the powershell and set all variables to null to free
                // up any resources.
                powershell.Dispose();
                powershell = null;
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Override inside a safe lock
        /// </summary>
        /// <param name="remoteRunspace">runspace to override</param>
        /// <param name="syncObject">object to use in synchronization</param>
        /// <param name="isRunspacePushed">set is runspace pushed</param>
        internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed)
        {
            lock (_localSyncObject)
            {
                _stopInvoke = false;
            }

            try
            {
                if (syncObject != null)
                {
                    lock (syncObject)
                    {
                        _runspaceRef.Override(remoteRunspace);
                        isRunspacePushed = true;
                    }
                }
                else
                {
                    _runspaceRef.Override(remoteRunspace);
                    isRunspacePushed = true;
                }

                if ((remoteRunspace.GetCurrentlyRunningPipeline() != null))
                {
                    // Don't execute command if pushed runspace is already running one.
                    return;
                }

                using (PowerShell powerShell = PowerShell.Create())
                {
                    powerShell.AddCommand("Get-Command");
                    powerShell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" });
                    powerShell.Runspace = _runspaceRef.Value;

                    bool isReleaseCandidateBackcompatibilityMode =
                        _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC;
                    powerShell.IsGetCommandMetadataSpecialPipeline = !isReleaseCandidateBackcompatibilityMode;
                    int expectedNumberOfResults = isReleaseCandidateBackcompatibilityMode ? 2 : 3;

                    powerShell.RemotePowerShell.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(HandleHostCall);

                    IAsyncResult asyncResult            = powerShell.BeginInvoke();
                    PSDataCollection <PSObject> results = new PSDataCollection <PSObject>();

                    while (!_stopInvoke)
                    {
                        asyncResult.AsyncWaitHandle.WaitOne(1000);

                        if (asyncResult.IsCompleted)
                        {
                            results = powerShell.EndInvoke(asyncResult);
                            break;
                        }
                    }

                    if (powerShell.Streams.Error.Count > 0 || results.Count < expectedNumberOfResults)
                    {
                        throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException();
                    }
                }
            }
            catch (Exception)
            {
                _runspaceRef.Revert();
                isRunspacePushed = false;
                throw;
            }
        }
Esempio n. 30
0
        public MainWindow()
        {
            //DateTime dstart = DateTime.Now;
            InitializeComponent();

            CommandArgs.AddRange(Environment.GetCommandLineArgs());
            CommandArgs.RemoveAt(0);

            //Disable SSL/TLS Errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            //Disable CRL Check
            System.Net.ServicePointManager.CheckCertificateRevocationList = false;
            //Get Proxy from IE
            WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();

            if (Properties.Settings.Default.UpgradeSettings)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.UpgradeSettings = false;
                Properties.Settings.Default.Save();
            }

            //Get Version
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);

            tbVersion.Text   = string.Format(tbVersion.Text, fvi.FileVersion);
            lVersion.Content = "Version: " + fvi.FileVersion;

            //Hide Tabs
            Style s = new Style();

            s.Setters.Add(new Setter(UIElement.VisibilityProperty, Visibility.Collapsed));
            tabWizard.ItemContainerStyle = s;

            tbSVC.Text = RZRestAPIv2.sURL;
            if (RZRestAPIv2.DisableBroadcast)
            {
                cbRZCache.IsChecked = false;
                cbRZCache.IsEnabled = false;
            }
            else
            {
                RZRestAPIv2.DisableBroadcast = Properties.Settings.Default.DisableBroadcast;
                cbRZCache.IsChecked          = !Properties.Settings.Default.DisableBroadcast;
            }

            if (string.IsNullOrEmpty(RZRestAPIv2.CustomerID))
            {
                tbCustomerID.IsEnabled   = true;
                RZRestAPIv2.CustomerID   = Properties.Settings.Default.CustomerID;
                btSettingsSave.IsEnabled = true;
            }
            else
            {
                tbCustomerID.Text        = RZRestAPIv2.CustomerID;
                tbCustomerID.IsEnabled   = false;
                btSettingsSave.IsEnabled = false;
            }

            oInstPanel.onEdit += oInstPanel_onEdit;
            oUpdPanel.onEdit  += oInstPanel_onEdit;
            //oInstPanel.OnSWUpdated += OUpdPanel_OnSWUpdated;
            oUpdPanel.OnSWUpdated += OUpdPanel_OnSWUpdated;

            //double dSeconds = (DateTime.Now - dstart).TotalSeconds;
            //dSeconds.ToString();


            //Run PowerShell check in separate thread...
            Thread thread = new Thread(() =>
            {
                try
                {
                    Runspace runspace = RunspaceFactory.CreateRunspace();
                    runspace.Open();

                    PowerShell powershell = PowerShell.Create();
                    powershell.AddScript("(get-Host).Version");
                    powershell.Runspace           = runspace;
                    Collection <PSObject> results = powershell.Invoke();
                    if (((System.Version)(results[0].BaseObject)).Major < 4)
                    {
                        if (MessageBox.Show("The current Version of PowerShell is not supported. Do you want to update ?", "Update Powershell", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.Yes) == MessageBoxResult.Yes)
                        {
                            //Update...
                            Process.Start("https://www.microsoft.com/en-us/download/details.aspx?id=50395");
                            this.Close();
                        }
                    }
                }
                catch { }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

            oSCAN = new RZScan(false, false);

            //AzureAD Authentication
            GetAADTokenAsync();

            FileVersionInfo FI = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location);

            //oSCAN.StaticInstalledSoftware.Add(new AddSoftware() { ProductName = "RuckZuck", Manufacturer = FI.CompanyName, ProductVersion = FI.ProductVersion.ToString() });
            oSCAN.OnSWScanCompleted  += OSCAN_OnSWScanCompleted;
            oSCAN.OnUpdatesDetected  += OSCAN_OnUpdatesDetected;
            oSCAN.OnSWRepoLoaded     += OSCAN_OnSWRepoLoaded;
            oSCAN.OnUpdScanCompleted += OSCAN_OnUpdScanCompleted;
            oSCAN.OnInstalledSWAdded += OSCAN_OnInstalledSWAdded;
            oSCAN.bCheckUpdates       = true;

            oSCAN.GetSWRepository().ConfigureAwait(false);

            //oSCAN.tRegCheck.Start();


            if (CommandArgs.Count > 0)
            {
            }
            else
            {
                //Show About once...
                if (!Properties.Settings.Default.ShowAbout)
                {
                    tabWizard.SelectedItem = tabMain;
                }
                else
                {
                    tabWizard.SelectedItem = tabStart;
                    Properties.Settings.Default.ShowAbout = false;
                    Properties.Settings.Default.Save();
                }
            }
        }