替换文件中的第一行文本

Bro*_*ing 5 powershell

我想将文件从一个位置复制到另一个位置,并用字符串替换第一行文本.我几乎完成了脚本,但不完全...(见下文)

# -- copy the ASCX file to the control templates
$fileName = "LandingUserControl.ascx"
$source = "D:\TfsProjects\LandingPage\" + $fileName
$dest = "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\CONTROLTEMPLATES\LandingPage"
#copy-item $source $dest -Force

# -- Replace first line with assembly name
$destf = $dest + "\" + $fileName
$destfTemp = $destf + ".temp"
Get-Content $destf | select -skip 1 | "<text to add>" + $_) | Set-Content $destfTemp
Run Code Online (Sandbox Code Playgroud)

Rom*_*min 10

不是单行,但它可以工作(用你的路径替换test1.txt和test2.txt):

.{
    "<text to add>"
    Get-Content test1.txt | Select-Object -Skip 1
} |
Set-Content test2.txt
Run Code Online (Sandbox Code Playgroud)

  • 运营商 ”。” 表示“在当前上下文中执行以下脚本块/命令”。还有运算符“&” –“在新上下文中执行”。在我们的情况下,“。”或“&”确实很重要;“。”通常会稍快一些。 (2认同)

Edg*_*eVB 8

在"不止一种皮肤养猫方式"的情况下,你可以用Out-File完成同样的事情,如果这是你周四的偏好.写作是为了更好地理解流动与单线冷凝.

$x = Get-Content $source_file
$x[0] = "stuff you want to put on first line"
$x | Out-File $dest_file
Run Code Online (Sandbox Code Playgroud)

这使用了Get-Content创建数组的事实,每行都是该数组的元素.