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 single command on many servers

 I had a requirement to run a single command on many servers arise, and this requirement was for auditing purposes, back in the day one would connect to all the serer individually, however remote management is amazing....

In this instance I needed to get a list of installed software off a bunch of servers, and save the to a network share with the name of the server as the TXT file, so this is what I did:

$serverlist = Get-Content C:\Source\servers.txt

foreach ($server in $serverlist)
{
$remotesession = New-PSSession -ComputerName $server
Invoke-Command -Session $remotesession {Get-WmiObject Win32_Product | select Name,Version > \\bear.local\CMD-Output\%computername%.txt}

However if you wanted to run a PowerShell script on the remote servers, rather than the command you could do this:

$servers = Get-Content "C:\Source\servers.txt"

foreach ($server in $servers) {
Invoke-Command -ComputerName $server -Filepath C:\RemoteCommand\RemoteCommand.ps1
}

Then set the contents of remotecommand.ps1 to this:

Get-WmiObject Win32_Product | select Name,Version > \\bear.local\CMD-Output\%computername%.txt

If you wanted the date with this as well as the computer name you could do this:

Get-WmiObject Win32_Product | select Name,Version > \\bear.local\CMD-Output\%computername%-%date%.txt

Previous Post Next Post

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