Top
JohnKlann / windows

Basic Powershell DNS Enumeration Module

This one will allow you too enumerate dns and filter by exclusion or inclusion of different record types.

<# 
    .SYNOPSIS simplifies dns enum and record type filtering 
    .EXAMPLE Ex1: (use default zone and server, return all records found) .\Get-DNSEnum.ps1 or 
            Ex2: (specifiy zone and server, return all except SVR and NS Records) .\Get-DNSEnum.ps1 -Zone domain.local -dc DomainControllerName -Exlcude 'SVR','NS' 
    .DESCRIPTION Detailed Syntax: .\Get-DNSEnum.ps -[Zone|z] dnszone -[Domain|dc] dns or domaincontroller -[ExcludeList|e] 'record','type(s)','to','exclude' -[IncludeList|i] 'record','type(s)','to','include' 
    .NOTES Author: John Klann 
#>
[cmdletbinding()]
Param
(
    [Parameter(Mandatory=$False, HelpMessage='Dns Zone aka domain' )]
    [Alias('z')]
    [string]$Zone = 'default zone / domain',
    [Parameter(Mandatory=$False, HelpMessage='Domain Controller')]
    [Alias('dc')]
    [string]$Domain = 'default domain controller',
    [Parameter(Mandatory=$False, HelpMessage='Record Type Include list')]
    [Alias('i')]
    [string[]]$IncludeList,
    [Parameter(Mandatory=$False, HelpMessage='Record Type Exclude List')]
    [Alias('e')]
    [string[]]$ExcludeList
)

if ($ExcludeList.Count -gt 0)
{
    Get-DnsServerResourceRecord -ZoneName $Zone -ComputerName $Domain | Where-Object { $_.RecordType -notin $ExcludeList }
}
elseif ($IncludeList.Count -gt 0)
{
    Get-DnsServerResourceRecord -ZoneName $Zone -ComputerName $Domain | Where-Object { $_.RecordType -in $IncludeList }
}
else
{
    Get-DnsServerResourceRecord -ZoneName $Zone -ComputerName $Domain
}

 

jklann

How to Set Environment Path Variables

Yay another powershell tip. Super useful and you could script it out if you want to carry around your custom environment paths and install them on any windows machine.

Admin PowerShell Prompt:

  1. Command Syntax:
     $pathtext=Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name "Path" | %{$_.Path}
    $pathtext+=";c:\your\new\path\"
    Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name "Path" -Value "$pathtext" 
  2. Example adding Cygwin bin directory:
     $pathtext=Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name "Path" | %{$_.Path}
    $pathtext+=";c:\dev\cyg\bin\" 
    Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name "Path" -Value "$pathtext" 
  3. Output:
  4. windows_powershell_ps_setting_windows_environment_path
  5. Logoff and Back in for it to take effect.
    shutdown /l

 

jklann

How to get and set a registry key using powershell

Hi Just a quick blurb on how to get and set registry values with powershell:

  1. Command Syntax:
    Set-ItemProperty -Path "Hive:KeyPath" -Name "DWORD or what not to change" -Value "value to set it to"
  2. Example to Set the Cygwin root directory:
    Set-ItemProperty -Path "HKLM:\SOFTWARE\Cygwin\setup" -Name "rootdir" -Value "c:\dev\cyg"
  3. Example to Get the Cygwin root directory:
    Get-ItemProperty -Path "HKLM:\SOFTWARE\Cygwin\setup" -Name "rootdir" | %{$_.rootdir}
  4. Output:
    windows_powershell_ps_get_registrykey_value

 

jklann

How to Forward Ports and Use Port Proxies

So I came across a need to Forward a port from one windows machine to another windows machine and found a nice solution using netsh and port proxies. In this example I will use port proxies to forward a Remote Desktop Port  3389 (RDP)  from one  server to another to allow access to this  server via RDP by connecting to a local port like localhost:5000.

  1. Create the Port Proxy
    1. Open Admin Command Prompt:
      netsh interface portproxy add v4tov4 listenport=freeport listenaddress=localip connectport=rdpport(default rdp is 3389) connectaddress=remoteip 
    2. Example:
      netsh interface portproxy add v4tov4 listenport=5000 listenaddress=192.168.1.25 connectport=3389 connectaddress=192.269.1.57
  2. Create the Firewall Rule:
    1. You will need to choose a local port that is not in use. If  you need to know how to check if a port is in use check out my Quick Tip Post on how to do that here: How to check if a port is in Use and What Process is running on it
    2. Command:
      netsh advfirewall firewall add rule name="Custom Port Rule" dir={in |out} action={allow | block} localport={number| n-n} protocol={TCP | UDP} remoteip={any | ip | range} profile={any | domain | public | private }

      Example:

      netsh advfirewall firewall add rule name="Custom Port Forward 5000" dir=in action=allow localport=5000 protocol=TCP remoteip=any profile="Domain"
  3. Output:

