ken_nogi/PAD/Enable-RemoteDesktopAccess.ps1
Kenichiro NOGI 88a402ce0f up
2026-07-10 18:13:30 +09:00

84 lines
2.4 KiB
PowerShell

#requires -Version 5.1
[CmdletBinding(SupportsShouldProcess = $true)]
param()
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
function Ensure-RegistryKey {
param(
[Parameter(Mandatory)] [string]$Path
)
if (-not (Test-Path -LiteralPath $Path)) {
if ($PSCmdlet.ShouldProcess($Path, 'Create registry key')) {
New-Item -Path $Path -Force | Out-Null
}
}
}
function Set-RegistryDword {
param(
[Parameter(Mandatory)] [string]$Path,
[Parameter(Mandatory)] [string]$Name,
[Parameter(Mandatory)] [int]$Value
)
Ensure-RegistryKey -Path $Path
$current = $null
try {
$current = (Get-ItemProperty -LiteralPath $Path -Name $Name -ErrorAction Stop).$Name
}
catch {
$current = $null
}
if ($current -ne $Value) {
$target = "$Path\\$Name"
if ($PSCmdlet.ShouldProcess($target, "Set DWORD to $Value")) {
New-ItemProperty -LiteralPath $Path -Name $Name -Value $Value -PropertyType DWord -Force | Out-Null
}
}
}
$terminalServerKey = 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server'
$rdpTcpKey = 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp'
# fDenyTSConnections: 0 = allow RDP connections
Set-RegistryDword -Path $terminalServerKey -Name 'fDenyTSConnections' -Value 0
# Keep NLA enabled as secure default
Set-RegistryDword -Path $rdpTcpKey -Name 'UserAuthentication' -Value 1
if ($PSCmdlet.ShouldProcess('Remote Desktop firewall rules', 'Enable inbound rules')) {
try {
Get-NetFirewallRule -Group '@FirewallAPI.dll,-28752' -ErrorAction Stop | Enable-NetFirewallRule -ErrorAction Stop | Out-Null
}
catch {
& netsh advfirewall firewall set rule group='remote desktop' new enable=Yes | Out-Null
if ($LASTEXITCODE -ne 0) {
throw 'Failed to enable Remote Desktop firewall rules.'
}
}
}
if ($PSCmdlet.ShouldProcess('TermService', 'Set startup type and start service')) {
try {
Set-Service -Name 'TermService' -StartupType Manual -ErrorAction Stop
}
catch {
Write-Warning ("Failed to change TermService startup type: {0}" -f $_.Exception.Message)
}
try {
Start-Service -Name 'TermService' -ErrorAction Stop
}
catch {
Write-Warning ("Failed to start TermService: {0}" -f $_.Exception.Message)
}
}
Write-Host 'Remote Desktop settings have been applied.' -ForegroundColor Green