我编写了一个函数,将输入的month参数转换为某种格式。例如我将04传递给该函数,该函数将返回“ _ APR_”。我写的功能如下:
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;
}
然后,我使用以下命令执行该函数以获取结果:
$mYear = $today.substring(0,4)
$mMonth =$today.substring(4,2)
$mDate = $today.substring(6,2)
$monthInEn = GetEnMonth $mMonth
好吧,结果总是“_No_Result_”,为什么呢?以下是异常(exception):
**** Exception type : System.Management.Automation.RuntimeException
**** Exception message : You cannot call a method on a null-valued expression.
有人可以给我答案吗?
我已经搜索了很多Google,但是找不到有用的解决方案。
最佳答案
您的switch语句错误,请尝试以下操作:
function GetEnMonth()
{
param([string] $month)
switch ($month)
{
"01" {$result = "_JAN_"}
"02" {$result = "_FEB_"}
"03" {$result = "_MAR_"}
"04" {$result = "_APR_"}
"05" {$result = "_MAY_"}
"06" {$result = "_JUN_"}
"07" {$result = "_JUL_"}
"08" {$result = "_AUG_"}
"09" {$result = "_SEP_"}
"10" {$result = "_OCT_"}
"11" {$result = "_NOV_"}
"12" {$result = "_DEC_"}
default {$result ="_No_Result_"}
}
return [string]$result;
}
关于function - 如何正确调用Powershell函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10086586/