6

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
1
  • Please copy and paste your error message
    – vrdse
    Sep 12, 2018 at 15:51

1 Answer 1

7

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"
}
1
  • The purpose of the New-PSSession was leftover from my attempt to authenticate with the remote machine, kind of like how "net use" works. I also had to add the $gettime and $run variables in there as well, but this worked perfectly for me, thank you. Sep 12, 2018 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.