开发者

append text to a file with powershell

开发者 https://www.devze.com 2023-04-08 19:04 出处:网络
I have the following powershell command that recursively loops through all .sql files in a folder ($ScriptFolder) and appends it to another sql file ($TargetFile).

I have the following powershell command that recursively loops through all .sql files in a folder ($ScriptFolder) and appends it to another sql file ($TargetFile).

Get-ChildItem -path "$ScriptFolder" -recurse |?{ ! $_.PSIsContainer } |?{($_.name).contains(".sql")} | %{ Out-File -filepath $TargetFile -inputobject (get-content $_.fullname) -Append }

What I would like to do as each .sql i开发者_如何学Gos appended to the target file, add text to the target file at the point .sql is appended to it and add text after the .sql is appended to the target file.

I am new to powershell, so could anyone outline how i might do this? Thanks


Here's something that might do the trick for you:

Get-ChildItem -recurse -include "*.sql" |
Foreach-Object { Add-Content -Path $targetFile -Value "-- Begin $($_.FullName)--`r`n$(Get-Content $_ | Out-String)--End $($_.FullName)--`r`n"; }

That code will loop through all .sql files recursively, adding their contents to $targetFile as you did. It wraps each addition with --Begin <full path>-- and --End <full path>--. FYI, I pipe the output of Get-Content to Out-String because Get-Content returns an array of objects. If you leave out that pipe, this code will strip newlines from your source files.

0

精彩评论

暂无评论...
验证码 换一张
取 消