繁体   English   中英

将csv行导入到Powershell中,指定日期大于

[英]Importing csv rows to powershell, with date specified as greater than

我有两个csv文件。 一个带有AD的报告,其中包含上个月创建的帐户,第二个是手动保存的数据库,理论上应该包含相同的信息,但来自公司的所有历史记录,还需要一些其他数据来进行会计处理。 我将AD报表导入到Powershell,现在需要导入数据库的特定行。 我需要的行由“添加日期”列中的值定义。 我只需要导入日期超过特定值的行。 我有以下代码:

$Report = Read-Host "File name" #AD report, last ten chars are date of report creation, in format yyyy-MM-dd 
$Date_text = $Report.Substring($Report.get_Length()-10)
$Date = Get-Date -Date $Date_text
$Date_limit = (($Date).AddDays(-$Date.Day)).Date
$Date_start = $Date_limit.AddMonths(-1)
$CSVlicence = Import-Csv $Database -Encoding UTF8 | 
where {(Where-Object {![string]::IsNullOrWhiteSpace($_.'Date added')} |
ForEach-Object{$_.'Date added' = $_.'datum Pridani' -as [datetime] $_}) -gt $Date_start}

这样运行时,不会导入任何内容。 没有这种条件,数据库就可以成功导入,但是它非常庞大,脚本的其余部分将永远存在。 因此,我只需要处理相关数据。 我不在乎,当Date_limit是9月30日时,Date_start将是8月30日而不是8月31日。这只是几行,但是如果所有内容都被导入,那么这10年左右的时间真的是永远的。

因此,根据您当前的逻辑,它会根据您的约束条件过滤PSCustomObject ,这是处理它的错误方法,因为对象中的任何项目都会导致其被过滤掉。 您要过滤源。

$Report = Read-Host -Prompt 'Filename'
## Grabs the datestamp at the end
$Date = Get-Date -Date $Report.Substring($Report.Length - 10)
## Grabs last day of previous month
$Limit = $Date.AddDays(-$Date.Day)
## Grabs last day of two months ago, inaccuracy of one day
$Start = $Limit.AddMonths(-1)

Get-Content -Path $Database -TotalCount 1 | Set-Content -Path 'tempfile'
Get-Content -Path $Database -Encoding 'UTF8' |
    ## Checks that the entry has a valid date entry within limits
    ForEach-Object {
      ## For m/d/yy or d/m/yy variants, try
      ## '\d{1,2}\/\d{1,2}\/\d{2,4}'
      If ($_ -match '\d{4}-\d{2}-\d{2}')
      {
        [DateTime]$Date = $Matches[0]
        If ($Date -gt $Start -and $Date -lt $Limit) { $_ }
      }
    } |
    Add-Content -Path 'tempfile'

$CSV = Import-Csv -Path 'tempfile' -Encoding 'UTF8'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM