How to get information about the VDI’s and Computers not Rebooted Science last 5 days

# Define the path to the text file containing computer names
$computerNamesFile = “C:PathToYourComputerNames.txt”

# Define the path for the output Excel file
$outputExcelFile = “C:PathToYourOutput.csv”

# Get the current date and subtract 10 days
$tenDaysAgo = (Get-Date).AddDays(-10)

# Read the computer names from the text file
$computerNames = Get-Content -Path $computerNamesFile

# Initialize an array to store the results
$results = @()

# Loop through each computer name
foreach ($computer in $computerNames) {
try {
# Test if the computer is reachable (ping test)
$isReachable = Test-Connection -ComputerName $computer -Count 1 -Quiet -ErrorAction Stop

if ($isReachable) {
# Get the last boot time using WMI (Windows Management Instrumentation)
$lastBootTime = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computer -ErrorAction Stop |
Select-Object -ExpandProperty LastBootUpTime

# Convert the last boot time to a DateTime object
$lastBootTime = [System.Management.ManagementDateTimeConverter]::ToDateTime($lastBootTime)

# Calculate the uptime
$uptime = (Get-Date) – $lastBootTime

# Check if the uptime is greater than or equal to 10 days
if ($uptime.Days -ge 10) {
# Add the computer name, last boot time, and uptime to the results array with “Reboot Required” status
$results += [PSCustomObject]@{
Hostname = $computer
LastBootTime = $lastBootTime.ToString(“yyyy-MM-dd HH:mm:ss”) # Format the date and time
Uptime = “{0} days, {1} hours, {2} minutes” -f $uptime.Days, $uptime.Hours, $uptime.Minutes #Formatted Uptime
Status = “Reboot Required”
}
}
} else {
# Mark the computer as “Powered Off” if it is not reachable
$results += [PSCustomObject]@{
Hostname = $computer
LastBootTime = “N/A”
Uptime = “N/A”
Status = “Powered Off”
}
}
} catch {
# Handle any errors (e.g., WMI access issues)
$results += [PSCustomObject]@{
Hostname = $computer
LastBootTime = “N/A”
Uptime = “N/A”
Status = “Error: $_”
}
}
}

# Filter the results to include those with uptime >= 10 days OR Status is “Powered Off”
$resultsToExport = $results | Where-Object {($_.Status -eq “Reboot Required”) -or ($_.Status -eq “Powered Off”)}

# Export the filtered results to an Excel file
$resultsToExport | Export-Csv -Path $outputExcelFile -NoTypeInformation

Write-Host “Results have been exported to $outputExcelFile”

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top