如何通过 Windows 启动事件检测调用 powershell 脚本的批处理文件是否为 运行

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

有一个调用 Powershell 脚本的批处理文件,我在 Windows 启动文件夹中创建了该批处理文件的快捷方式,因此每次 Windows Powershell 脚本都会运行启动。我只想知道我的 Powershell 脚本如何在运行时检测到它是在 windows 启动事件期间被批处理文件调用,还是当用户手动 运行 批处理时被批处理文件调用文件。

如果当用户 运行 时他们只会直接 运行 批处理文件而不是通过启动快捷方式,那么您可以设置启动快捷方式以在 运行.

右键单击快捷方式和 select 属性。 在目标字段中,添加 space 然后 1.

例如如果是 "C:\MyDir\MyScript.bat",请将其更改为 "C:\MyDir\MyScript.bat" 1

当你运行这个快捷方式时,它会启动批处理文件,而且还会将变量%1

中的值1传递给批处理文件

接下来,在批处理文件的顶部(或任何您想要的地方)添加以下内容。

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

如果批处理 运行ning 来自启动快捷方式,您可以将 echo 行替换为您想要 运行 的命令。

方案A:移除用户的选项。从他们的 运行 键启动 .bat 文件。

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

方案 B:如果您的需求很复杂,可以使用。

# 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"
}

试试这个:

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

它使用 wmi class Win32_StartupCommand(在 wmic 别名 startup 中检查启动时 bat 文件是否 运行。