禁用RDP的脚本

时间:2019-06-04 16:55:38

标签: powershell

我正在尝试使用Powershell禁用RDP。

我尝试了以下代码,但是我列出的计算机名称上的值没有更改。

$file = Get-Content c:\PSscripts\regchange\computers.txt
foreach ($computername in $file){
    $PingStatus = Gwmi Win32_PingStatus -Filter "Address = '$computername'" | Select-Object StatusCode
    If ($PingStatus.StatusCode -eq 0){
        $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computername )
        $regKey= $reg.OpenSubKey("System\\CurrentControlSet\\Control\\Terminal Server" ,$true)
        $regKey.SetValue("fDenyTSConnections","1",[Microsoft.Win32.RegistryValueKind]::dword)
    }
    else {
        Write-Host "$computername unreachable"
    }
}

我怀疑我输入注册表路径名称的方式有问题。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

如果启用了PSRemoting,请尝试以下操作…… (这需要在PowerShell提升的管理员会话中执行。)

Get-Content -Path 'c:\PSscripts\regchange\computers.txt' | 
ForEach{
    If (Test-Connection -$PSItem -Count 1 -Quiet)
    {
        $paramblock = @{
            Path = 'HKLM:\System\CurrentControlSet\Control\Terminal Server'
            Name = 'fDenyTSConnections'
            Value = '1'
        }

        Invoke-Command –Computername $PSItem –ScriptBlock {Set-ItemProperty @paramblock}
    }
    Else
    {Write-Warning -Message "Either the host $PSItem is offline or not reachable."}
}

答案 1 :(得分:1)

问题必须是权限(我认为您具有权限,因为没有明显的错误消息),刷新问题或在Get-Content中以及文件的结构。

为了使Get-Content以这种方式工作,每台计算机都位于单独的行上。例如:

MyComputer1
MyComputer2

另一个故障排除步骤是尝试添加Write-Host $computername条目以验证您是否正确循环通过。:

$file = Get-Content c:\PSscripts\regchange\computers.txt
foreach ($computername in $file){
     $PingStatus = Gwmi Win32_PingStatus -Filter "Address = '$computername'" | Select-Object StatusCode
     If ($PingStatus.StatusCode -eq 0){
         Write-Host "$computername set"
     }
    else {
        Write-Host "$computername unreachable"
    }
}

您还可以通过在设置后添加$regKey.GetValue来确认:

$file = Get-Content c:\PSscripts\regchange\computers.txt
foreach ($computername in $file){
    $PingStatus = Gwmi Win32_PingStatus -Filter "Address = '$computername'" | Select-Object StatusCode
    If ($PingStatus.StatusCode -eq 0){
        $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computername )
        $regKey= $reg.OpenSubKey("System\\CurrentControlSet\\Control\\Terminal Server" ,$true)
        $regKey.SetValue("fDenyTSConnections","1",[Microsoft.Win32.RegistryValueKind]::dword)

        Write-Host "$computername set to: $($regKey.GetValue("fDenyTSConnections"))"

    }
    else {
        Write-Host "$computername unreachable"
    }
}

手动设置$computername = "MyComputer"并运行代码,我可以确认用于设置注册表的代码是否有效...我也可以确认从远程取消对远程虚拟工作站的RDP访问也可以。 ..听起来很可怕;-)