【问题标题】:Creating a scheduled task on a remote machine with powershell使用 powershell 在远程机器上创建计划任务
【发布时间】:2025-12-20 17:20:11
【问题描述】:

我遇到了一个问题,即尝试在我的域中的远程计算机上创建计划任务时出现访问被拒绝错误。奇怪的是,当我在 powershell 中使用“New Remote Powershell Tab”按钮并运行我的代码时,它运行完美。但是,我似乎无法通过正常运行 powershell 脚本来复制它。我有域管理员凭据,我用它来创建与远程机器的会话,但这似乎并不重要。有没有办法复制我在使用远程 powershell 选项时似乎获得的权限?

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

【问题讨论】:

  • 请复制并粘贴您的错误信息

标签: powershell windows-10 scheduled-tasks access-denied


【解决方案1】:

脚本中New-PSSession -ComputerName $hostname -Credential * 的意图是什么?

如果您尝试在远程机器上创建计划任务,请为本地机器创建脚本,一旦它适用于本地机器,然后将其放入 Scriptblock 并使用 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"
}

【讨论】:

  • New-PSSession 的目的是我尝试对远程机器进行身份验证时遗留下来的,有点像“网络使用”的工作方式。我还必须在其中添加 $gettime 和 $run 变量,但这对我来说非常有效,谢谢。
最近更新 更多