通过在最终输出中传递文件名和打印文件名来实现Concat文件 - PowerShell

时间:2016-07-07 13:40:34

标签: powershell batch-file

我有一个文件列表,我希望通过将文件名作为参数将它们组合在一个文件中。另外,在最后一篇文章中,我想在合并之前和之后添加一些硬编码文本。例如:在一个文件夹中,我有5个文件标记为1.txt,2.txt,3.txt,4.txt& 5.txt。 我想要的是1.txt,3.txt和amp;的内容。 5.txt和文件内容类似

'1.txt开始'

然后是1.txt的内容

'1.txt结束'

'3.txt开始'

然后是3.txt的内容

'3.txt结束'

'5.txt开始'

然后是5.txt的内容

'5.txt结束'

我是powershell世界的新手,任何帮助都会非常有帮助。

注意:在任何给定时间我都可以合并n个文件。在我的问题中,我只提供了一个输出的例子。

2 个答案:

答案 0 :(得分:1)

我建议你使用一些小的noobish解决方案,但我认为它会更容易理解:)

$FolderWithFiles = 'C:\Users\YourUser\Desktop\FolderWithFiles\' #You can have many files here
$FilesToMerge = '1.txt', '2.txt', '5.txt'  #List only the ones you need
$OutputFile = 'C:\Users\YourUser\Desktop\FolderWithFiles\Output4.txt' #Set the output file. No need to be existing file'
$i = 0

$FileCollection = Get-ChildItem $FolderWithFiles

foreach($file in  $FileCollection) #Loop trough all files
{
    $i++ #I use it to get the current number of the file

    $CurrentFileName = $file.Name
    $CurrentFilePath = $file.FullName 

    #Check if the files are the one you need
    if($FilesToMerge -contains $CurrentFileName){

        #get their content
       $CurrentContent = Get-Content $CurrentFilePath

       #Create new content
       $NewFileContent = "`r`nFile " + $i + " Starts`r`n" + $CurrentContent + "`r`nFile " + $i + " Ended`r`n " 

       #Append it to a text file 
       $NewFileContent | Out-File -LiteralPath $OutputFile -Append
    }
}

希望它有所帮助。

答案 1 :(得分:0)

我会尝试这样的事情:

Function Merge-Files {
    [CmdLetBinding()]
    Param (
        [ValidateScript({Test-Path $_ -Type Leaf})]
        [Parameter(Mandatory)]
        [String]$File1,
        [ValidateScript({Test-Path $_ -Type Leaf})]
        [Parameter(Mandatory)]
        [String]$File3,
        [ValidateScript({Test-Path $_ -Type Leaf})]
        [Parameter(Mandatory)]
        [String]$File5,
        [Parameter(Mandatory)]
        [String]$Destination
    )

    $ContentFile1 = Get-Content -LiteralPath $File1
    Write-Verbose "Saved content of '$File1' as '$ContentFile1'"

    $ContentFile3 = Get-Content -LiteralPath $File3
    Write-Verbose "Saved content of '$File3' as '$ContentFile3'"

    $ContentFile5 = Get-Content -LiteralPath $File5
    Write-Verbose "Saved content of '$File5' as '$ContentFile5'"

    $NewContent = @"
'1.txt Starts'
$ContentFile1
'1.txt Ends'

'3.txt Starts'
$ContentFile3
'3.txt Ends'

'5.txt Starts'
$ContentFile5
'5.txt Ends'
"@ # Needs to be against the margin

    $NewContent | Out-File -LiteralPath $Destination -Force| Out-Null
    Write-Verbose "New file '$Destination' saved with content '$NewContent'"

}

$Params = @{
    File1 = 'C:\1.txt'
    File3 = 'C:\3.txt'
    File5 = 'C:\5.txt'
    Destination = 'C:\NewFile.txt'
}

Merge-Files @Params -Verbose
# Same as writing: Merge-Files -File1 'C:\1.txt' -File3 'C:\3.txt' ..

这里使用的一些技巧是: