Notice: Due to size constraints and loading performance considerations, scripts referenced in blog posts are not attached directly. To request access, please complete the following form: Script Request Form Note: A Google account is required to access the form.
Disclaimer: I do not accept responsibility for any issues arising from scripts being run without adequate understanding. It is the user's responsibility to review and assess any code before execution. More information

Powershell : Run payload remotely (with status)


If you need to run a payload (or script) remotely on a large amount of servers then please do not login to the servers manually and run that script when you can get so much more creative with Powershell.

In the script you will need to define the servers and the payload/script you wish to run remotely this is done in the variables which are shown below in bold, with the script you wish to run on the remote servers you need to ensure append this to the last line of the script, which will tell the script it has terminated successfully

exit 0

Script : ScriptRemoteRun.ps1

$ServerList = @("<server1>", "<server2>")
$ScriptPath = "MyLittlePresent.ps1" # Local path to original script

foreach ($Server in $ServerList) {
    Write-Host "Processing $Server..." -ForegroundColor Cyan   
    try {
        # Copy script to remote server
        Copy-Item -Path $ScriptPath -Destination "\\$Server\C$\Temp\" -Force       

        # Execute remotely
        $result = Invoke-Command -ComputerName $Server -ScriptBlock {
            $output = & "C:\Temp\MyLittlePresent.ps1"
            return @{
                Success = ($LASTEXITCODE -eq 0)
                Output = $output
            }
        }       

        # Report status
        if ($result.Success) {
            Write-Host "✓ $Server - Deployment successful" -ForegroundColor Green
        } else {
            Write-Host "✗ $Server - Deployment failed" -ForegroundColor Red
        }       

        # Clean up
        Remove-Item "\\$Server\C$\Temp\MyLittlePresent.ps1" -Force       
    } catch {
        Write-Host "✗ $Server - Error: $_" -ForegroundColor Red
    }
}

This shows you what the script should look like on a successful deployment of in this case, Microsoft Arc agent, which you can obtain from the agent download filename, as you can see from the verbose log options:


Large Server List : User External File

If you have lots of servers you could always call them from a servers.txt file which will contain a list of server names with no extra characters at the end and one on each line then you can use this:

$ServerList = Get-Content -Path "servers.txt"

Previous Post Next Post

نموذج الاتصال