有一个批处理文件调用了一个PowerShell脚本,我已经在Windows启动文件夹中创建了一个指向该批处理文件的快捷方式,因此每次Windows启动时都会运行PowerShell脚本。我想知道我的PowerShell脚本如何在运行时检测它是否是由批处理文件在Windows启动事件期间调用的,还是由用户手动运行批处理文件调用的。
有一个批处理文件调用了一个PowerShell脚本,我已经在Windows启动文件夹中创建了一个指向该批处理文件的快捷方式,因此每次Windows启动时都会运行PowerShell脚本。我想知道我的PowerShell脚本如何在运行时检测它是否是由批处理文件在Windows启动事件期间调用的,还是由用户手动运行批处理文件调用的。
@echo off
if "%1"=="1" (
echo Hey I'm running at startup
)
echo
行替换为你想要运行的命令,如果批处理文件是从启动快捷方式运行的。试试这个:
@echo off
wmic startup get command | find "%~f0" >nul && (
echo I am running at startup!
)
它使用wmi类Win32_StartupCommand(在wmic中别名为startup
)来检查bat文件是否在启动时运行。
# 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"
}
%1
中的值无法在call
过程中保留。如果您需要在call
内部使用%1
的值,则需要首先将其设置为您选择的变量,然后再使用该变量。也就是说,执行set var1=%1
。 - Durry42