使用PowerShell,如何将标题行插入到文本文件的第一行?

wfveoks0  于 2023-06-29  发布在  Shell
关注(0)|答案(2)|浏览(270)

我可以在文件前面加上$newstring的内容。

  1. $sourceDirectory = "C:\SFTP_Root\kcmosdftp\"
  2. $keyword = "User_ID|User_Alt_ID"
  3. $newString = "User_ID|User_Alt_ID|Home_Room_Teacher|User_Group_ID|User_First_Name|User_Middle_Name|User_Last_Name|User_Library|User_Profile|User_Category1|User_Category2|User_Category3|User_Category4|User_Category5|User_Category10|User_Priv_Granted|User_Priv_Expires|Password|Street|City_State|zip|Email|PHONE|User_Birth_Date"
  4. # Set the file name to search for
  5. $fileName = "INBOUND-Student_New_File_Format.txt"
  6. # Get the latest file in the source directory
  7. $latestFile = Get-ChildItem -Path $sourceDirectory | Sort-Object LastWriteTime -Descending | Select-Object -First 1
  8. # Check if the latest file contains the specified keyword
  9. $containsKeyword = (Get-Content $latestFile.FullName) | Select-Object -first 1
  10. if ($containsKeyword -notmatch $keyword) {
  11. # Read the contents of the latest file
  12. $fileContents = Get-Content $latestFile.FullName
  13. # Insert the new string at the beginning of the contents
  14. $fileContents = $newString + "`r`n" + $fileContents
  15. # Determine the new file path
  16. $newFilePath = Join-Path -Path $sourceDirectory -ChildPath "Modified_$($latestFile.Name)"
  17. # Write the modified contents to the new file
  18. $fileContents | Set-Content $newFilePath
  19. Write-Host "Added the string to the first row of $($latestFile.Name). New file saved as $($newFilePath)."
  20. }
  21. else {
  22. Write-Host "The latest file already contains the keyword."
  23. }

不过,新的“修改”文件只有两行。在某些地方,这段代码删除了原始文件($filename)中的所有回车和新行。
不知道我在这里哪里错了。

nhaq1z21

nhaq1z211#

Get-Content默认返回文本文件中的各行,一行接一行,当捕获时,它变成一个 * 数组 *。
因此,以下内容 * 不 * 按预期工作:
$fileContents = $newString + "rn" + $fileContents
它向$newString + "rn"追加一个 array,并且当PowerShell stringifies 一个数组时,它 * 用空格 * 连接其元素(默认情况下;很少使用的$OFS首选项变量可以改变这一点);尝试"foo: " + 1, 2, 3,它将产生逐字的foo: 1 2 3
在您的情况下,最简单且性能更好的解决方案是使用Get-Content-Raw开关将文件读取为 * 单个多行 * 字符串,在这种情况下,字符串连接将按预期工作。

  1. $fileContents = Get-Content -Raw $latestFile.FullName

但是,考虑到Set-Content的工作方式,您甚至不需要字符串连接,并且可以传递两个字符串-新的标题行和带有现有文件内容的多行字符串- * 分开 *:

  1. $newString, $fileContents | Set-Content $newFilePath
vaqhlq81

vaqhlq812#

更改以下内容:

  1. if ($containsKeyword -notmatch $keyword) {
  2. # Read the contents of the latest file
  3. $fileContents = Get-Content $latestFile.FullName

To(注意-Raw的用法):

  1. if ($containsKeyword -notmatch $keyword) {
  2. # Read the contents of the latest file
  3. $fileContents = Get-Content $latestFile.FullName -Raw

这样$fileContents就变成了一个单个多行字符串,而不是一个字符串数组
当你试图在操作的左手边将一个字符串与一个数组连接起来时,该数组被强制转换为字符串,因此由$OFS(默认情况下是一个空格``)连接。
示例:

  1. $myArr = 'foo', 'bar', 'baz'
  2. $newString = 'hello world'
  3. $newString + "`r`n" + $myArr

输出:

  1. hello world
  2. foo bar baz

而不是你所期望的:

  1. hello world
  2. foo
  3. bar
  4. baz
展开查看全部

相关问题