• 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

    • Audacious 4.6.1 by Razvan Serea Audacious is a lightweight, open-source audio player that emphasizes simplicity, performance, and sound quality. Designed for Linux, Windows, and macOS, it supports a wide range of audio formats, internet radio streaming, and playlist management. Users can customize the interface with Winamp-style skins or modern themes, making it flexible for different preferences. Audacious also includes an equalizer, advanced audio effects, and a plugin system for extending functionality. Its low resource usage makes it especially suitable for older computers or users who value efficiency without sacrificing playback quality. Audacious key features: High audio quality – delivers clean, gapless playback with minimal distortion. Wide format support – plays MP3, FLAC, Ogg Vorbis, AAC, WAV, WMA, and more. Internet radio streaming – supports Shoutcast, Icecast, and other online streams. Winamp skin support – classic, nostalgic look for users who prefer the old-school style. Modern GTK-based interface – clean, simple UI with a more modern feel. Customizable themes – change appearance through skins and themes. Advanced playlist management – organize, save, and edit playlists with ease. Equalizer – fine-tune audio output with a built-in graphical equalizer. Audio effects – built-in DSP options like crossfade, replay gain, and more. Plugin system – extend functionality with additional components. File metadata support – displays and organizes music based on tags. Drag-and-drop support – quickly add songs or playlists. Global hotkey support – control playback without switching windows. Bit-perfect output modes – bypass system mixers for pure audio output. ReplayGain support – normalizes track loudness automatically. Cue sheet support – play entire albums from a single audio file with .cue. MPRIS2 integration – integrates with Linux desktop environments for media controls. Advanced resampling options – adjust playback quality with different resampler settings. Gapless playback – seamless transition between tracks encoded properly. Crossfade plugin – blend one song into the next smoothly. Last.fm scrobbling plugin – track listening history online. Remote control support – control Audacious via command-line or scripts. Lyrics plugin – display song lyrics if available. Alarm / timer plugin – start or stop playback at set times. SOX resampler plugin – high-quality resampling for audiophiles. Spectrum analyzer / visualization plugins – visual feedback while playing music. Headphone crossfeed effect – simulates speaker listening for headphones. Customizable buffer size – tweak latency and playback smoothness. Audacious 4.6.1 changelog: Use XDG cache dir to store temporary files (#1817) Accept embedded lyrics in more cases (#1818) Bump .so and plugin ABI versions retrospectively (#1819) Include Georgian translation (#1820) Fix build on systems using musl instead of glibc (#1823) Download: Audacious 4.6.1 | 48.2 MB (Open Source) Download: Portable Audacious 4.6.1 | 69.8 MB View: Audacious Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • I really wonder if this has to do with the built in VPN or "private DNS" of browsers that trip up legal requirements like cookie consent and Cloudflare (to avoid all the botnet attacks we get). And BTW some botnets still manage to get past Cloudflare, we are constantly having to tweak it to block malicious traffic that ultimately cause a DDoS.
    • CPPC states can also be messed around with in most UEFI settings but aren't as robust as the ones that the Windows Scheduler can provide! Make sure you look into what your motherboard also has before customizing for the Windows Scheduler.
  • Recent Achievements

    • Week One Done
      rolfus earned a badge
      Week One Done
    • One Month Later
      Leroy Jethro Gibbs earned a badge
      One Month Later
    • Conversation Starter
      flexorcist earned a badge
      Conversation Starter
    • One Month Later
      AndreaB earned a badge
      One Month Later
    • One Month Later
      agatameier earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      518
    2. 2
      +Edouard
      198
    3. 3
      PsYcHoKiLLa
      147
    4. 4
      ATLien_0
      93
    5. 5
      Steven P.
      78
  • Tell a friend

    Love Neowin? Tell a friend!