Wednesday 15 January 2020

PowerShell Script to execute command on multiple Servers

PowerShell Script to execute same command and get some information from multiple servers:

PS Script to run remotely on multiple servers:

#path of the text file with the list of all the servers

$path = C:\PSScripts\serverslist.txt
$computers = Get-Content -Path $path

$software = "SQL Server*";
$installed = (Get-Service | Where-Object {$_.DisplayName -like $software}) -ne $null

#Another way is to use like below
#$computers = @("Server1",”Server2”,Server3)

#Can also ask\save for credential who have access on all servers before execution
#$Cred = Get-Credential # Add Credentials for all Servers (Domain or non-Domain)
  

# Run Command 

foreach($computer in $computers){
 Write-Host "Running process on $computer" -ForegroundColor green

    
if (Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue)
    {

#With $cred option
#Invoke-Command -ComputerName $computer -ScriptBlock `
#{Get-WmiObject -Class Win32_Volume -EA silentlyContinue | `
#Select-Object $env:computername,Name,Label,BlockSize | Format-Table -AutoSize} -Credential $cred

 #Without $cred option
         Invoke-Command -ComputerName $computer -ScriptBlock `
         {Get-WmiObject -Class Win32_Volume -EA silentlyContinue | `
          Select-Object $env:computername,Name,Label,BlockSize | Format-Table -AutoSize}
                    

#additional check on running particular script on SQL Server
             If(-Not $installed) { Write-Host "'$software' is not installed." }
             else { Invoke-Sqlcmd -InputFile `
                    "C:\PSScripts\TempDBValidation.sql" -ServerInstance $computer}


    }
else{ Write-Host "$computer Server is not accessiable" -ForegroundColor red }

#For loop end
}
Save the script as ".ps1" extension.

Ways to execute the script and capture output in text\csv file :
1. Open PowerShell as admin mode
2. Go to path where ".ps1" file is saved.
3. Two ways to execute-
Simple way to execute & output on PowerShell console:
.\Remote_PS-Script.ps1

Capture Output in csv:
.\Remote_PS-Script.ps1 | `
Out-File -FilePath C:\output\PS_Script-$(Get-Date -format yyyyMMdd_hhmmsstt).csv -Append

No comments:

Post a Comment