Skip to content

Invoke Command

Joe Workman edited this page Jun 22, 2020 · 9 revisions

Below is an example of how invoke-command can be used against a group of offline and online systems with psremoting enabled. When it is ran the 'scriptblock' is run locally on each machine as a disconnected session. This sessions results can then be collected and returned. This framework will be used later to run and collect results from the ADMU, when ran from an input csv or other object.

  • C:\Windows\Temp\online_computer_results.txt, the systems that were online with the returned results
  • C:\Windows\Temp\offline_computer_results.txt, the systems that are offline when the script is ran or can't be resolved by DNS.
$Computers = ('10ent17091', '10ent18031', '10ent18091', '10pro17091', '10pro18031', '7pro1')
$ScriptBlock = {
    $teststring = $env:computername + ' ' + $true
    return $teststring
    #import-module '\\JCADB2DC1\ADMU\Functions.ps1'; AgentIsOnFileSystem
    #unblock-file c:\jcadmu\powershell\Functions.ps1; cd c:\jcadmu\powershell\ ; import-module .\Functions.ps1; Start-Migration -DomainUserName 'john.wick' -JumpCloudUserName 'jwick4' -TempPassword 'Temp123!' -JumpCloudConnectKey 'JC-CONNECTKEY' -AcceptEULA $true -InstallJCAgent $true -LeaveDomain $true -ForceReboot $true -AZureADProfile $false
}
$ConnectionTest = $Computers | ForEach-Object {
    Test-NetConnection -ComputerName:($_) -WarningAction:('SilentlyContinue')
}

$OnlineComputers = $ConnectionTest | Where-Object { $_.PingSucceeded }
$OfflineComputers = $ConnectionTest | Where-Object { -not $_.PingSucceeded }
If (-not [System.String]::IsNullOrEmpty($OfflineComputers))
{
    $OfflineComputers | ForEach-Object { Write-Warning ('Computer is offline: ' + $_.ComputerName.ToUpper()) }
}
If (-not [System.String]::IsNullOrEmpty($OnlineComputers))
{
        $SessionOptions = New-PSSessionOption -IdleTimeout:(60000)
        $Command = Invoke-Command -ComputerName:($OnlineComputers.ComputerName) -ScriptBlock:($ScriptBlock) -InDisconnectedSession -SessionOption:($SessionOptions)
        Get-PSSession | ForEach-Object {Receive-PSSession -id  $_.ID} | out-file -FilePath C:\Windows\Temp\online_computer_results.txt
        $OfflineComputers | out-file -FilePath C:\Windows\Temp\offline_computer_results.txt
        $Command | Remove-PSSession  
}

After generating a list of systems, the PowerShell script could be ran against remote systems with the DomainUserName, JumpCloudUserName, TempPassword and JumpCloudConnectKey parameter set populated for each system.