1

我写了一个函数来将输入月份参数转换为某种格式。例如,如果我将 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 上搜索了很多,但没有找到有用的解决方案。

4

4 回答 4

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;
} 
于 2012-04-10T10:05:36.120 回答
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_"}
    }
} 
于 2012-04-10T12:48:19.223 回答
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;
} 
于 2012-04-10T10:07:54.873 回答
2

这不是答案,而是另一种在一行中使用文化参数执行相同操作的方法:

$month = 3
$smonth=[string]::format([System.Globalization.CultureInfo]"en-US", "_{0:MMM}_",[datetime]("$month/01"))
$smonth
_MAR_
于 2012-04-10T11:38:26.163 回答