Search code examples
windowspowershellbatch-filestartup

How to detect if batch file that calls powershell script was run by Windows startup event or not


There is a batch file that calls a Powershell script, and I've created a shortcut to that batch file inside the Windows startup folder, so the Powershell script runs every time that Windows starts up. I just want to know how my Powershell script can detect at runtime if it was called by the batch file during a windows startup event or if it was called by the batch file when a user manually ran the batch file.


Solution

  • If when run by a user they will only ever run the Batch File directly and not via the startup shortcut, then you could set startup shortcut to pass an argument to the batch on run.

    Right-click the Shortcut and select properties. In the target field, add a space then 1.

    E.g. if it was "C:\MyDir\MyScript.bat", change it to "C:\MyDir\MyScript.bat" 1

    When you run this shortcut it will start the Batch File, but also pass the Batch File the value 1 in the variable %1

    Next, inside your batch file at the top(Or where ever you want it) add the following.

    @echo off
    if "%1"=="1" (
       echo Hey I'm running at startup
    )
    

    You can replace the echo line with the command you want to run if the Batch was running from the startup shortcut.