Skip to content

Instantly share code, notes, and snippets.

@psrdrgz
Created March 29, 2018 01:54
Show Gist options
  • Save psrdrgz/fd41275f7db873e8c2dfd62a7a60c08d to your computer and use it in GitHub Desktop.
Save psrdrgz/fd41275f7db873e8c2dfd62a7a60c08d to your computer and use it in GitHub Desktop.
function Enable-RemotePSRemoting
{
[cmdletbinding()]
Param(
[Parameter(Mandatory = $True,Position = 0,ValueFromPipelineByPropertyName = $True)]
[string[]]$ComputerName,
[Parameter(Mandatory = $False)]
[switch]$Force,
[Parameter(Mandatory = $False)]
[pscredential]$Credential = $null
)
Begin{
$InvokeArgs = @{
Path = 'win32_process'
Name = 'Create'
ArgumentList = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -Command Enable-PSRemoting -Force'
ErrorAction = 'Stop'
}
$TestWsmanArgs = @{
ErrorAction = 'SilentlyContinue'
ErrorVariable = 'NoWsmanResponse'
}
If($null -ne $Credential)
{
$InvokeArgs.Credential = $TestWsmanArgs.Credential = $Credential
}
}
Process{
Foreach($Computer in $ComputerName)
{
If(-not (Test-Connection -ComputerName $Computer -Quiet -Count 1))
{
Write-Warning -Message "Cannot connect to $Computer. Verify that the computer exists on the network and that the name provided is spelled correctly."
Continue
}
$Response = Test-WSMan @TestWsmanArgs -ComputerName $Computer
If($Response -and -not $Force)
{
Write-Verbose -Message "[$Computer] PSRemoting is already enabled."
Continue
}
Write-Verbose -Message "[$Computer] Enabling PSRemoting ..."
Try
{
$null = Invoke-WmiMethod @InvokeArgs -ComputerName $Computer
}
Catch
{
Write-Warning -Message "[$Computer] Unable to create remote process. $($_.Exception.Message)"
Continue
}
$Timer = [System.Diagnostics.Stopwatch]::StartNew()
$WSManEnabled = $null
do
{
$WSManEnabled = Test-WSMan @TestWsmanArgs -ComputerName $Computer
}
until($WSManEnabled -or $Timer.Elapsed.TotalMinutes -gt 1)
If($WSManEnabled)
{
Write-Verbose -Message "[$Computer] PSRemoting enabled successfully."
}
Else
{
Write-Warning -Message "[$Computer] Failure. PSRemoting not enabled."
}
}
}
End{}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment