#Spawning

40 messages · Page 1 of 1 (latest)

tardy pollen
#

chat for more specific details. Im building an application for Windows with latest Electron version. No matter what I do, I cannot get my PowerShell script to be triggered and spawn powershell.exe to run the .ps1 file when I initiate it from my Electron app. I've tried at least 4 different methods atp.

modern flint
#

Where are you spawing it ? Is it part of the launch process ?

#

Is it in the electron code, like in app when ready ? How are you trying to spawn it using node spawn ?

tardy pollen
#

trigger:

#

` if (installBtn) {
installBtn.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent event bubbling to overlay

        if (currentInstallAction) {
            closeSidebar();
            // Run the install action
            currentInstallAction();
        }
    });
}

`

#

`
document.addEventListener('click', (e) => {
if (e.target && e.target.id === 'sidebar-install-btn') {
console.log('Install button clicked via event delegation!');
e.stopPropagation();
e.preventDefault();

        const installBtn = document.getElementById('sidebar-install-btn');
        if (installBtn && installBtn.onclick) {

            installBtn.onclick(new MouseEvent('click', { bubbles: false }));
        } else if (window.currentInstallAction) {
            console.log('Running install action via delegation...');
            window.currentInstallAction(true);
        } else {
            console.log('No currentInstallAction found in window!');
        }
    }
});

`

#

logic:

#

`
const softwareInfo = {
'wise': {

    installAction: () => installSoftware('Wise Memory Optimizer')
},

};
`

#

execution:

#

`
async function installSoftware(name) {

const confirmed = await window.api.showConfirm({
    title: `Install ${name}`,
    message: `This will run the PowerShell script to install ${name}.\n\nContinue?`
});

if (!confirmed) return;

try {

    const scriptMap = {
        'Wise Memory Optimizer': 'install_wise_memory_optimizer.ps1',
        'Mozilla Firefox': 'install_firefox.ps1',
        'LibreWolf': 'install_librewolf.ps1',
        'Brave Browser': 'install_brave.ps1',
        'Google Chrome': 'install_chrome.ps1',
        'Tor Browser': 'install_tor.ps1',
        'Bitwarden': 'install_bitwarden.ps1',
        'Proton VPN': 'install_protonvpn.ps1',
        'ClamAV Antivirus': 'install_clamav.ps1',
        'VLC Media Player': 'install_vlc.ps1',
        'VSCodium': 'install_vscodium.ps1',
        '7-Zip': 'install_7zip.ps1'
    };
    
    const scriptFile = scriptMap[name];
    if (!scriptFile) {
        throw new Error(`No installation script found for ${name}`);
    }
    
    const scriptPath = `software/${scriptFile}`;
    

    await window.api.runPowerShellScript(scriptPath);
    

    
} catch (error) {

}

}
`

#

this is the bridge

`

contextBridge.exposeInMainWorld('api', {

runPowerShellScript: (script) => ipcRenderer.invoke('run-powershell-script', script),

});
`

#

sys exec:

#

`
ipcMain.handle('run-powershell-script', async (event, script) => {
console.log('=== run-powershell-script IPC handler called ===');
console.log('Script parameter:', script);

const scriptPath = path.join(__dirname, script);
console.log('Full script path:', scriptPath);

if (!fs.existsSync(scriptPath)) {
    console.error('Script file not found!');
    throw new Error(`Script not found: ${script} at ${scriptPath}`);
}
console.log('Script exists: true');

try {
    console.log(`Attempting to open script with the default OS shell: ${scriptPath}`);

separate window.
const errorMessage = await shell.openPath(scriptPath);
if (errorMessage) {
throw new Error(The OS failed to open the script: ${errorMessage});
}

    console.log('OS has been instructed to open the script.');
    return { success: true, message: 'PowerShell script opened via shell' };

} catch (error) {
    console.error('Error starting PowerShell script:', error);
    throw new Error(`Failed to start PowerShell script: ${error.message}`);
}

});
`

