Skip to content

Instantly share code, notes, and snippets.

@langheran
Created March 19, 2025 00:59
Show Gist options
  • Save langheran/3e9df09a6b8adab9c65528f35f22b045 to your computer and use it in GitHub Desktop.
Save langheran/3e9df09a6b8adab9c65528f35f22b045 to your computer and use it in GitHub Desktop.
C:\Users\NisimHurst\NDS\scripts\cmds\pod_logs.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 "Fetching logs for pod: $pod"
$params = "logs --tail=20"
if($previous) {
$params += " --previous"
}
if($namespace -ne "default") {
$params += " -n $namespace"
}
$params += " $pod"
if ($container) {
# split by space and get all the container names
$containers_ = Invoke-Expression $("kubectl get pod " + $pod + $namespace_param + " -o jsonpath='{range .spec.containers[*]}{.name}{\""\n\""}{end}'")
# split by space and get all the container names
$newContainer = $containers_ | ForEach-Object {
$containerName = $_
# write-host "Container: $containerName"
if ($containerName -match ".*" + $container + ".*") {
return $containerName
}
}
$params += " -c $newContainer"
}
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'."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment