Tuesday, April 10, 2012

How to call powershell function properly?

I wrote a function to convert the input month parameter to a certain format. such as if I passed 04 to the funtion and the function will return the "_APR_". the function I wrote is like below:



function GetEnMonth()
{
param([string] $month)
switch ($month)
{
($_ -eq "01"){$result = "_JAN_"}
($_ -eq "02"){$result = "_FEB_"}
($_ -eq "03"){$result = "_MAR_"}
($_ -eq "04"){$result = "_APR_"}
($_ -eq "05"){$result = "_MAY_"}
($_ -eq "06"){$result = "_JUN_"}
($_ -eq "07"){$result = "_JUL_"}
($_ -eq "08"){$result = "_AUG_"}
($_ -eq "09"){$result = "_SEP_"}
($_ -eq "10"){$result = "_OCT_"}
($_ -eq "11"){$result = "_NOV_"}
($_ -eq "12"){$result = "_DEC_"}
default {$result ="_No_Result_"}
}
return [string]$result;
}


Then I use below command to excute the function to get the result:



$mYear = $today.substring(0,4) 
$mMonth =$today.substring(4,2)
$mDate = $today.substring(6,2)
$monthInEn = GetEnMonth $mMonth


well, the result is always "_No_Result_", why? below is the exception:



 **** Exception type : System.Management.Automation.RuntimeException
**** Exception message : You cannot call a method on a null-valued expression.


Could anyone give me an answer for this? thx.
I have searched goole a lot but don't find useful solutions.





No comments:

Post a Comment