我写了一个函数来将输入月份参数转换为某种格式。例如,如果我将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 type : System.Management.Automation.RuntimeException
**** Exception message : You cannot call a method on a null-valued expression.
有人能给我一个答案吗? 我经常搜索Google,但找不到有用的解决方案。
答案 0 :(得分:3)
这应该有效:
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;
}
答案 1 :(得分:3)
这是我对此的看法。我将参数类型更改为Int,这样您就可以获得诸如“03”或3的过程。我还添加了break语句以使开关更快地工作。
function GetEnMonth
{
param([int] $month)
switch ($month)
{
1 {"_JAN_"; break}
2 {"_FEB_"; break}
3 {"_MAR_"; break}
4 {"_APR_"; break}
5 {"_MAY_"; break}
6 {"_JUN_"; break}
7 {"_JUL_"; break}
8 {"_AUG_"; break}
9 {"_SEP_"; break}
10 {"_OCT_"; break}
11 {"_NOV_"; break}
12 {"_DEC_"; break}
default {"_No_Result_"}
}
}
答案 2 :(得分:2)
您的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;
}
答案 3 :(得分:2)
这不是一个答案,而是在一行和文化参数中做同样的另一种方式:
$month = 3
$smonth=[string]::format([System.Globalization.CultureInfo]"en-US", "_{0:MMM}_",[datetime]("$month/01"))
$smonth
_MAR_