• 0

Executing a PowerShell script from C# with Parameters


Question

Sup. I'm adapting this solution to a Windows Forms solution. So far I've been able to execute the `Get-WUList` command with no problems. But it doesn't seem to go well with the `Hide-WUUpdate`. This is what I've tried so far:

 

    public class PowerShellController : IPowerShell
    {

        //Created at a global scope so anyone can fetch it.
        InitialSessionState initial;
        RunspaceInvoke scriptInvoker;
        Runspace runspace;
        PowerShell ps;

        //The View to Control
        IView view;

        //The Helper GridViewProcessor class
        IGridViewProcessor gp;

        //Initializing the Controller - Loads the Module.
        public PowerShellController()
        {
            initial = InitialSessionState.CreateDefault();
            initial.ImportPSModule(new string[] { @"C:\Users\Jose\Documents\WindowsPowerShell\Modules\PSWindowsUpdate\PSWindowsUpdate.psd1" });
            scriptInvoker = new RunspaceInvoke();
            scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope Process");

            runspace = RunspaceFactory.CreateRunspace(initial);
            runspace.Open();

            using (ps = PowerShell.Create())
            {
                ps.Runspace = runspace;
            }

            //Console.WriteLine("Please Wait. This will take a while to load.");

        }


        public void SetView(IView view, IGridViewProcessor gp)
        {
            this.view = view;
            this.gp = gp;
        }


        public void GetAvailableUpdates()
        {

            MessageBox.Show("Ok. The program will kind of hang. This is normal." +
                            "This Means that it will start looking for updates "
                );

            IEnumerable<PSObject> WUList; //Placeholder for the PS Executed Command

            using (ps = PowerShell.Create())
            {
                //Adds the PowerShell Command
                ps.Commands.AddCommand("Get-WUList");
                //Executes the PowerShell command
                WUList = ps.Invoke();
            }
            
            //Loads the Model - Can be later on rewritten for Ninject Support.
            List<WindowsUpdate> model = new List<WindowsUpdate>();
            int id = 1;
            foreach (PSObject result in WUList)
            {
                WindowsUpdate item = new WindowsUpdate
                {
                    Id = id,
                    Name = result.Members["Title"].Value.ToString(),
                    Size = result.Members["Size"].Value.ToString(),
                    Type = UpdateType.Undefined,

                };
                model.Add(item);
                id++; //Icnrease ID count
                //Console.WriteLine("Update Name {0} --- Size: {1}", result.Members["Title"].Value.ToString(), result.Members["Size"].Value.ToString());
            }

            //Adds it to the view:
            view.AddUpdateToGrid(model);
        }

        public void HideSelectedUpdates(DataGridView grid)
        {
            //Gets SelectedUpdates to the WindowsUpdate model
            var SelectedUpdates = gp.GetSelectedUpdates(grid);
            using (ps = PowerShell.Create())
            {
                foreach (var update in SelectedUpdates)
                {
                    ps.Commands.Clear();
                    ps.Commands.AddCommand("Hide-WUUpdate").AddParameter("Title",update.Name).AddParameter("Confirm", false);
                                        
                    //ps.Commands.AddCommand("Hide-WUUpdate -Title \""+update.Name+"\"");
                   var result = ps.Invoke();
                    
                }

            }

            MessageBox.Show("Updates Have been hidden");

        }

    }


The method I can't seem to work is the `HideSelectedUpdates(DataGridView grid)`.

Script gets executed and no exceptions are thrown, but it doesn't seem to reflect any changes at all.

Any suggestions?
 

4 answers to this question

Recommended Posts

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • they should stop making bad games that no one asked for
    • Nice rant! Expletive after expletive after expletive. Poor petal, I've touched a nerve. Would you like a tissue to wipe those tears away. Btw, nice one calling Neowin trash. Why would you stick around when you disrespect this site and the people behind it? Just go away if you feel that way.
    • Internet Download Manager (IDM) 6.43 Build 1 by Razvan Serea Internet Download Manager (IDM) is a tool to increase download speeds by up to 8 times due to its smart dynamic file segmentation technology. Unlike other download managers and accelerators, Internet Download Manager segments downloaded files dynamically during download process, and it reuses available connections without additional connect and login stages to achieve the best possible acceleration performance. Comprehensive error recovery and resume capability will restart broken or interrupted downloads due to lost connections, network problems, computer shutdowns, or unexpected power outages. All popular browsers are supported IDM integrates seamlessly into Google Chrome, FireFox, Microsoft Edge, Opera, Safari, Internet Explorer, Maxthon and all other popular browsers to automatically handle your downloads. You can also drag and drop files, or use Internet Download Manager from command line. The program supports proxy servers, ftp and http protocols, firewalls, redirects, cookies, authorization, MP3 audio and video content processing. IDM includes web site spider and grabber IDM downloads all required files that are specified with filters from web sites, for example all pictures from a web site, or subsets of web sites, or complete web sites for offline browsing. It's possible to schedule multiple grabber projects to run them once at a specified time, stop them at a specified time, or run periodically to synchronize changes. Easy downloading with one click When you click on a download link in a browser, IDM will take over the download and accelerate it. You don't need to do anything special, just browse the Internet as you usually do. IDM will catch your downloads and accelerate them. IDM supports HTTP, FTP, HTTPS and MMS protocols. Changes in Internet Download Manager 6.43 Build 1: Added the ability to download MP4 files from web sites where previously only TS videos were available. IDM displays both TS and MP4 file formats in its video download button. If you only need MP4 files, disable TS in IDM Options -> General tab -> Customize IDM Download panels in browsers -> Edit button. Remove TS extension on "Customize IDM Download panel in browsres" dialog Fixed video downloading problems on several popular web sites Fixed bugs Download: Internet Download Manager 6.43 Build 1 | 11.9 MB (Shareware) Links: Internet Download Manager Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • This is of course "clickbait" WTF? It is literally your example but tech based. A "clickbait" title is a sensationalized headline designed to manipulate readers into clicking a link using things like "fear" rather than delivering objective facts. A "clickbait" headline also usually provides little value compared to the hype generated. How does this headline not qualify? It's a generic often reused headline that is overly sensationalized. Oh no! "millions" can't use this app anymore. It has no basic facts like what f*cking app. You read the article and it's the Samsung VPN which no one cares about and there is a million free VPNs. How are you defending this ######? Headlines like this (and among other things) make me read Neowin much less than I used to in the past. It's trash...
  • Recent Achievements

    • Veteran
      branfont went up a rank
      Veteran
    • Reacting Well
      Almohandis earned a badge
      Reacting Well
    • First Post
      Cosminus earned a badge
      First Post
    • One Year In
      ThatGuyOnline earned a badge
      One Year In
    • Week One Done
      Jeroen Wilms earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      475
    2. 2
      +Edouard
      182
    3. 3
      PsYcHoKiLLa
      122
    4. 4
      Steven P.
      85
    5. 5
      neufuse
      73
  • Tell a friend

    Love Neowin? Tell a friend!