function - 如何正确调用Powershell函数?

标签 function powershell

我编写了一个函数,将输入的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/

相关文章:

Powershell 自定义对象 toString 值用作 Note 属性

file - 在 Powershell 中检查文件大小 gt 0

c - 关于在 C 中使用 "functions"

Excel 英尺和英寸到毫米

python - 提取 python 方法参数的数量和名称

rest - 带有REST API调用的Powershell脚本无法在启动时运行

arrays - 将哈希表转换为 json 后 Powershell 缺少数组

json - Powershell无需迭代即可直接引用JSON对象

python - Print only 在函数完成执行后打印

C++ 独立函数文件