我正在使用PowerShell脚本解析CSV文件。我想将CSV文件中读取的日期与当前日期进行比较,并执行某些操作或退出处理脚本。以下问题可以帮助我吗?
CSV文件中的日期如下:
交易日期:,2015-12-14
$CurrentTimeStamp = Get-Date
$TradeDate = $CurrentTimeStamp.ToString("yyyyMMdd")
$CheckDate = $TradeDate
TradeDate如上:
$FileTradeDate = $Cols[1]
$TradeDate = $FileTradeDate.ToString("yyyy-MM-dd")
if ($TradeDate -ne $CheckDate) {
$host.Exit()
} else {
$TradeDate = $FileTradeDate
LogWrite $TradeDate
}
我收到以下错误:
Cannot find an overload for "ToString" and the argument count: "1".
At \\multinasdub301\Software\SysAdmin\WebDownloads\ProcessUBSFrescoCCYHDG.ps1:139 char:5
+ $TradeDate = $FileTradeDate.ToString("yyyy-MM-dd")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
答案 0 :(得分:0)
从CSV文件读取的数据已经是一个字符串,从您的示例中看,它似乎已经采用yyyy-MM-dd
格式,因此无需再次将其转换为字符串。您需要使用相同的格式格式化$checkDate
,否则字符串永远不会匹配:
$CheckDate = (Get-Date).ToString('yyyy-MM-dd')
或者您可以将CSV中的日期解析为实际DateTime
值并比较两个日期:
$CheckDate = (Get-Date).Date
$culture = [Globalization.CultureInfo]::InvariantCulture
Import-Csv 'C:\path\to\your.csv' |
Select-Object -Property *, @{n='Trading Date';e={
[DateTime]::ParseExact($_.'Trading Date', 'yyyy-MM-dd', $culture)
}} -Exclude 'Trading Date' |
ForEach-Object {
if ($_.'Trading Date' -eq $CheckDate) {
$TradeDate = $FileTradeDate
LogWrite $TradeDate
}
}