Powershell and error handling

I am trying to build a script that would start up my domain services in order in the event of a complete power failure

I am booting up the machines remotely using an iDrac, waiting a few minutes then checking the system uptime using get-wmiobject to make sure that the operating system is loaded.

To do this I have this code I found on a website

$timeinseconds = ((get-date)-[system.management.managementdatetimeconverter]::todatetime((get-wmiobject -class win32_operatingsystem -computer servername -erroraction silentlyContinue -ErrorVariable badoutput).Lastbootuptime)).TotalSeconds

Now this works fine when the system is online, but if the system is offline it throws an error message

Exception calling "ToDateTime" with "1" argument(s): "Specified argument was out of the range of valid values.
Parameter name: dmtfDate"

I am guessing this is because it is trying to convert the variable to .TotalSeconds but there is no value in the $timeinseconds.

I have added the erroraction and errorvariable commands so that I can store the error, but this I think is only for the wmi section, as it will store "the rpc server is unavailable" as expected, but the exception on top is still generated.

What could I change to get this to work better?

Thanks in advance for any help.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dorababu MSenior Software EngineerCommented:
You can use Test-Connection to check whether the system is online.

$computer  = "name"
If (Test-Connection -ComputerName $computer -Count 1 -Quiet)
       Write-Host "$computer is Online"

Open in new window

Count can be changed as per your requirement.
CaptainGibletsAuthor Commented:
Would that not return a ping even if the operating system hadn't booted up yet? as long as the network card was on.
The system responding to ping does not mean that WMI is up and accessible, so you'll have to wrap that in a Try/Catch:
$ServerName = '.'
If (Test-Connection -ComputerName $ServerName -Count 2 -Quiet) {
	Try {
		$Uptime = [int]((Get-Date) - [System.Management.ManagementDateTimeConverter]::ToDateTime((Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ServerName -ErrorAction Stop).LastBootupTime)).TotalSeconds
		Write-Host "$($ServerName) is up since $($Uptime) seconds." -ForegroundColor Green
	} Catch {
		Write-Host "$($ServerName) failed: $($_.Exception.Message)" -ForegroundColor Red
} Else {
	Write-Host "$($ServerName) failed: no ping response" -ForegroundColor Red

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

David Johnson, CD, MVPOwnerCommented:
$computer = $env:COMPUTERNAME
  try {
    $ServerWMITime = get-wmiobject -class win32_operatingsystem -ComputerName $computer  -ErrorAction SilentlyContinue -ErrorVariable badoutput |
                     Select-Object -ExpandProperty LastBootUpTime
        $dateTime = [System.Management.ManagementDateTimeConverter]::ToDateTime($ServerWMITime)
    Write-Host $dateTime

    Write-Host $badoutput
    Write-Host "Computer Not Available" -ForegroundColor Red

Open in new window

This gives you the boot up time in a DATE/Time not the # of seconds the machine has been up i.e. 09-Jan-2018 4:47:24 AM
CaptainGibletsAuthor Commented:
I have put this in and it works great, however I am trying to put it into another bit of code, but it doesn't seem to work with that.

If I need to open another question I will but.....

I am running a dell command line via powershell such as

$powerstatus = racadm -r ipaddress-u $idracadmin -p $idracpassword --nocertwarn serveraction powerstatus

to get the power status. If the ipaddress is a correct address it works fine, however if it is incorrect it will show the below in ISE and if ran alone it shows "ERROR: Unable to connect to RAC at specified IP address."  

If it is a correct address nothing is put in the output and the results are stored in the variable correct.

"racadm : ERROR: Unable to connect to RAC at specified IP address.
At C:\Users\testscript.ps1:7 char:18
+ ... werstatus = racadm -r ipaddress -u $idracadmin -p $idracpassword ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (ERROR: Unable t...ied IP address.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
David Johnson, CD, MVPOwnerCommented:
put it in a try catch block

try {
$powerstatus = racadm -r $ipaddress-u $idracadmin -p $idracpassword --nocertwarn serveraction powerstatus -EA SilentlyContinue
catch {
write-host ("Error connecting to $ipaddress")


Open in new window

CaptainGibletsAuthor Commented:
I tried that and its still returning the error in ISE and the one line standalone.
For native commands like exe files, Try/Catch won't work.
You can use something like this:
$IdracIPAddress = ''
$StdErr = $($Powerstatus = racadm -r IdracIPAddress -u $idracadmin -p $idracpassword --nocertwarn serveraction powerstatus) 2>&1
If ($StdErr) {
	Write-Host "Could not connect to $($IdracIPAddress): $($StdErr)" -ForegroundColor Red
} Else {
	Write-Host "Powerstatus obtained from $($IdracIPAddress): $($Powerstatus)"

Open in new window

PberSolutions ArchitectCommented:
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I have recommended this question be closed as follows:

-- oBdA (https:#a42428439)
-- oBdA (https:#a42428852)
-- David Johnson CD MVP (https:#a42428539)

If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.

Experts-Exchange Cleanup Volunteer
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.