简体   繁体   中英

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.

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 .

Eg 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.

Plan A: Is remove the option from the user. Start the .bat file from their run key.

HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run

Plan B: could be used if your needs are complex.

# The time the script was ran
$runtime = get-date

# Starts when the user logs on
$LogonTime = (Get-Process explorer)[0].starttime

$differenceTime = New-TimeSpan -Start $logontime -End $runtime

If ($differenceTime.TotalMinutes -lt 1) {
    White-host "$env:USERNAME did not run it"
}
Else {
    Write-host "$env:USERNAME did run it"
}

Try this:

@echo off
wmic startup get command | find "%~f0" >nul && (
  echo I am running at startup!
)

It uses wmi class Win32_StartupCommand (in wmic aliased startup to check if the bat file was running at startup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM