Powershell – Error – InvalidCastFromStringToInteger – “Input string was not in a correct format.”

Background

Wanted to quickly document an error message I received earlier today working on a little Powershell script.

Error

Error Image


Cannot convert value "0:0:0.1" to type "System.Int32". Error: "Input string was not in a correct format."
At
+     $elapsedTime = "{0}:{1}:{2}.{3}" -f $ts.Hours, $ts.Minutes, $ts.S ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToInteger

Error Message

Code

Code – Error


#Stop Watch - Start
$stopwatch =  [system.diagnostics.stopwatch]::StartNew()

#Stop Watch - Stop
$stopwatch.Stop();

#Get the elapsed time as a TimeSpan value.
$ts = $stopWatch.Elapsed;

$elapsedTime = $formatTime -f $ts.Hours, $ts.Minutes, `
	       $ts.Seconds, $ts.Milliseconds / 10;

Code – Correction

Outline

  1. The issue is with trying to divide within the format statement
  2. To correct
    • Place parentheses around the arithmetic operation
      • $ts.Milliseconds / 10 becomes ( $ts.Milliseconds / 10 )
    • Perform the arithmetic operation in an early statement
      • $tsElapsedMilliSeconds = $ts.Milliseconds/10;
      • And, use the result of the operation within the format statemet

 

Code – Correction -01


#Stop Watch - Start
$stopwatch =  [system.diagnostics.stopwatch]::StartNew()

#Stop Watch - Stop
$stopwatch.Stop();

#Get the elapsed time as a TimeSpan value.
$ts = $stopWatch.Elapsed;

$elapsedTime = $formatTime -f $ts.Hours, $ts.Minutes, `
               $ts.Seconds, ($ts.Milliseconds/10);

Code – Correction -02


#Stop Watch - Start
$stopwatch =  [system.diagnostics.stopwatch]::StartNew()

#Stop Watch - Stop
$stopwatch.Stop();

#Get the elapsed time as a TimeSpan value.
$ts = $stopWatch.Elapsed;

$tsElapsedMilliSeconds = $ts.Milliseconds/10;

$elapsedTime = $formatTime -f $ts.Hours, $ts.Minutes, `
               $ts.Seconds, $tsElapsedMilliSeconds;

Code Sharing

Gist

Link

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s