Friday, May 08, 2015

Powershell v3: How to check if a PC is up for > 30 days

step 1- Check uptime. If > 30 days, then go for step 2; else exit step 2- Check if desktop is unlocked. If yes, popup saying it will be rebooted in next 24 hours. If locked, exit step 3- reboot
Is that accurate? Can be do in powershell.
$computer = "<Computer name>"
 if (Test-Connection $computer -Count 2 -Quiet) {

try {

     $user = $null

     $user = gwmi -Class win32_computersystem -ComputerName $computer | select -ExpandProperty username -ErrorAction Stop
     }
 catch { Write-Host "Not logged on"; return }
 try {
     if ((Get-Process logonui -ComputerName $computer -ErrorAction Stop) -and ($user)) {
        Write-Host "Workstation locked by $user"
         }
     }
 catch { if ($user) 
 { 
Write-Host "$user logged on" 
   $wmi = Get-WmiObject -ComputerName $computer -Query "SELECT LastBootUpTime FROM Win32_OperatingSystem"

$now = Get-Date

$boottime = $wmi.ConvertToDateTime($wmi.LastBootUpTime)

$uptime = $now - $boottime

$d =$uptime.days

$h =$uptime.hours

$m =$uptime.Minutes

$s = $uptime.Seconds
# above h/m/s are optional, but good to have!
if ($d -gt 30) { 
 Write-Host "Greather than 30 days" 
 # call shutdown tool here or do other activities

 } 
else { Write-Host "Less than 30 days" }

} }

}

 else { Write-Host "$computer Offline" }

Linux/Bash: How to report the CPU/ memory usage per user.

for user in `ps -aef | awk '{print $1}' | sort -k1 | uniq | grep -v UID`; do
procs=$(ps -u $user -o user,comm,vsz | wc -l) ;
echo -en $user " : Memory in KiB : " $(ps -u $user -o user,cmd,vsz | grep -v grep | awk 'BEGIN{s=0;} {s=s+$NF;}END{print s/1024}'); echo "" ;
echo -en $user " : CPU% : " $(ps -u $user -eo %cpu | grep -v grep | awk 'BEGIN{s=0;} {s=s+$NF;}END{print s}'); echo "" ;
done

Another method I learnt was:


ps -eo %cpu=,vsz=,user= |

awk '{ cpu[$3]+=$1; vsz[$3]+=$2 } END { for (user in cpu) printf("%-10s : Memory %10.1f KiB, CPU%%: %4.1f\n", user, vsz[user]/1024, cpu[user]); }'

OR



LC_ALL=C ps -eo %cpu=,vsz=,user= |

awk '{ cpu[$3]+=$1; vsz[$3]+=$2 } END { for (user in cpu) printf("%-10s : Memory %10.1f KiB, CPU%%: %4.1f\n", user, vsz[user]/1024, cpu[user]); }'




And finally:



ps axro "pid,%cpu,ucomm" | awk 'FNR>1' | head -n 3 | awk '{ printf "%5.1f%%,%s,%s",$2,$3,$1 }


ps axo "rss,pid,ucomm" | sort -nr | head -n3 | awk ‘{ printf "%8.0f MB,%s,%s",$1/1024,$3,$2 }