powershell - 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
感谢您的帮助。
解决方案
我不完全理解你的问题。像 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
推荐阅读
- python - 无序列表作为 dict 键
- python - TypeError:serve() 得到了一个意外的关键字参数“document_root”
- javascript - 带有评论系统的 React,socket.io 帖子
- ruby-on-rails - 使用资源定义铁路路线
- php - 如何在 Hacklang 中使用管道附加到 darray
- html - 响应式图像导致文本和图像在小屏幕尺寸下溢出屏幕
- python - Matplotlib:在给定预先计算的计数和 bin 的情况下绘制直方图
- firebase - Firebase 将新用户与 airtable 同步
- excel - Excel - INDEX + MATCH + COUNTIF 函数
- ios - 如何从 rx observable 中获取最后十个元素?