尋找作業系統帳號建立日期

2024-07-17 工作雜記 linux

weindows

Write-Output "User,Birth"

# 取得所有用戶名和主目錄路徑
$users = Get-WmiObject Win32_UserAccount | Where-Object { $_.LocalAccount -eq $true -and $_.SIDType -eq 1 }

foreach ($user in $users) {
    $homeDir = "C:\Users\$($user.Name)"
    
    if (Test-Path $homeDir) {
        $creationTime = (Get-Item $homeDir).CreationTime
        $formattedTime = $creationTime.ToString("yyyy-MM-dd HH:mm:ss")
        Write-Output "$($env:COMPUTERNAME),$($user.Name),$formattedTime"
    } else {
        Write-Output "$($env:COMPUTERNAME),$($user.Name),-"
    }
}

Linux

#!/bin/bash


# 從 /etc/passwd 文件中讀取所有用戶名和主目錄路徑
while IFS=: read -r username _ _ _ _ home_dir _; do
  if [ -d "$home_dir" ]; then
    # 使用 stat 命令獲取主目錄資訊
    stat_output=$(stat "$home_dir")
    birth_time=$(echo "$stat_output" | grep 'Birth' | awk '{print $2 " " $3}')
    
    if [ -n "$birth_time" ]; then
      formatted_time=$(date -d "$birth_time" +'%Y-%m-%d %H:%M:%S')
      echo "$(hostname),$username,$formatted_time"
    else
      birth_time=$(echo "$stat_output" | grep 'Change' | awk '{print $2 " " $3}')
    if [-n "$birth_time"]; then
      formatted_time=$(date -d "$birth_time" +'%Y-%m-%d %H:%M:%S')
    else
      echo "$(hostname),$username,-"
    fi
      
    fi
  else
    echo "$(hostname),$username,-"
  fi
done < /etc/passwd