powershell - 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
提前致谢!!
解决方案
通过计划任务的替代解决方案:
## 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
推荐阅读
- python - 括号和范围中的 Python 变量
- powerbi - 将 SQL 查询转换为 power bi 中使用的 DAX 查询,以查找具有特定 ID 的最大日期的行
- laravel - 控制器中的模态问题
- firebase - Firebase 数据库规则如何过滤数据
- python - Dragonfly 不打印需要按 Alt Gr 的字符,例如 { 或 [
- javascript - 如何在 jQuery 包含选择器中添加多个单词?
- c++ - 矩阵乘法及其转置
- r - r 用于自制函数的梯度提升包装器
- rxjs - 使用 RXJS 延迟每个元素
- java - 在自定义线程中处理 RunTimeException