PowerShell嵌套的ForEach循环问题

时间:2020-10-28 16:03:44

标签: powershell foreach nested

我正在收集有关电子邮件的数据并导出为CSV。在脚本的这一部分中,我需要生成一个文本文件,该文本文件将在CSV文件中变为2列。第一列(电子邮件主题行文本)已存在于文本文件中,我需要在文件的每一行中添加以下内容:井号标签加上文件名的一部分加上井号标签。标签是我对CSV文件的定界符。

在我的第一个ForEach循环中,我遍历文件夹以生成文件名列表,然后拆分为所需的部分名称。这有效。然后,在第二个ForEach循环中,我尝试遍历文件夹中的文件,并将适当的文件名部分添加到每一行。不仅将所有文件名都附加到一个相关的文件名部分,而且还将所有文件名附加到每一行。

以下是文件“ Inbox_Subject_Reports&Timekeeping.txt”中的当前数据示例:

回复:您的每周业务报告回复:提交时间表

所需的输出:

Re: your weekly business reports#Reports & Timekeeping.txt#
Re: submission of timesheet#Reports & Timekeeping.txt#

但是在同一文件夹中还有其他文件,所以我得到了所有文件名,并且数据正在复制4次:

Re: your weekly business reports#Reports & Timekeeping.txt#Fourth Quarter Returns#
Re: submission of timesheet#Reports & Timekeeping.txt#Fourth Quarter Returns#

Re: your weekly business reports#Reports & Timekeeping.txt#Fourth Quarter Returns#
Re: submission of timesheet#Reports & Timekeeping.txt#Fourth Quarter Returns#

Re: your weekly business reports#Reports & Timekeeping.txt#Fourth Quarter Returns#
Re: submission of timesheet#Reports & Timekeeping.txt#Fourth Quarter Returns#

Re: your weekly business reports#Reports & Timekeeping.txt#Fourth Quarter Returns#
Re: submission of timesheet#Reports & Timekeeping.txt#Fourth Quarter Returns#

是我的ForEach循环的嵌套吗?我需要某种“休息”功能吗?我喜欢PowerShell,并且能够做很多事情,但是我在这里所掌握的知识有限。我宁愿学习如何正确执行此操作,也不要创建麻烦的解决方法。

这是脚本部分:

$dir = "$Filelocation\Inbox_Subfolders\"
$filelist = @(Get-ChildItem $dir)

ForEach ($file in $filelist){
$folder = $file.Name.Split("_")[2]
}
{
$TextToAdd = "#" + $folder + "#"
$output = @()
$fileContent = Get-Content "$Filelocation\Inbox_Subfolders\Inbox_Subject_*.txt"
}
ForEach ($line in $filecontent){
$output += $line + $TextToAdd
$output | Set-Content "$Filelocation\Inbox_Subfolders\Inbox_Subject_*.txt"
}

我花了很多天试图找出嵌套的ForEach循环以及我要去哪里。我愿意以不同的方式取得相同的结果。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

首先:使用适当的缩进。它将使您更容易查看嵌套代码块的开始和结束位置。

这是您想要的吗?

$dir = "$Filelocation\Inbox_Subfolders"

Get-ChildItem $dir -Filter *.txt | foreach {
    $folder = $_.Name.Split("_")[2]
    $TextToAdd = "#" + $folder + "#"
    (Get-Content $_.FullName) | foreach {
        $_ + $TextToAdd
    } | Set-Content $_.FullName
}