Posted On October 15, 2021

Invoke Commands on Remote Computers [To Install Applications]

kimconnect 0 comments
blog.KimConnect.com >> Codes >> Invoke Commands on Remote Computers [To Install Applications]
$computers=@(
    'pc1',
    'pc2'
)
$commandString="choco install pgadmin4 -y --ignore-checksums"

function invokeCommand{
    param(
        $computers,
        $commandString,
        $credentials
        )
    $command={
        param($commandString);
        write-host $env:computername;
        invoke-expression $commandString;    
    }
    foreach ($computer in $computers){
        try{
            $session=if($credentials){New-PSSession -ComputerName $computer}else{New-PSSession -ComputerName $computer -Credential $credentials}
            if($session.state -eq 'Opened'){
                invoke-command -session $session -scriptblock $command -Args $commandString
            Remove-PSSession $session
            }else{
                write-warning "Cannot connect to $computer"
            }
        }catch{
            write-warning $_
        }}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

PowerShell: Adding a New Domain Controller

Error when trying to run DCPROMO on a Windows 2019 Server: ---------------------------Active Directory Domain Services…

Microsoft Dynamics Email Router Failed to Start

Symptoms Event Log: Item 1: highest correlating event ID 26234 #26234 - The Email Router…

PowerShell: Legacy Methods to Save Credentials

PowerShell version 7 or later may already have facilities to store and retrieve credentials without…
Other project: DragonCoin.com