我正在处理一个小型PowerShell脚本来处理CSV文件。
CSV文件示例:
"lastname";"firstname";"birthday" "meier";"bernd";"23.06.1976" "hoffmann";"sven";"12.04.1955" "berger";"tim";"14.15.2007"
该脚本创建一个窗口,用户可以使用两个数据采集器选择日期,因此用户应该能够删除所选日期之前或之后生日所在的所有行。
Function Start-MyImport {
#Build the GUI
[xml]$xaml_ar = @"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="Title" Height="164.653" Width="498.907" ResizeMode="NoResize" Topmost="True" WindowStartupLocation="CenterScreen">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="27*"/>
<ColumnDefinition Width="464*"/>
</Grid.ColumnDefinitions>
<Button Name="agerange_go" Content="go!" HorizontalAlignment="Left" Height="23" Margin="334,71,0,0" VerticalAlignment="Top" Width="96" Grid.Column="1"/>
<CheckBox Name="agerange_before" Content="birthday before:" Grid.Column="1" HorizontalAlignment="Left" Margin="18,76,0,0" VerticalAlignment="Top"/>
<CheckBox Name="agerange_after" Content="birthday after:" Grid.Column="1" HorizontalAlignment="Left" Margin="18,103,0,0" VerticalAlignment="Top"/>
<DatePicker Name="dp_before" Grid.Column="1" HorizontalAlignment="Left" Margin="176,71,0,0" VerticalAlignment="Top"/>
<DatePicker Name="dp_after" Grid.Column="1" HorizontalAlignment="Left" Margin="176,98,0,0" VerticalAlignment="Top"/>
</Grid>
</Window>
"@
$reader_ar = (New-Object System.Xml.XmlNodeReader $xaml_ar)
$Window_ar = [Windows.Markup.XamlReader]::Load($reader_ar)
$xaml_ar.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | ForEach {
Set-Variable -Name ($_.Name) -Value $Window_ar.FindName($_.Name)
}
#Events
$agerange_go.Add_Click({
if ($agerange_before.IsChecked) {
$dp_before = $dp_before.Text
if ($dp_before -ne "") {
Write-Host $dp_before
Import-Csv my.csv -Delimiter ";" -Encoding UTF8 |
where birthday -as[DateTime]::ParseExact($_."birthday", "dd.MM.YYYY", $null) -lt $dp_before |
Export-Csv CsvFileOut.csv -Delimiter ";" -Encoding UTF8 -NoTypeInfo
}
}
$Window_ar.Close()
#Lieferant-Repl
})
$Window_ar.ShowDialog() | Out-Null
}
Start-MyImport
问题是,我无法将生日列解析为日期。我的方式不起作用。
where birthday -as[DateTime]::ParseExact($_."birthday", "dd.MM.YYYY", $null) -lt $dp_before
如何正确处理这个问题?
答案 0 :(得分:2)
您必须阅读并注意错误消息。 (顺便说一句,请告诉我们错误信息。不要只说它不起作用。这没有用。)
C:\> [DateTime]::ParseExact("23.06.1976", "dd.MM.YYYY", $null)
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
所以两个字符串中的一个是错误的。这个日期看起来没问题,所以这意味着我们应该看一下format string,事实上我们发现没有&#34; YYYY&#34;这样的东西。如果我们将其更正为&#34; yyyy&#34;,那么它可以工作:
C:\> [DateTime]::ParseExact("23.06.1976", "dd.MM.yyyy", $null)
Wednesday, 23 June 1976 12:00:00 AM