Powershell RunOnce


通过Powershell给计算机进行配置或安装软件之后,需要重启电脑生效。生效后仍然想继续执行脚本进行配置。
需要用到注册表中的RunOnce
位于:HKLM:SOFTWAREMicrosoftWindowsCurrentVersionRunOnce
一旦给该项添加类型为string的子项,内容为某程序的路径。该程序就会使用系统账号开机执行,并且仅执行一次,因为程序执行结束后,该键值会自动清除。

下面的脚本演示:如何使用Powershell脚本多次重启电脑并进行配置。 因为要更改注册表所以需要以管理员权限运行。

$runOncePath="HKLM:SOFTWAREMicrosoftWindowsCurrentVersionRunOnce"
$dir=Split-Path -Parent $MyInvocation.InvocationName
$logFile=$dir + "RunOnceLog.txt"

if($args.Length -eq 0)
{
    "开始配置电脑,可能需要多次重启奥。" >> $logFile
    New-ItemProperty -Path $runOncePath -Name MyScript -PropertyType "string" -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe -File $($MyInvocation.InvocationName) 1"
    Restart-Computer
    return
}

if($args[0] -eq 1)
{
    "第 1 次配置" >> $logFile
    New-ItemProperty -Path $runOncePath -Name MyScript -PropertyType "string" -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe -File $($MyInvocation.InvocationName) 2"
    Restart-Computer
}
elseif($args[0] -eq 2)
{
    "第 2 次配置" >> $logFile
    New-ItemProperty -Path $runOncePath -Name MyScript -PropertyType "string" -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe -File $($MyInvocation.InvocationName) 3"
    Restart-Computer
}
elseif($args[0] -eq 3)
{
    "第 3 次配置" >> $logFile
New-ItemProperty -Path $runOncePath -Name MyScript -PropertyType "string" -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe -File $($MyInvocation.InvocationName) 911"
    Restart-Computer
}
else
{
    "配置完成" >> $logFile
}

三次重启后也会生成日记文件:

开始配置电脑,可能需要多次重启奥。
第 1 次配置
第 2 次配置
第 3 次配置
配置完成

本文链接: https://www.pstips.net/powershell-runonce.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注