Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

29.7 Program: Remotely Enable PowerShell Remoting

Although not required for Windows Server by default, you may sometimes need to remotely enable PowerShell Remoting. Unfortunately, most machines are not configured to support remote task management. Most are, however, configured to support WMI connections. As a bootstrapping step, we can use the Create() method of the Win32_Process class to launch an instance of PowerShell, and then provide PowerShell with the commands to enable PowerShell Remoting.

The script shown in Example 29-1 automates this cumbersome process.

Example 29-1. Enable-RemotePSRemoting.ps1
##############################################################################
##
## Enable-RemotePsRemoting
##
## From PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################

<#

.SYNOPSIS

Enables PowerShell Remoting on a remote computer. Requires that the machine
responds to WMI requests, and that its operating system is Windows Vista or
later.

.EXAMPLE

PS > Enable-RemotePsRemoting <Computer>

#>

param(
    ## The computer on which to enable remoting
    $Computername,

    [Switch] $SkipNetworkProfileCheck,

    ## The credential to use when connecting
    [PSCredential] $Credential
)

Set-StrictMode -Version 3

$VerbosePreference = "Continue"

Write-Verbose "Configuring $computername"
$skipNetworkProfileCheckFlag = '$' + $SkipNetworkProfileCheck.IsPresent
$command = "powershell -NoProfile -Command" +
    "Enable-PSRemoting -SkipNetworkProfileCheck:$skipNetworkProfileCheckFlag -Force"

if($Credential)
{
    $null = Invoke-WmiMethod -Computer $computername -Credential $credential `
        Win32_Process Create -Args $command

    Start-Sleep -Seconds 10

    Write-Verbose "Testing connection"
    Invoke-Command $computername {
        Get-WmiObject Win32_ComputerSystem } -Credential $credential
}
else {
    $null = Invoke-WmiMethod -Computer $computername Win32_Process Create -Args $command
    Start-Sleep -Seconds 10

    Write-Verbose "Testing connection"
    Invoke-Command $computername { Get-WmiObject Win32_ComputerSystem }
}

For more information about running scripts, see Recipe 1.2.

See Also

Recipe 1.2, “Run Programs, Scripts, and Existing Tools”

Recipe 28.1, “Access Windows Management Instrumentation and CIM Data”

Recipe 29.2, “Enable PowerShell Remoting on a Computer”