简体   繁体   中英

Run Scheduled PowerShell script as admin

I create a windows task using admin PowerShell Register-ScheduledJob .

It works fine when calling it directly by doing Start-Job . But the job triggers execute it without elevated permissions. How can I create a task/job on windows ( using admin PowerShell) where the - scheduled script itself - runs as admin too. On Linux imagine: I edit root crontab.

This is what I tried so far, nothing worked for me (popup does not show):

$min = New-TimeSpan -Minute 30
$opts = New-ScheduledJobOption -RunElevated -RequireNetwork
Register-ScheduledJob -Name msaccess_invita_gmbh_hook -ScheduledJobOption $opts
  -RunNow -RunEvery $min -ScriptBlock {
  Start-Process powershell -Verb runAs -ArgumentList
    "Add-Type -AssemblyName PresentationCore,PresentationFramework;
    [System.Windows.MessageBox]::Show('whatup')"
}

Continuing from my comments, here is a full ST creation:

https://duckduckgo.com/?q=powershell+create+scheduled+task+admin+credentials&t=h_&ia=web

Example:

$Action   = New-ScheduledTaskAction -Execute 'C:\Windows\System32\WindowsPowerShellv1.0\powershell.exe' -Argument "-NonInteractive -NoLogo -NoProfile -File 'C:\scripts\PowerShellscript.ps1'" -WorkingDirectory 'C:\scripts'
$Trigger  = New-ScheduledTaskTrigger -RandomDelay (New-TimeSpan -Minutes 5) -AtStartup
$Settings = New-ScheduledTaskSettingsSet -DontStopOnIdleEnd -RestartInterval (New-TimeSpan -Minutes 1) -RestartCount 10 -StartWhenAvailable
$Settings.ExecutionTimeLimit = 'PT0S'

$SecurePassword = $password = Read-Host -AsSecureString
$UserName       = 'svc_account'
$Credentials    = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $SecurePassword
$Password       = $Credentials.GetNetworkCredential().Password

$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Settings
$Task | Register-ScheduledTask -TaskName 'ScheduledTaskName' -User 'svc_account' -Password $Password

Update, as per our comment exchange.

Event with use schtasks.exe, to run with a different identity/creds, you must pass them in on creation.

# Create a task to run at 11 pm every weekday
SCHTASKS /Create /SC weekly /D MON,TUE,WED,THU,FRI /TN MyDailyBackup /ST 23:00 /TR c:\backup.cmd /RU MyDomain\MyLogin /RP MyPassword

If it is to run as the current user, then that is the default.

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