首页 > 解决方案 > Powershell - 在管道内使用 $_ ($PSItem) 的问题是自己的 $_

问题描述

我有这个脚本:

$cont = @(
    "2019-01-01 00:00:00;0;1;224.94999999999999;13.710000000000001;7.9226000000000005E-2",
    "2019-01-01 00:00:00;0;2;-5.9999999999999998E-2;13.630000000000001;6.0484000000000003E-2"
)
$cont | % {
    $lig = $_ # line for production
    $lig = $cont[0].split(";") # line for test
    $var1 = $lig.split(";")
    try {
        $var1[0].ToDateTime($psitem) 
        $var1[1].ToInt16($_) 
        $var1[2].ToInt16($_)
        $var1[3].ToSingle($_)
        $var1[4].ToSingle($_)
        $var1[5].ToSingle($_) 
    }
    catch {
        write-host "Erreur dans la ligne $lig"
    }

}

如果我仅从“测试行”手动运行不使用循环,% 我会得到尝试结果:

狂欢节 2019 年 1 月 1 日 00:00:00 0 1 224.95 13.71 0.079226

但如果我运行整个脚本(我评论“测试行”),我有

ERREUR DANS LA LIGNE 2019-01-01 00:00; 0; 0; 1; 224.9499999999999999; 13.7100000000001; 7.92260000000000001; 7.9226000000000000000000000000000000000000000000000005E-2 2;13.630000000000001;6.0484000000000003E-2

$Error[0] 给我:

$error[0] Impossible de convertir l'argument «provider» (valeur «2019-01-01 00:00:00;0;2;-5.9999999999999998E-2;13.630000000000001;6.0484000000000003E-2») de «ToDateTime» en type «System.IFormatProvider»: «Impossible de convertir la valeur «2019-01-01 00:00:00;0;2;-5.9999999999999998E-2;13.630000000000001;6.0484000000000003E-2» du type «System.String»输入 «System.IFormatProvider»。»

似乎他混淆了$_使用foreach$_使用的两个值ToInt16($_),ToDateTime($psitem) ...

我该怎么做才能使用$var[1].toint16[$_]$_是价值$var1[1]而不是价值的方法$cont

感谢您的帮助。

标签: powershell

解决方案


我不完全理解你的问题。像 todatetime() 这样的东西需要一个 iformatprovider 参数https://docs.microsoft.com/en-us/dotnet/api/system.convert.todatetime?view=netcore-3.1#System_Convert_ToDateTime_System_String_System_IFormatProvider_,但 $null 会起作用。或 [Cultureinfo] 对象。如果没有 try/catch,就会有很多错误消息来描述它。与 toint16() 和 tosingle() 的想法相同。我不明白你认为“$_”和“$psitem”应该来自哪里。

'2019-01-01 00:00:00'.todatetime

OverloadDefinitions
-------------------
datetime IConvertible.ToDateTime(System.IFormatProvider provider)


'2019-01-01 00:00:00'.todatetime('2019-01-01 00:00:00')

MethodException: Cannot convert argument "provider", with value: "2019-01-01 00:00:00", for "ToDateTime" to type "System.IFormatProvider":
"Cannot convert the "2019-01-01 00:00:00" value of type "System.String" to type "System.IFormatProvider"."


'2019-01-01 00:00:00'.todatetime($null)               

Tuesday, January 1, 2019 12:00:00 AM


'2019-01-01 00:00:00'.todatetime([Cultureinfo]'en-US')

Tuesday, January 1, 2019 12:00:00 AM

推荐阅读