modern flint
tardy pollen
#

Ill dm you it later after I get on break

#

Before I do imma try one last thing to fix it myself

#

By ps2exe and see if spawning individual custom exe's is easier then spawning PS

modern flint
#

Does it have to be a powershell script ?

#

What errors are you getting exactly like is the spawn failing, i.e it cant find the file ? I need a better idea.

#

What is shell ? You call shell.openPath

#

Is it doing something like const child = spawn('powershell.exe', psArgs, { cwd: cwd || path.dirname(resolvedPath), windowsHide: true, env: process.env });

tardy pollen
#

yes

tardy pollen
#

thats what im trying out rn

#

i converted PS files to exe's

#

and see if its any better

modern flint
#

From what im gathering i think the problem is how your spawing the exe's and how your handerling javascript promises of said spawned process

modern flint
#

use a helper like ```/**

  • Runs a PowerShell script

  • @param {string} scriptPath - Path to the .ps1 file

  • @param {string[]} [args] - Arguments to pass to the script

  • @returns {Promise<string>} - Resolves with stdout, rejects on error
    */
    function RunPowerShellScript(scriptPath, args = []) {
    return new Promise((resolve, reject) => {
    let output = '';
    let errorOutput = '';

    const child = spawn('powershell.exe', [
    '-NoProfile',
    '-ExecutionPolicy', 'Bypass',
    '-File', scriptPath,
    ...args
    ], {
    windowsHide: true
    });

    child.stdout.on('data', (data) => {
    output += data;
    });

    child.stderr.on('data', (data) => {
    errorOutput += data;
    });

    child.on('error', reject);

    child.on('close', (code) => {
    if (code !== 0) {
    reject(new Error(errorOutput.trim() || Exit code ${code}));
    } else {
    resolve(output.trim());
    }
    });
    });
    }```

#

use it like ```const { RunPowerShellScript } = require('./RunPowerShellScript');

// Simple
const output = await RunPowerShellScript('C:\script.ps1');
console.log(output);

// With args
await RunPowerShellScript('C:\script.ps1', ['arg1', 'arg2']);```

#

I do somthing similar in my projects but use node js scripts and spawn node to run them

#

Tell me how that goes

#

Make sure to await them in a async function

#

Here is demo you can test via cli make a js file called run_powershell.js add content like ```const { spawn } = require("child_process");
const path = require("path");

/**

  • Runs a PowerShell script

  • @param {string} scriptPath - Path to the .ps1 file

  • @param {string[]} [args] - Arguments to pass to the script

  • @returns {Promise<string>} - Resolves with stdout, rejects on error
    */
    function RunPowerShellScript(scriptPath, args = []) {
    return new Promise((resolve, reject) => {
    let output = "";
    let errorOutput = "";

    const child = spawn(
    "powershell.exe",
    [
    "-NoProfile",
    "-ExecutionPolicy",
    "Bypass",
    "-File",
    scriptPath,
    ...args,
    ],
    {
    windowsHide: true,
    },
    );

    child.stdout.on("data", (data) => {
    output += data;
    });

    child.stderr.on("data", (data) => {
    errorOutput += data;
    });

    child.on("error", reject);

    child.on("close", (code) => {
    if (code !== 0) {
    reject(new Error(errorOutput.trim() || Exit code ${code}));
    } else {
    resolve(output.trim());
    }
    });
    });
    }

async function main() {
const stdout = await RunPowerShellScript(path.normalize("C:\dev\fluf\hello_world.ps1"));
console.log("Finished with ", stdout)
}

main()
Change that path of the powershell script to one on your system and run in the terminalPS C:\dev\fluf> node .\run_powershell.js
Finished with Hello World
PS C:\dev\fluf> ``` Thats runs any powershell script just take these ideas and add it to your electron code

tardy pollen
#

okay thank u i will try it out

tardy pollen
modern flint
tardy pollen