|
| 1 | +Function Get-RemoteRules { |
| 2 | + <# |
| 3 | + .SYNOPSIS |
| 4 | + Retrieve firewall rules from a remote computer using WinRM. |
| 5 | +
|
| 6 | + .DESCRIPTION |
| 7 | + This function retrieves firewall rules from a specified remote computer, it establishes a session, retrieves the firewall rules, and then closes the session. |
| 8 | +
|
| 9 | + .PARAMETER ComputerName |
| 10 | + Mandatory - name of the remote computer from which to retrieve firewall rules. |
| 11 | + .PARAMETER Username |
| 12 | + Mandatory - username used for authentication to the remote computer. |
| 13 | + .PARAMETER Pass |
| 14 | + Mandatory - password associated with the provided username for authentication. |
| 15 | +
|
| 16 | + .EXAMPLE |
| 17 | + Get-RemoteRules -ComputerName 'remote_computer' -Username 'remote_user' -Password 'remote_pass' |
| 18 | +
|
| 19 | + .NOTES |
| 20 | + v0.0.1 |
| 21 | + #> |
| 22 | + param ( |
| 23 | + [Parameter(Mandatory = $true)] |
| 24 | + [string]$ComputerName, |
| 25 | + |
| 26 | + [Parameter(Mandatory = $true)] |
| 27 | + [string]$Username, |
| 28 | + |
| 29 | + [Parameter(Mandatory = $true)] |
| 30 | + [string]$Pass |
| 31 | + ) |
| 32 | + Write-Verbose -Message "Adding client machine to TrustedHosts" |
| 33 | + $CurrentTrustedHosts = Get-Item WSMan:\localhost\Client\TrustedHosts -ErrorAction SilentlyContinue |
| 34 | + if ($null -eq $CurrentTrustedHosts) { |
| 35 | + Set-Item WSMan:\localhost\Client\TrustedHosts -Value $ComputerName -Force |
| 36 | + } |
| 37 | + else { |
| 38 | + $ExistingValue = $CurrentTrustedHosts.Value |
| 39 | + if ($ExistingValue -notlike "*$ComputerName*") { |
| 40 | + Set-Item WSMan:\localhost\Client\TrustedHosts -Value "$ExistingValue,$ComputerName" -Force |
| 41 | + } |
| 42 | + } |
| 43 | + try { |
| 44 | + $SecurePassword = ConvertTo-SecureString $Pass -AsPlainText -Force |
| 45 | + $Credential = New-Object System.Management.Automation.PSCredential ($Username, $SecurePassword) |
| 46 | + $Session = New-PSSession -ComputerName $ComputerName -Credential $Credential |
| 47 | + $FirewallRules = Invoke-Command -Session $Session -ScriptBlock { |
| 48 | + Get-NetFirewallRule | Select-Object DisplayName, Action, Direction, Enabled |
| 49 | + } |
| 50 | + Remove-PSSession -Session $Session |
| 51 | + return $FirewallRules |
| 52 | + } |
| 53 | + finally { |
| 54 | + Write-Verbose -Message "Removing client machine from TrustedHosts" |
| 55 | + $CurrentTrustedHosts = Get-Item WSMan:\localhost\Client\TrustedHosts -ErrorAction SilentlyContinue |
| 56 | + if ($null -ne $CurrentTrustedHosts) { |
| 57 | + $ExistingValue = $CurrentTrustedHosts.Value |
| 58 | + $NewValue = $ExistingValue -replace ",?$ComputerName", "" |
| 59 | + Set-Item WSMan:\localhost\Client\TrustedHosts -Value $NewValue -Force |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments