Coder Social home page Coder Social logo

Synchronous Invokation about child-shell HOT 4 CLOSED

rannn505 avatar rannn505 commented on June 18, 2024
Synchronous Invokation

from child-shell.

Comments (4)

BenjaminMichael avatar BenjaminMichael commented on June 18, 2024 2

You can use a wrapper function + tail recursion (see my example below) but the more sophisticated thing would be to utilize popular modules like "async" (not the same thing as async await) which have tons of methods for flow control and sequencing like async.Sequence, async.waterfall, async.map, etc

Working with streams in node can be challenging so this is a problem that has been more or less solved already. The beauty of a module like async is that can help your sequence run fast and it saves you from ugly callback syntax much like async await.

Dont forget to .dispose() unless you want a lot of PS consoles open in memory ;)

from child-shell.

rannn505 avatar rannn505 commented on June 18, 2024

Hey @cawoodm ,
First of all sorry it took me a long time to answer. 💯
Second of all, what do you mean when you say synchronously?
Basically, PS invoke most of his commands synchronously:

PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. wikipedia

Let me know if you need further help ... maybe you can add an example...
GL and THx 👍

from child-shell.

alexkokkinos avatar alexkokkinos commented on June 18, 2024

@rannn505
I realize this is a really old issue that's been closed, but I thought I'd clarify what @cawoodm meant since he/she didn't clarify, and I was working on something tangentially related that brought me here:

PowerShell invokes most commands synchronously, but the node-powershell Invoke function is asynchronous, so if one wants to wait for their PowerShell command to finish before moving on to the next line of their Node script they will of course have to call a function from the promise resolution or use async/await.

Since Powershell is generally synchronous, I think @cawoodm is making the request that node-powershell also have a synchronous function to invoke the PowerShell commands so that promises are not returned by node-powershell's Invoke function.

Essentially, the ask is about the possibility of creating a Sync option similarly to how projects like fs-extra or klaw/klaw-sync work.

With the increased adoption of async/await and all the design norms of node, I'm unsute of the utility of this feature, but that's what @cawoodm was inquiring about.

from child-shell.

BenjaminMichael avatar BenjaminMichael commented on June 18, 2024

problem: you don't want concurrent ps script calls but you don't want "PowerShell Inception" with promises returning promises returning promises programatically.

I made a demo about the problem here:
https://github.com/BenjaminMichael/node-powershell-electron-basic-demo

here's an excerpt:

// node-powershell commands in sequence

      $('#test1Btn').click( () => {
        loading()
        let i=0
        let max=testData.length
        let runningTotal=0;
        let ps = new shell({
            executionPolicy: 'Bypass',
            noProfile: true
            });
        const doPowershell = (val) => {
            ps.addCommand(`write-host ${val}`)
            ps.invoke()
        }
        ps.on('output', output => {
            runningTotal+=parseInt(output)
            $('#resultsGoHere').append(`<div class="chip orange lighten-3 purple-text z-depth-3 text-darken-1 col s2 m2 l2">${output}</div>`)
            if (i<max) {return doPowershell(testData[i++])}else{
                ps.dispose()
                $('#myH3').html('<h2>Done.</h2>')
                $('#resultsGoHere').append(`<div class="chip orange lighten-3 purple-text z-depth-3 text-darken-1 col s2 m2 l2">total:${runningTotal}</div>`)
            }
        })
        doPowershell(testData[i++])
    })

and here is a more advanced example from an intermediate tutorial I am working on... this is the fastest and lowest memory hogging way to do it because I'm only using 1 PowerShell Console not opening and closing consoles.

//...
//iterate through all the groups to check effective access
    let max = adGroupDNsToRem.length;
    let psChain = new powershell({
        executionPolicy: 'Bypass',
        noProfile: true
        });
    const doPowerShell = (i) => {
        let adg = adGroupDNsToRem[i],
        cu =  names.currentUser;
        $(`#REM-LED-${i}`).addClass("led-yellow").removeClass("led-blue");
        psChain.addCommand(`./get-effective-access.ps1 -adgroupdn '${adg}' -me ${cu} -i ${i}`);
        psChain.invoke();
        return;
    };
    psChain.on('output', output => {
        const data = JSON.parse(output);
        const elementID=$(`#REM-LED-${data.bind_i}`);   
        if(!data.Result.includes("FullControl")){
            elementID.addClass("led-red").removeClass("led-yellow");
        }else{
            elementID.addClass("led-green").removeClass("led-yellow");
            $(`#REM-ADGroupBtn${data.bind_i}`).slideToggle("slow").click(function(){
                //disable btn immediately so you cant spam it
                $(this).addClass('disabled pulse');
                _remGroup(data.targetGroupName, names.user1DN, data.bind_i);
                });
            }
        if (data.bind_i<max-1){let i = data.bind_i+1;return doPowerShell(i);}else{psChain.dispose();return;};
        });
        psChain.on('err', err => {
            $('#redMessageBar').html(err);
    });
    doPowerShell(0);

//...

from child-shell.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.