Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Friday, 27 December 2024

Terminating a process running on local port using Powershell

Developers who work with frontend and backend often switching between tools get a message that a certain process is holding a port. For example, using the dotnet command, you can get a message that the address is already in use. Note - you usually must decide if you really want to terminate the process running on a certain port, but if you are sure that you just want to close the process and free up the local port for its use, it would be nice to have a way of
just closing the process running on that local port. A typical output would be:

 System.IO.IOException: Failed to bind to address http://127.0.0.1:5000: address already in use.

We can locate which process is using te port, that is, the local port, and then terminate the process. This will free up the local port so we can use it. Here is a Powershell function that will find the process running at a local port, if any, given by a specied port number.


<#
.SYNOPSIS
Stops the process using the specified local port 

.DESCRIPTION
This function finds the process, if any, using the specified port and stops it.
In case there are no process, the function exits.

.PARAMETER portId
The port number to check for the process

.RETURNS int
If successful, returns 0. If not, returns -1.

.EXAMPLE
Terminate-Port -portId 5000
#>
function Terminate-Port {
    param (
        [Parameter(Mandatory = $true)]
        [int]$portId
    )

    # Get the process ID (PID) using the specified port 
    try {
        Write-Host "Looking for processing running using local port: $portId"
        $connection = Get-NetTCPConnection -LocalPort $portId -ErrorAction Stop
        if ($connection) {
            Write-Output "Port $portId is in use by process ID $($connection.OwningProcess | Select-Object -Unique)."
        } else {
            Write-Output "Port $portId is not in use."
            return 0 | Out-Null
        }
    } catch {
        Write-Output "An error occurred: $_"
        return -1 | Out-Null
    }

    $processId = $connection.OwningProcess

    if ($processId -and $processId -gt 0) {
        $process = Get-Process -Id $processId
        if ($process) {
            # Stop the process
            try {
                Stop-Process -Id $processId -Force
                Write-Host "Process running at port $portId was terminated."
                return 0 | Out-Null
            } catch {
                Write-Host "Could not stop process. Reason: $error"
            }
        }
    }

    Write-Host "No process found using port $portId."
    return -1 | Out-Null
}



To terminate , we just run the command

 Terminate-Port -portId 5000


Screenshots of the function being run: BEFORE the command Terminate-Port is run and AFTER. Note that the process running at the given portId was terminated and then the local port is freed up again.
AFTER

Wednesday, 10 June 2020

Creating a self signed certificate with Powershell and preparing it for IIS

I just wrote an automated routine in Powershell to create a self signed certificate.
#Install-Module -Name 'WebAdministration'

Import-Module -Name WebAdministration

