如何在PowerShell foreach循环中比较字符串到文件

时间:2018-10-08 04:09:59

标签: powershell

如何使用Power Shell脚本将当月与当月修改的文件进行比较。我的代码是工作文件,但它正在读取给定目录中的所有csv文件。我只想阅读当月文件,即2018年10月修改的文件。

请帮帮我,我的目录中总共有6个文件。 3个文件的日期在2018年10月被修改,其余3个文件在2018年9月被修改。 我希望我的脚本检查当月,然后阅读当月的所有csv,即2018年10月

代码:

$files = Get-ChildItem 'C:\Users\212515181\Desktop\Logsheet\*.csv'
$targetPath = 'C:\Users\212515181\Desktop\Logsheet'
$result = "$targetPath\Final.csv"
$curr_month = (Get-Date).Month
$curr_year = (Get-Date).Year

# Adding header to output file 
[System.IO.File]::WriteAllLines($result,[System.IO.File]::ReadAllLines($files[1])[1])


foreach ($file in $files)    
{
    $month = $file.LastWriteTime.ToString()
    $curr_month=(Get-Date).Month

    if ($month= $curr_month)
    {
        $firstLine = [System.IO.File]::ReadAllLines($file) | Select-Object -first 1 
        [System.IO.File]::AppendAllText($result, ($firstLine | Out-String))
        $lines = [System.IO.File]::ReadAllLines($file)
        [System.IO.File]::AppendAllText($result, ($lines[2..$lines.Length] | Out-String))
    }
}

# Change output file name to reflect month and year in MMYYYY format

Rename-Item $result "Final_$curr_month$curr_year.csv"

1 个答案:

答案 0 :(得分:1)

您的比较是错误的。并且将返回$ true导致所有文件被读取
应该是

 if ($month -eq $curr_month)

我还要删除第二个

$curr_month = (get-date).month

在循环之前设置脚本会增加脚本开销