Search code examples
powershellwindows-10scheduled-tasksaccess-denied

Creating a scheduled task on a remote machine with powershell


I have an issue where I get an access denied error when attempting to create a scheduled task on a remote machine on my domain. What is odd is that when I use the "New Remote Powershell Tab" button in powershell and run my code, it runs flawlessly. However I cannot seem to replicate this by running the powershell script normally. I have domain admin credentials which I am using to create a session with the remote machine but that does not seem to matter. Is there a way to replicate the permissions I seem to get when using the remote powershell option?

function Install {
$hostname = Read-Host -Prompt "Enter hostname" 

echo 'Testing connection...'

If(!(Test-Connection -ComputerName $hostname -Count 1 -quiet)){
echo "`n"
echo 'There was an issue connecting to this computer.'
pause
Install
}

echo 'Connection successful!'

Get-Service -Name WinRM -ComputerName $hostname | Start-Service

$cd = Convert-Path .

Copy-Item -Path "$cd\Install.bat" -Destination "\\$hostname\C$\Install.bat"

New-PSSession -ComputerName $hostname -Credential *

$gettime = (Get-Date).AddMinutes(1)
$run = $gettime.ToString('HH:mm')

$action = New-ScheduledTaskAction -Execute 'C:\Test'
$trigger = New-ScheduledTaskTrigger -Once -At $run
$principal = New-ScheduledTaskPrincipal -GroupID "BUILTIN\Administrators" -RunLevel Highest

Register-ScheduledTask -Action $action -Trigger $trigger -Principal $principal -TaskName "Install" -Description "Test"

pause
}

Install

Solution

  • What was the intent of New-PSSession -ComputerName $hostname -Credential * in the script ?

    If you are trying to create scheduled tasks on a remote machine, create the script for local machine, once its working for local machine, then put it inside a Scriptblock and invoke using Invoke-Command

    $Credes = Get-Credential
    Invoke-Command -ComputerName $hostname -Credential $Credes -Scriptblock {
        $action = New-ScheduledTaskAction -Execute 'C:\Test'
        $trigger = New-ScheduledTaskTrigger -Once -At $run
        $principal = New-ScheduledTaskPrincipal -GroupID "BUILTIN\Administrators" -RunLevel Highest
    
        Register-ScheduledTask -Action $action -Trigger $trigger -Principal $principal -TaskName "Install" -Description "Test"
    }