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

Kubernetes: Cert-Manager Certificate Request YAML Example

# Set variables certPrefix=kimconnect domainName=kimconnect.com domainName2=www.kimconnect.com serviceName=kimconnectblog-wordpress servicePort=8080 # Create a yaml file and create…

PowerShell: Get Terminal Service (Remote Desktop Service) Licenses Report

# rdsLicenseReport.ps1 $knownRdsComputers=$null # Options: (a) 'SERVER1','SERVER100' (b) Get-Content Path\To\RDServers.txt function getTsLicenses{ param( $knownRdsComputers, $domain=$env:userdnsdomain…

PowerShell: connectWinRM Function to Create New-PSSession

This reusable function may be included into PoSh scripts for better connection toward Windows machines…
Other project: DragonCoin.com