Skip to content

Instantly share code, notes, and snippets.

@langheran
Created March 14, 2025 23:17
Show Gist options
  • Save langheran/ed78450870ae4a249e9f6cc0d3c1438f to your computer and use it in GitHub Desktop.
Save langheran/ed78450870ae4a249e9f6cc0d3c1438f to your computer and use it in GitHub Desktop.
C:\Users\NisimHurst\NDS\scripts\cmds\sh_pod.ps1
# read parameters from the command line
param(
[string]$namespace = "default",
[string]$pattern = "",
[bool]$previous = $false
)
# check if pattern has a space and if so, split it in two and use the first part
$container = ""
if ($pattern.Contains(" ")) {
$container = $pattern.Split(" ")[1]
$pattern = $pattern.Split(" ")[0]
write-host "Pattern: $pattern"
write-host "Container: $container"
}
$pattern = ".*$pattern.*"
# Define the namespace and the regular expression pattern to match pod names
# Get the list of pod names in the specified namespace
$params = "--no-headers"
if ($namespace -ne "default") {
$params += " -n $namespace"
}
write-host "Fetching pods"
$pods_ = Invoke-Expression $("kubectl get pods " + $params)
$pods = $pods_ | ForEach-Object {
$podName = $_.Split(" ")[0]
if ($podName -match $pattern) {
return $podName
}
}
# Check if any pods matched the pattern
if ($pods) {
# Retrieve logs from the matched pods
foreach ($pod in $pods) {
Write-Host "Connecting to pod: $pod"
$params = "exec -it "
if($previous) {
$params += " --previous"
}
if($namespace -ne "default") {
$params += " -n $namespace"
}
if ($container) {
$params += " -c $container"
}
$params += " $pod"
# $params += " -- bash"
$params += " -- /bin/sh"
# Write-Host "kubectl $params"
start-process -NoNewWindow -Wait -FilePath kubectl -ArgumentList $params
}
} else {
Write-Host "No pods found matching the pattern '$pattern' in namespace '$namespace'."
}
@echo off
chcp 437 > nul
pushd %~dp0
powershell -command ".\sh_pod.ps1 -pattern ""%*"""
popd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment