英文:
Compare 2 dates and output all past dates (powershell)
问题
我有一个关于我的PowerShell脚本的问题。我导入了一个包含不同日期的CSV文件,然后与今天的日期进行比较。
我不知道为什么,但我从CSV文件中得到了3个将来的日期。
脚本:
$InfoCSV = Import-Csv -Path "C:\Script\BDR\Info.csv" -Delimiter ";"
$Date = Get-Date
$today = (Get-Date -format dd.MM.yyyy)
foreach ($Item in $InfoCSV){
$BDate = $Item.BDate
$BDate = $BDate -replace "yyyy",$Date.Year
$parsedBDate = Get-Date $BDate -Format "dd.MM.yyyy"
if($parsedBDate -le $today){
$Name = $Item.Name
Write-Output "$BDate";}
}
输出:
10.01.2023
06.02.2023
03.04.2023
06.05.2023
09.05.2023
02.07.2023
03.07.2023
07.07.2023
09.07.2023
02.08.2023
06.08.2023
02.09.2023
最后3个日期是从哪里来的?
我将不胜感激地接受任何答案。此外,如果有人有更好的方法来存储日期或以任何其他方式改进我的脚本,我会很高兴。
谢谢
Luca
英文:
I have a problem with my powershell script. I import a csv with different dates and compare them with today.
I dont know why but I get 3 dates from the csv that are in the future.
The script:
$InfoCSV = Import-Csv -Path "C:\Script\BDR\Info.csv" -Delimiter ";"
$Date = Get-Date
$today = (Get-Date -format dd.MM.yyyy)
foreach ($Item in $InfoCSV){
$BDate = $Item.BDate
$BDate = $BDate -replace "yyyy",$Date.Year
$parsedBDate = Get-Date $BDate -Format "dd.MM.yyyy"
if($parsedBDate -le $today){
$Name = $Item.Name
Write-Output "$BDate"}
}
Output:
10.01.2023
06.02.2023
03.04.2023
06.05.2023
09.05.2023
02.07.2023
03.07.2023
07.07.2023
09.07.2023
02.08.2023
06.08.2023
02.09.2023
Where do the last 3 dates come from?
I would appreciat any answer.
Furthermore I would be happy when anyone has a better Idea how to store the dates or improve my script in any other way.
Thanks
Luca
答案1
得分: 1
请看以下的翻译:
对于_按时间顺序_比较,按照[Olaf](https://stackoverflow.com/users/9196560/olaf)的建议,将您的日期_字符串_解析为`[datetime]`([`System.DateTime`](https://learn.microsoft.com/en-US/dotnet/api/System.DateTime))实例:
```powershell
# 获取今天的日期作为[datetime]实例。
$today = (Get-Date).Date
# ...
# 将CSV列值解析为[datetime]实例。
$parsedBDate =
[datetime]::ParseExact($Item.BDate, 'dd.MM.yyyy', [cultureinfo]::InvariantCulture)
# 现在 $parsedBDate -le $today 可正常工作。
希望这对您有所帮助。如果您需要更多翻译,请告诉我。
<details>
<summary>英文:</summary>
For _chronological_ comparison, parse your date _strings_ into `[datetime]` ([`System.DateTime`](https://learn.microsoft.com/en-US/dotnet/api/System.DateTime)) instances, as [Olaf](https://stackoverflow.com/users/9196560/olaf) suggests:
Get today's date as a [datetime] instance.
$today = (Get-Date).Date
...
Parse the CSV column value into a [datetime] instance.
$parsedBDate =
[datetime]::ParseExact($Item.BDate, 'dd.MM."yyyy"', [cultureinfo]::InvariantCulture)
Now $parsedBDate -le $today works as intended.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论