Windows_command_prompt_cmd_add_firewall_rule

  • Use the Port Proxy:
    1. Syntax:
       {localhost | ip or hostname you created the rule on}:{port number you chose} 
    2. Example:
       mstsc locahost:5000 /admin 
  • Delete the Port Proxy:
    1. Syntax:
      netsh interface portproxy delete v4tov4 listenport=portyouchose listenaddress=localip
      Example:
      
      
      
      netsh interface portproxy delete v4tov4 listenport=5000 listenaddress=192.168.1.25
  • Delete the Firewall Rule:
    1.  Syntax:
      netsh advfirewall firewall delete rule name="firewall rule name"
    2. Example:
      netsh advfirewall firewall delete rule name="Custom Port Forward 5000"
    3. Output:

Windows_command_prompt_cmd_delete_firewall_rule

jklann

How to check if a port is in Use and What Process is running on it

So really simple way to check if a port is in use and by what process.

  1. Method 1 CMD:
  2. Open Admin Command Prompt:
    netstat -ano | findstr "portnumber"
    

     

  3. Example using default rdp port:
    netstat -ano | findstr "3389"
    
  4. Output:
    windows_command_prompt_netstat_ano_rdp_port

 

Method 2 PowerShell:

  1. Open Admin PowerShell Prompt:
    1. Command:
      &amp;nbsp;netstat -ano | findstr "portnumber" | Select-String -Pattern "\d+$" -AllMatches | % {$_.Matches } | foreach { tasklist |select-string -Pattern $_.Value } | Get-Unique
      
    2. Example using port 80:
      1. Note: this could probably be a lot cleaner but hey i did it in 5 minutes in 1 oneline :) !
         netstat -ano | findstr "80" | Select-String -Pattern "\d+$" -AllMatches |  % {$_.Matches } | foreach { tasklist |select-string -Pattern $_.Value } | Get-Unique
        
    3. Output:
      windows_powershell_netstat_ano_port_number_tasklist_processname_process_stats

Method 3 CMD with Cygwin:

  1. This will get all of the process running on a particular port.
    1. Note: you will need (Cygwin bin directory pathed in your environment See how to do this here: How to add environment Paths via command line (cmd, powershell) )
      1. Open Admin cmd Prompt:
        1. Command:
           for /f "delims=" %a in ('netstat -ano ^| grep "portnumber" ^| grep -m1 -oP "[\d]{1,6}$"') do @set pid=%a | tasklist | grep %a 
      2. Example using port 80:
         for /f "delims=" %a in ('netstat -ano ^| grep "80" ^| grep -m1 -oP "[\d]{1,6}$"') do @set pid=%a | tasklist | grep %a 
      3. Output:
        windows_command_prompt_cygwin_netstat_ano_grep_port_number_tasklist_processname
jklann

How to add environment Paths via command line (cmd, powershell)

Here’s a quick one lol.

Quick Note: This will temporarily set the Environment path with in that shell. If you want a more permanent solution you will have to added through windows environment variables config then logoff and back in.

  1. In CMD or Powershell prompt Run this command:
    1. Syntax:
       PATH %PATH%;c:\path\you\want\to\add\ 
  2. Example Using Cygwin Bin directory:
     PATH %PATH%;c:\dev\cyg\bin\ 
  3. Output:

windows_command_prompt_cmd_powershell_prompt_ps_set_environement_path

jklann

How to Start a Process as Administrator

So I find this one to be rather useful. I probably use it nearly every day. The syntax is simple the results are powerful. How to start a process as administrator in powershell.

  1. Open Powershell Console (doesn’t need to be admin) or the windows run prompt (win+R):
  2. Use the following Command Syntax to launch a process as admin:
    1. Start-Process ProcessName -Verb runas
  3. Example:
    1. Start-Process Powershell -Verb runas

 

