How to PowerShell and WinRM (Windows Remote Management)

Remoting Powershell

PowerShell supports two types of remote management: first type allows concurrent users to remote into a single server. Second type makes it possible to send out a set of commands or scripts to a group of remote servers at once. This secont type relies on Windows Management Instrumentation (WMI) and Windows Remote Management (WinRM)

The first step to use PowerShell remoting is to enable the remoting feature on the remote box:

Enable-PSRemoting

PowerShell Remoting only works if the network location is set under Home, Work or Domain. If one or more network connections are under the Public network location, enabling PowerShell Remoting will fail.

To execute a cmdlet on a remote computer, you need to use the –ComputerName parameter. Let’s list out the services on the remote machine:

Get-service -ComputerName SRV01

Here another example with cmdlet Invoke-Command

$command = {
	Get-Process |
        Sort-Object WorkingSet -Descending |
        Select-Object -First 1
}

Invoke-Command SRV01,SRV02 $command

Background Job

By default, all cmdlets that are executed runs synchronously, as in, the entire script will be executed and finished on one remote machine, before the next remote machine will execute the script. With background job, the scripts will be executed on all affected remote machines at the same time.

$servers= @("SRV01","SRV02")
Get-Wmiobject Win32_operatingsystem -computername @servers

To execute the cmdlet as a background job, you need to use the –asjob switch:

LGet-Wmiobject Win32_operatingsystem -computername @servers -asjob

To check for on the status of the jobs, we use the cmdlet Get-Job:

Get-Job
Receive-Job -name Job1

Transactional Support

PowerShell 2.0 supports transactions, which allows you to commit or rollback to earlier configurations.

First step is to enable transaction, by running the following:

Start-Transaction

Let’s add a new value into the registry:

New-ItemProperty -path HKCU:Test -name TestTransaction -value "Test value" -useTransaction

–useTransaction tells PowerShell that the command is part of a transaction. Not all the cmdlet support the -UseTransaction switch. Here how to list the cmdlet that support transactions:

$capTransactions = [int][System.Management.Automation.Provider.ProviderCapabilities]::Transactions
Get-PSProvider |
    Where-Object { $_.Capabilities -Band $capTransactions }

To commit or discard, we use the cmdlet:

Complete-Transaction

or

Undo-Transaction
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s