Skip to content

Instantly share code, notes, and snippets.

@langheran
Last active February 21, 2025 18:43
Show Gist options
  • Save langheran/7d92d8b50a66ba37c66ce1bb0a02fd33 to your computer and use it in GitHub Desktop.
Save langheran/7d92d8b50a66ba37c66ce1bb0a02fd33 to your computer and use it in GitHub Desktop.
C:\Users\NisimHurst\NDS\scripts\cmds\klogs.cmd
@echo off
klogs %*
@echo off
chcp 437 > nul
pushd %~dp0
powershell -command ".\pod_logs.ps1 -pattern ""%*"""
popd
# 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 "Patter: $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 "Fetching logs for pod: $pod"
$params = "logs --tail=20"
if($previous) {
$params += " --previous"
}
if($namespace -ne "default") {
$params += " -n $namespace"
}
$params += " $pod"
if ($container) {
$params += " -c $container"
}
start-process -NoNewWindow -Wait -FilePath kubectl -ArgumentList $params
}
} else {
Write-Host "No pods found matching the pattern '$pattern' in namespace '$namespace'."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment