Execute remote commands using powershell

      No Comments on Execute remote commands using powershell

How many times we want to bulk update a registry key, copy/remove files and so on? Pretty often right?
Sure you can create a GPO to do it, but if its a one time thing then you can probably get away with Powershell

The answer is Invoke-Command. Just to give you a quick example on how easy it is, have a look below:

Invoke-Command -ComputerName TargetComputer -ScriptBlock {
New-Item -Path "HKLM:\SYSTEM\CurrentControlSet\services\pvscsi\Parameters\Device"Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\services\pvscsi\Parameters\Device" -name DriverParameter -value "RequestRingPages=32,MaxQueueDepth=254" | Out-Null
}

So what am I doing here? Well i’m changing the registry of computer TargetComputer and i’m doing it remotely.
To a single computer you might ask, why do i need this? But lets say we are talking about 10? or 100? It will take you the exact same amount of time to execute 🙂

To apply it to a list of computers you can iterate through it, or, if in a virtualized environment this can be done directly from a vcenter with get-vm or get-view -ViewType VirtualMachine

Suppose we are in a virtualized environment (I work for VMware after all:) ) and I wanted to apply the above setting to all SQL servers we have.
I could potentially connect to all my vcenter servers and do the following (depending on naming convention you may need to adjust it)

$sqlServers = Get-view -ViewType VirtualMachine |where {$_.name -like '*SQL*'}
foreach ($server in $sqlServers) {
Invoke-Command -ComputerName $server -ScriptBlock {
New-Item -Path "HKLM:\SYSTEM\CurrentControlSet\services\pvscsi\Parameters\Device"Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\services\pvscsi\Parameters\Device" -name DriverParameter -value "RequestRingPages=32,MaxQueueDepth=254" | Out-Null
}
}

And voilá! My Paravirtual disk controller settings are now updated on all my sql server vms!
Note: This is a very simple example, using invoke-command you can run full scripts within the scriptblock or even PS1 files, sky is the limit!!!

More on invoke-command here

Leave a Reply

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