我有一个文件列表,我想通过传递文件名作为参数将它们合并到一个文件中。另外,在最后一个版本中,我想在合并前后添加一些硬编码文本。例如:在文件夹中,我有5个文件标记为1.txt、2.txt、3.txt、4.txt & 5.txt。我想要的是1.txt、3.txt & 5.txt的内容,文件内容类似于
“1.txt开始”
然后是1.txt的内容
“1.txt结束”
'3.txt开始‘
然后是3.txt的内容
'3.txt结束‘
'5.txt开始‘
然后是5.txt的内容
'5.txt结束‘
我对powershell世界很陌生,任何帮助都会很有帮助。
注意:在任何给定的时间,我都可以合并n个文件。在我的问题中,我只提供了一个输出的例子。
发布于 2016-07-07 14:35:50
我建议你一个简单的解决方案,但我认为更容易理解:)
$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
}
}希望能帮上忙。
发布于 2016-07-07 14:14:31
我会尝试这样的方法:
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' ..这里使用的一些技术是:
https://stackoverflow.com/questions/38247039
复制相似问题