Running a Powershell script, restarting and then continue to run

后端 未结 2 1131
广开言路
广开言路 2021-01-19 16:13

I\'m just starting out with the very basics of Powershell scripting and am looking at creating a script to one set of instructions then restart and continue running the rest

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-19 16:50

    The most easiest way is already built-in into Windows. There are a bunch of registry keys, which you can use to configure some action that is to be executed once after a reboot.

    For your use case, you probably want to use one of the RunOnce keys. As always, the exhaustive documentation can be found in the MSDN pages, here's the essence of it:

    [...] RunOnce registry keys cause programs to run each time that a user logs on. The data value for a key is a command line. Register programs to run by adding entries of the form description-string=commandline. You can write multiple entries under a key. If more than one program is registered under any particular key, the order in which those programs run is indeterminate.

    The Windows registry includes [...]:

    • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
    • HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce

    By default, the value of a RunOnce key is deleted before the command line is run. You can prefix a RunOnce value name with an exclamation point (!) to defer deletion of the value until after the command runs. Without the exclamation point prefix, if the RunOnce operation fails the associated program will not be asked to run the next time you start the computer.

    By default, these keys are ignored when the computer is started in Safe Mode. The value name of RunOnce keys can be prefixed with an asterisk (*) to force the program to run even in Safe mode.

    So basically the only thing you need to do is to create an entry under that reg key which calls powershell and passes your script as argument.

    set-location HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce
    new-itemproperty . MyKey -propertytype String -value "Powershell c:\temp\myscript.ps1"
    

    Using RunOnce below HKLM would run the script for any user, but requires elevated rights to write the registry entry. In contrast, HKCU is bound to the current user, but does not require additional permissions.

    For reboot, simply call the Windows shutdown command, e.g.

    shutdown /r 
    

提交回复
热议问题