function AddSelfSignedCertificateToSSL([String]$dnsname, [String]$siteName='Default Web Site'){
 $newCert = New-SelfSignedCertificate -DnsName $dnsname -CertStoreLocation Cert:\LocalMachine\My
 $binding = Get-WebBinding -Name $siteName -Protocol "https"
 $binding.AddSslCertificate($newCert.GetCertHashString(), "My")
 $newCertThumbprint = $newCert.Thumbprint
 $sourceCertificate = $('cert:\localmachine\my\' + $newCertThumbprint)
 
 $store = new-object system.security.cryptography.X509Certificates.X509Store -argumentlist "Root", LocalMachine
 $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadWrite")
 $store.Add($newCert)
 return $newCertThumbprint
}

Write-Host Installing self-signed certificate Cert:\LocalMachine\My and Cert:\LocalMachine\Root ..

$certinstalledThumbprint = AddSelfSignedCertificateToSSL 'someacmeapp.somedomain.net'

Write-Host Added certificate $certinstalledThumbprint to Cert:\LocalMachine\My and Cert:\LocalMachine\Root and set this up as the SSL certificate on Default Web Site.




Friday, 10 May 2019

Adding only untracked files in Git repo using Powershell

Are you a .NET developer mainly still use Windows OS and use Powershell and not Git bash for example ? The following procedure can be followed to create an aliased function for adding untracked files in a Git repository. Inside your $profile file of Powershell (in case it is missing - you can run: New-Item $Profile) notepad $Profile Now add this Powershell method:
function AddUntracked-Git() {
 &git ls-files -o --exclude-standard | select | foreach { git add $_ }
}
Save the $profile file and reload it into Powershell. Then reload your $profile file with: . $profile This is similar to the source command in *nix environments IMHO. So next time you, if you are developer using Powershell in Windows against Git repo and want to just include untracked files you can run: AddUntracked-Git This follows the Powershell convention where you have verb-nouns.

Friday, 3 May 2019

Powershell - Appending folder to path

The following Powershell function can be used to append a folder to the path for a user at the command line.

function AppendPath($filePath) {
 $path = [Environment]::GetEnvironmentVariable("Path")
 $path += ";" + $filePath
 [Environment]::SetEnvironmentVariable("Path", $path)
 Write-Host $path 
}

To call this function, just run the Powershell command:
AppendPath "c:\temp"
You can add this file into your $profile file as a function for easy availability. Run . $profile to reload your $profile file. This will append the folder "c:\temp" to your environment variable PATH. To view your environment variable PATH just enter:
echo $env:path
It is not required, but you can also use Chocolatey's refreshenv script to force update the environment variable if it is still not updating.

Tuesday, 26 February 2019

Powershell - starting and stopping multiple app pools

The following powershell script defines some functions in Powershell that can start up or stop all iis app pools on a server. It can be handy when you want to test out concurrency issues and switch off all IIS app pools and start up again.

Function fnStartApplicationPool([string]$appPoolName){
Import-Module WebAdministration 
 if ((Get-WebAppPoolState $appPoolName).Value -ne 'Started') {
  Write-Host 'IIS app pool ' $appPoolName ' is not started. Starting.' 
  Start-WebAppPool -Name $appPoolName 
  Write-Host 'IIS app pool ' $appPoolName 'started' 
 }
}

Function fnStartAllApplicationPools() {
Import-Module WebAdministration  
 Write-Host "Starting all app pools" 
 $appPools = (Get-ChildItem IIS:\AppPools)

foreach ($appPool in $appPools) { 
  & fnStartApplicationPool -appPoolName $appPool.Name
}
}

#fnStartAllApplicationPools #start all applications pools


Function fnStopApplicationPool([string]$poolname) {
Import-Module WebAdministration 
 if ((Get-WebAppPoolState $appPoolName).Value -ne 'Stopped') {
  Stop-WebAppPool -Name $appPoolName 
 }
}

Function fnStopAllApplicationPools(){
Import-Module WebAdministration  
 Write-Host "Starting all app pools" 
 $appPools = (Get-ChildItem IIS:\AppPools)

foreach ($appPool in $appPools) { 
  & fnStopApplicationPool-appPoolName $appPool.Name
}  

}

#fnStopAllApplicationPools #start all applications pools


Wednesday, 17 October 2018

Working with Netsh http sslcert setup and SSL bindings through Powershell

I am working with a solution at work where I need to enable IIS Client certificates. I am not able to get past the "Provide client certificate" dialog, but it is possible to alter the setup of SSL cert bindings on your computer through the Netsh command. This command is not in Powershell, but at the command line. I decided to write some Powershell functions to be able to alter this setup atleast in an easier way. One annoyance with the netsh command is that you have to keep track of the Application Id and Certificate hash values. Here, we can easier keep track of this through Powershell code. The Powershell code to display and alter, modify, delete and and SSL cert bindings is as follows:

function Get-NetshSetup($sslBinding='0.0.0.0:443') {

$sslsetup = netsh http show ssl 0.0.0.0:443
#Get-Member -InputObject $sslsetup

$sslsetupKeys = @{}

foreach ($line in $sslsetup){
 if ($line -ne $null -and $line.Contains(': ')){
    
    $key = $line.Split(':')[0]
    $value = $line.Split(':')[1]
     if (!$sslsetupKeys.ContainsKey($key)){
       $sslsetupKeys.Add($key.Trim(), $value.Trim()) 
      }
    } 
}


return $sslsetup

}

function Display-NetshSetup($sslBinding='0.0.0.0:443'){
 
 Write-Host SSL-Setup is: 

 $sslsetup = Get-NetshSetup($sslBinding)

foreach ($key in $sslsetup){
 Write-Host $key $sslsetup[$key]
}
}

function Modify-NetshSetup($sslBinding='0.0.0.0:443', $certstorename='My',
  $verifyclientcertrevocation='disable', $verifyrevocationwithcachedcleintcertonly='disable',
  $clientCertNegotiation='enable', $dsmapperUsage='enable'){
  $sslsetup = Get-NetshSetup($sslBinding)
 
  echo Deleting sslcert netsh http binding for $sslBinding ...
  netsh http delete sslcert ipport=$sslBinding
  echo Adding sslcert netsh http binding for $sslBinding...
  netsh http add sslcert ipport=$sslBinding certhash=$sslsetup['Certificate Hash'] appid=$sslsetup['Application ID'] certstorename=$certstorename verifyclientcertrevocation=$verifyclientcertrevocation verifyrevocationwithcachedclientcertonly=$verifyrevocationwithcachedcleintcertonly clientcertnegotiation=$clientCertNegotiation dsmapperusage=$dsmapperUsage
  echo Done. Inspect output.  
  Display-NetshSetup $sslBinding
}



function Add-NetshSetup($sslBinding, $certstorename, $certhash, $appid, 
  $verifyclientcertrevocation='disable', $verifyrevocationwithcachedcleintcertonly='disable',
  $clientCertNegotiation='enable', $dsmapperUsage='enable'){

  echo Adding sslcert netsh http binding for $sslBinding...
  netsh http add sslcert ipport=$sslBinding certhash=$certhash appid=$appid  clientcertnegotiation=$clientCertNegotiation dsmapperusage=$dsmapperUsage certstorename=$certstorename verifyclientcertrevocation=$verifyclientcertrevocation verifyrevocationwithcachedclientcertonly=$verifyrevocationwithcachedcleintcertonly 
   
  echo Done. Inspect output.  
  Display-NetshSetup $sslBinding
}





#Get-NetshSetup('0.0.0.0:443'); 
Display-NetshSetup
#Modify-NetshSetup 
Add-NetshSetup '0.0.0.0:443' 'MY' 'c0fe06da89bcb8f22da8c8cbdc97be413b964619' '{4dc3e181-e14b-4a21-b022-59fc669b0914}'
Display-NetshSetup