powershell_start_process_as_administrator

jklann

Easily Manage a Service on a Remote Machine

For this example I will use Windows Remote Desktop Services and their ever needing service restart.

  1. Remote Restart Service
    1. Syntax
    2. Get-Service -ComputerName yourremotecomputername -Name servicename | Restart-Service
      
    3. Example (Restart Remote Desktop Services)
    4. Get-Service -ComputerName server1.domain.local -Name TermService | Restart-Service -Force
      
    5. The “-Force” is added to the end as TermSerivce has dependent services and this flag is required to restart TermSerivce as well as its depedencies
  2. From here you can explore other Service commands and options using this base syntax to get the service object on a remote machine.

 

jklann

Postgres How To Get List of Functions Like PGAdmin III

Recently I had the need to get a bunch of object stats and counts of two postgres databases to compare them. The goal was to confirm both via query results as well as visually via PGAdmin III, just in case I missed something in excel :P. Anyways I quickly realized that some of my object counts did not match the UI counts. After a little playing with the query I realized the UI splits the Functions into aggregates, functions, and trigger functions. However by default the UI hides the views for aggregates and trigger functions and you have to manually specify these to be shown in schema tree.

File -> Options
pg_admin_III_file_options

Browser -> Display -> Objects
pg_admin_III_file_options_browser_display_objects

So If you are wanting to get only user functions like the list that is in PGAdmin III under each schema in the function tree. You will want to remember to exclude aggregate functions and trigger functions.

This Query does just that. It gets the count of functions per schema just like displayed in the UI.

select ns.nspname, count(*)
from pg_proc pr
join pg_namespace ns on 
    pr.pronamespace = ns.oid
--Exlcude system schemas
where ns.nspname <> 'pg_catalog' 
    and ns.nspname <> 'information_schema' 
    --Exclude Trigger Functions
    and pr.oid not in 
        (select tgfoid from pg_trigger)
    --Exclude aggregate functions
    and pr.proisagg = 'f'
group by ns.nspname
order by ns.nspname;

This Query Gets a count of Aggregate functions per schema.

select ns.nspname, count(*)
from pg_proc pr
join pg_namespace ns on 
      pr.pronamespace = ns.oid
--Exlcude system schemas
where ns.nspname <> 'pg_catalog' 
    and ns.nspname <> 'information_schema' 
    --Exclude Trigger Functions
    and pr.oid not in 
         (select tgfoid from pg_trigger)
    --include aggregate functions
    and pr.proisagg = 't'
group by ns.nspname
order by ns.nspname

Lastly this Query Gets a count of Trigger functions per schema.

select ns.nspname, count(*)
from pg_proc pr
join pg_namespace ns on 
    pr.pronamespace = ns.oid
--Exlcude system schemas
where ns.nspname <> 'pg_catalog' 
    and ns.nspname <> 'information_schema' 
    --Include Trigger Functions
    and pr.oid in
         (select tgfoid from pg_trigger)
group by ns.nspname
order by ns.nspname

Now you have a set of Function count queries that will match the PGAdmin III UI.

jklann
sqlThemeSmall

SQL Sever Management Studio 2014 Custom Solarized Theme (JK_Solar)

I was looking for a really good SQL Sever Management Studio Solarized theme and I found it rather difficult to find any themes that were created specifically for SQL Sever Management Studio. There are a lot of Visual Studio themes that are out there that you can load but the syntax highlight for TSQL was never great. So I took some colors from a collection of Visual Studio themes and created a custom SQL Sever Management Studio theme specially for TSQL. You can find the download link to the vssettings Theme file below. I haven’t tested this with any other version of SQL Sever Management Studio other than 2014 but I don’t see why it wouldn’t work on earlier versions.

JK_Solar SSMS Theme

JK_Solar SSMS Theme

To import this theme into SSMS follow these steps:

  1. Open the Tools menu and select Import and Export Settings.
  2. Select Import selected environment settings then click Next.
  3. Select a place to backup your current settings.
  4. Select the JK_Solar.vssettings file you downloaded then click Next.
  5. Click Finish and you’re done!

Download Link: JK_Solarized.vssettings Count: 1,561 FileSize: 1.9 kB

Link to Script in Screen Capture: Stack Overflow Script

jklann