Home > Enterprise >  Powershell invoke-computer to a remote that survives a reboot of my local computer?
Powershell invoke-computer to a remote that survives a reboot of my local computer?

Time:11-03

Is there a way to "invoke-command" to a remote computer such that I can reboot my computer and the job will still be running, and I can check the output log whenever I want?

    PS> invoke-command -Computer Remote1 -File "ScriptThatRunsFor7days.ps1"
    PS> restart-computer
    PS> # Hey where's my job on remote computer?  Can i see it running and connect to
        # its output after rebooting my computer?

CodePudding user response:

Isn't it easier to just register a scheduled task that runs the script on the remote computer? For logging just use the cmdlet Start-Transcript at the top of the script. I made a script not to long ago to easely register scheduled tasks on a remote computer. Maybe you can try out and see if it works for you?

[CmdletBinding()]
param(
    [parameter(Mandatory=$true)]
    [string]
    $PSFilePath,

    [parameter(Mandatory=$true)]
    [string]
    $TaskName,

    [parameter(Mandatory=$true)]
    [string]
    $ComputerName
)

$VerbosePreference="Continue"

New-Variable -Name ScriptDestinationFolder -Value "Windows\PowershellScripts" -Option Constant -Scope Script

New-Variable -Name ScriptSourcePath -Value $PSFilePath -Option Constant -Scope Script
Write-Verbose "Script sourcepath: $ScriptSourcePath"

New-Variable -Name PSTaskName -Value $TaskName -Option Constant -Scope Script
Write-Verbose "TaskName: $TaskName"

$File = Split-Path $ScriptSourcePath -leaf
Write-Verbose "Filename: $File"
New-Variable -Name PSFileName -Value $File -Option Constant -Scope Script
Write-Verbose "PSFileName: $PSFileName"

$ExecutionTime = New-TimeSpan -Hours 8
Write-Verbose "Execution time: $ExecutionTime hours"

Invoke-Command -ComputerName $ComputerName -ScriptBlock {
    $VerbosePreference="Continue"        
    #Removing old Scheduled Task 
    Write-Verbose "Unregistering old scheduled task.."
    Stop-ScheduledTask -TaskName $Using:PSTaskName -ErrorAction SilentlyContinue
    Unregister-ScheduledTask -TaskName $Using:PSTaskName -Confirm:$false -ErrorAction SilentlyContinue


     #Creating destination directory for Powershell script
     $PSFolderPath = "C:" , $Using:ScriptDestinationFolder -join "\"
     Write-Verbose "Creating folder for script file on client: $PSFolderPath"
     New-Item -Path $PSFolderPath -ItemType Directory -Force

     #Scheduled Task definitions
    
     $Trigger = New-ScheduledTaskTrigger -Daily -At "8am" 
     $PSFilePath = "C:", $Using:ScriptDestinationFolder , $Using:PSFileName -join "\"  
     Write-Verbose "Setting path for script file to destination folder on client: $PSFilePath"
     $Action = New-ScheduledTaskAction -Execute PowerShell -Argument "-File $PSFilePath"
     $Principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType S4U
     $Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -DontStopOnIdleEnd -ExecutionTimeLimit $Using:ExecutionTime -StartWhenAvailable
     $Task = Register-ScheduledTask -TaskName $Using:PSTaskName -Principal $Principal -Action $Action -Settings $Settings -Trigger $Trigger
     $Task = Get-ScheduledTask -TaskName $Using:PSTaskName   
     $Task.Triggers[0].EndBoundary = [DateTime]::Now.AddDays(90).ToString("yyyyMMdd'T'HH:mm:ssZ") 
     Write-Verbose "Trigger expiration date set to: $Task.Triggers[0].EndBoundary"
     $Task.Settings.DeleteExpiredTaskAfter = 'P1D'
     Write-Verbose "Scheduled task will be deleted after $Task.Settings.DeleteExpiredTaskAfter after expiry."     
     $Task | Set-ScheduledTask -ErrorAction SilentlyContinue

 } #End Invoke-Command

#Copy script file from source to the computer
$ScriptDestination = "\" , $ComputerName , "C$",  $ScriptDestinationFolder  -join "\"
Write-Verbose "Script destination is set to: $ScriptDestination"

Write-Verbose "Copying script file: `"$ScriptSourcePath`" to `"$ScriptDestination`""
Copy-Item -Path $ScriptSourcePath -Destination $ScriptDestination -Force

Usage:

Create-ScheduledTask-Test.ps1 -ComputerName MyRemoteComputer -PSFilePath "ScriptToRun.ps1" -TaskName DoSomeWork

CodePudding user response:

Something with scheduled jobs. I'm copying the script to the remote computer using a pssession.

$s = new-pssession remote1
copy-item script.ps1 c:\users\admin\documents -tosession $s
invoke-command $s { Register-ScheduledJob test script.ps1 -Runnow }

And then later, only when it starts running, it will automatically appear as a regular job on the remote computer:

invoke-command remote1 { get-job | receive-job -keep }
  • Related