2010-09-14 70 views
4

我想將文件從一個位置複製到另一個位置,並用字符串替換第一行文本。我幾乎有腳本完成,但也不能令人信服。(見下文)從文件中替換第一行文本

# -- 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 

回答

8

不是一個襯墊,但它的工作原理(與你的路代替test1.txt的和的test2.txt):

.{ 
    "<text to add>" 
    Get-Content test1.txt | Select-Object -Skip 1 
} | 
Set-Content test2.txt 
+0

什麼是「。」意思? – BrokeMyLegBiking 2010-09-14 12:44:38

+1

運營商「。」意思是「在當前上下文中執行下面的腳本塊/命令」。還有操作符「&」 - 「在新的上下文中執行」。在我們的情況下,它確實很重要「。」或「&」;」。「通常工作速度稍快。 – 2010-09-14 12:54:07

+0

哎呀,我的意思是:在我們的情況下並不重要「。」或「&」(奇怪,我無法編輯我的評論) – 2010-09-14 13:24:38

5

在「以一種方式去皮膚的貓」靜脈,你可以用Out-File完成同樣的事情,如果這是你在星期四的偏好。爲了更好地理解流動與單線凝結而寫。

$x = Get-Content $source_file 
$x[0] = "stuff you want to put on first line" 
$x | Out-File $dest_file 

這使用了Get-Content創建數組的事實,每行都是該數組的一個元素。