简体   繁体   中英

how do i execute a statement in batch /powershell just once?

I want to know how to execute a set of statements or a command in a Windows Batch file or PowerShell script to be executed just once . Even if I run the script multiple times, that particular set of code or program should just run once.

If possible give an example for both Batch files and PowerShell.

In both cases you need to make changes that (a) persist beyond running the batch file or PowerShell script and (b) are visible when you start it the next time. What those changes are would depend on how cluttered you want to leave the system.

One option would be an environment variable. You can set those from batch files with setx or from PowerShell with [Environment]::SetEnvironmentVariable . You should also set them normally to have them in the current session, just to make sure that it can't be called from that session again, too.

if defined AlreadyRun (
  echo This script ran already
  goto :eof
)
...
setx AlreadyRun 1
set AlreadyRun 1

or

if (Test-Path Env:\AlreadyRun) {
  Write-Host This script ran already
  exit
}
...
[Environment]::SetEnvironmentVariable('AlreadyRun', '1', [EnvironmentVariableTarget]::User)
'1' > Env:\AlreadyRun

This approach has its drawbacks, though. For example, it won't prevent you from running the same script twice in different processes that both existed at the time the script ran first. This is because environment variables are populated on process start-up and thus even the system-wide change only applies to new processes, not to those already running.

Another option would be a file you check for existence. This has the benefit of working even under the scenario outlined above that fails with environment variables. On the other hand, a file might be accidentally deleted easier than an environment variable.

However, since I believe your batch file or PowerShell script should do something, ie have a side-effect, you should probably use exactly that as your criterion for abort. That is, if the side-effect is visible somehow. Eg if you are changing some system setting or creating a bunch of output files, etc. you can just check if the change has already been made or whether the files are already there.

A probably very safe option is to delete or rename the batch file / PowerShell script at the end of its first run. Or at least change the extension to something that won't be executed easily.

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