首页 > 解决方案 > RunOnce 在启动时未运行

问题描述

我的启动脚本在重新启动时没有运行,这有问题。

我试图让我的系统执行一堆脚本,但在每个脚本运行后重新启动,等等。这个脚本将设置注册表项,但在它自动登录后,powershell 根本不运行。

#Sets Autologin for scripts
$RegPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion \Winlogon"
$DefaultUsername = Read-Host -Prompt "User's O365 Cred"
$DefaultPassword = Read-Host -Prompt "User's O365 Pass"
Set-ItemProperty $RegPath "AutoAdminLogon" -Value "1" -type String
Set-ItemProperty $RegPath "DefaultUsername" -Value "$DefaultUsername" -type String
Set-ItemProperty $RegPath "DefaultPassword" -Value "$DefaultPassword" -type String


#Reboots and starts next script
$RunOnceKey = "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
set-itemproperty $RunOnceKey "NextRun" ('C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe  -File ' + "~\Downloads\systemrename.ps1")
Start-Sleep 10
Restart-Computer

提前致谢!!

标签: powershell

解决方案


通过计划任务的替代解决方案:

## Create the action
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-Command "c:\temp\systemrename.ps1"'

## Set to run as local system, No need to store Credentials!!!
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest

## set to run at startup could also do -AtLogOn for the trigger
$trigger = New-ScheduledTaskTrigger -AtStartup

## register it (save it) and it will show up in default folder of task scheduler.
Register-ScheduledTask -Action $action -TaskName 'mytask' -TaskPath '\' -Principal $principal -Trigger $trigger

请注意,所有这些命令都支持通过 cimsession 进行远程处理,如下所示:

## Create remote cimsession
$cimSession = New-CimSession -ComputerName 'computername'

## Create the action
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-Command "c:\temp\systemrename.ps1"' -CimSession $cimSession

## Set to run as local system, No need to store Credentials!!!
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest -CimSession $cimSession

## set to run at startup could also do -AtLogOn for the trigger
$trigger = New-ScheduledTaskTrigger -AtStartup -CimSession $cimSession

## register it (save it) and it will show up in default folder of task scheduler.
Register-ScheduledTask -Action $action -TaskName 'mytask' -TaskPath '\' -Principal $principal -Trigger $trigger -CimSession $cimSession

## clean up cimsession
Remove-CimSession -CimSession $cimSession

推荐阅读