Lastreboot with Powershell

by Mvinogradac at 2013-03-20 01:29:43

Hello Everyone,

i’ve write thise code in Powershell. But it’s not function. I can not find the Error. Can you Help me ?

#LastBootTime#
#Version 1.0#
#Marko Vinogradac#


#Uptime Abfrage###########################################################################################
function Computer {
$CPName = Import-Csv "E:\Servers.csv"
$CPName | foreach {
#Ping#####################################################################################################
function Alive{
$P = Get-WmiObject Win32_PingStatus -filter "Address=‘$CPName’"
if($P.StatusCode -eq 0){Lastreboot}
else {"Host $CPName down" | Out-File "E:\Reboots.txt" -Append}
#Lastreboot###############################################################################################
function Lastreboot {
$wmi= gwmi -computer $CPName Win32_OperatingSystem -filter "Address=‘$CPName’"
$LBTime = $wmi.ConvertToDateTime($wmi.LastBootUpTime)
[TimeSpan]$UPtime=New-TimeSpan $LBTime $(Get-Date)
"{0} Seit {1} Tagen kein Reboot" -f $Cpname,$UPtime.days | Out-File "E:\Reboots.txt" -Append}
}
}
}
#Start Skript####
$Start = $args[0]
if($start){Alive}
else {Computer}
by DonJ at 2013-03-20 06:56:40
For starters, you are attempting to ping multiple computers - you use $CPName, which contains the contents of your text file. You do the same thing in a couple of places. You need to enumerate those and use just one computer name at a time. However, right now this is not very well written, the way you have nested all of the functions. It may be a little difficult to fix, the way this is currently written.
by coderaven at 2013-03-20 11:44:36
I see what you are trying to do, let me see if I can get your stuff in a close to working state.

#PowerShell Script - Get-MyLastBootReport.ps1
Param([String]$ComputerName)

Foreach ($Computer in $ComputerName)
{
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet)
{
try {
$wmi = Get-WMIObject -ComputerName $Computer -Class Win32_ComputerSystem -Filter {Address -eq $Computer} -ErrorAction Stop
New-Object -TypeName PSObject -Property @{Computer=$Computer;Active=$True;LastBoot=$wmi.ConvertToDateTime($wmi.LastBootTime)}
}
catch { New-Object -TypeName PSObject -Property @{Computer=$Computer;Active=$True;LastBoot="UNKNOWN"} }
}
else
{
New-Object -TypeName PSObject -Property @{Computer=$Computer;Active=$False;LastBoot="NA"}
}
}

The way you would use it is to call the file and get the field from the CSV that has the computer name
\path\to\ps1\file\Get-MyLastBootReport.ps1 -ComputerName (Import-Csv -Path FILENAME.CSV | Select -ExpandProperty CName) | Export-Csv -Path \path\to\csv\lastbootreport.csv -NoTypeInformation

Hope that help and keep in mind that this is untested ad-hoc stuff.