Download Mastering-PowerShell
Transcript
Method invocation failed because [System.String]
doesn't contain a method named "op_Subtraction".
At line:3 char:9
+ $value1 - <<<< $value2
Errors caused by mismatching data types are difficult to locate and remove because the resulting
error message sounds confusing and the error is reported in a completely wrong location where the
process is trying to get something done with an inappropriate data type.
It would make much more sense if the argument parser of the function hadn't accepted the
mismatching arguments in the first place, which brings us to the solution: you can tell the argument
parser which data types the parameters of your function can use. If the user specifies the wrong
data types as an argument anyway, the argument parser will refuse to accept it and report the
mistake with a much more explicit error message:
# This function accepts nothing but numbers as an argument:
function Subtract([int]$Value1, [int]$Value2)
{ $value1 - $value2 }
Subtract 5 2
3
# As long as the argument can be converted
# to a number, the function is satisfied:
Subtract "5" 2
3
# The function will accept no inputs that cannot
# be converted to numbers
Subtract Hello world
subtract : cannot convert value "Hello" to type "System.Int32".
Error: "input string was not in a correct format."
At line:1 char:12
+ Subtract <<<< Hello world
To get the argument parser to accept nothing but very specific data types, you should use the strong
type specification that you learned about in Chapter 3. For that purpose, jot down the desired data
type in brackets in front of the parameter. Effective immediately, the parameter will accept only
numbers or information that can be changed to numbers. If the user specifies the wrong data type,
an error will be generated that will now describe the cause with much greater clarity.
But watch out when you choose the data type for your arguments. Do you have any idea why your
function returns the following results?
Subtract 8.2 0.2
8
Subtract 8.2 1.4
Table of Contents | About PowerShell Plus
257
Sponsors | Resources | © BBS Technologies
Related documents
Table of Contents
Terminal de distributeurs Type 03/05
Wiley Automating Active Directory Administration with Windows PowerShell 2.0
R1209 Six-Way™ Power Seat Base Service Manual
R1208 Six-Way Power Seat Base Service Manual
May 2010 - Center
Manual
May 2010 - 1105 Media
MiKTEX Manual
External Interfaces/API
Online RETROFIT Application Training Manual
Filière Informatique de gestion www.hevs.ch