Set-Content无效

时间:2017-07-10 13:54:06

标签: powershell

基本上,我要做的就是根据行号替换文本文件中的一些文本。在这个例子中,当我运行脚本时,3 Set-Content中只有2个实际工作。但是,当我运行不能使用断点的Set-Content,或突出显示块并单独运行它时,它会神奇地起作用。如果我删除其他两个set-content块,它也可以工作。

我已尝试投放多个Start-Sleep,并尝试使用某些版本的PS 5安装Windows Server 2012 R2和Windows 10. Get-Content在括号内,以确保该操作是在继续之前完成。我试过在每个操作之间放一个Get-Content。完整脚本在第一个和最后一个之间有多个Set-Content,无论它们出现在哪个顺序,它们都会失败。

您可以自己测试一下。使用以下内容创建文本文件:

;12.1 - MyName

$ScriptVer = "12.1"

         If $VAR<"1.2.3"

然后运行:

#Declare Paths
$Temp = "\\FileShare\e$\Temp\file.txt"

#Get-Content
$KIXOLD = (Get-Content $Temp)

[decimal]$OLDVER = 12.1
$NEWVER = ($oldver + .1)

#Update Version Number in File - THIS WORKS
#I can put in multiple of these anywhere in the script and they all work
#I can even move this block to the end and it still works
$VerLine = Select-String -Pattern $oldver -Path $temp |
           select -ExpandProperty LineNumber |
           select -Index 1
$KIXOLD[$VerLine - 1] = "`$ScriptVer = `"$NEWVER`""
$KIXOLD | Set-Content $temp    

#Find the old version in the text file and replace with new
#This FAILS unless there's a breakpoint or it's run separately
#It doesn't matter if it's the first set-content last, or middle, this fails
$CONV = $KIXOLD | where {$_ -like "*If `$VAR<`"1.2.3`""}
($kixold).Replace("$CONV", "         If `$VAR<`"1.2.4`"") | Set-Content $Temp

#Update notes to contain current version - THIS WORKS
#I can put in multiple of these anywhere in the script and they all work
$linenum = Select-String -Pattern $oldver -Path $Temp |
           select -ExpandProperty LineNumber |
           select -Index 0
$NewLine = [int]$linenum +1
$KIXOLD[$linenum] = ";$NewVer - MyName"
$KIXOLD | Set-Content $temp

您会发现生成的文本文件如下所示:

;12.1 - MyName
;12.2 - MyName
$ScriptVer = "12.2"

         If $VAR<"1.2.3"

它应该是这样的:

;12.1 - MyName
;12.2 - MyName
$ScriptVer = "12.2"

         If $VAR<"1.2.4"

重申一下,如果存在断点或者我单独运行该选择,则会发生If $VAR<"1.2.3" DOES的修改。

无论我尝试什么,只有第一个和最后一个Set-Content工作,除非有一个断点或它是单独运行的。我很茫然,任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:3)

应用于对象的

.Replace方法不会更改该对象!使用

$CONV = $KIXOLD | where {$_ -like "*If `$VAR<`"1.2.3`""}
$KIXOLD = $kixold.Replace("$CONV", "         If `$VAR<`"1.2.4`"")
$KIXOLD | Set-Content $Temp

$CONV = $KIXOLD | where {$_ -like "*If `$VAR<`"1.2.3`""}
($kixold.Replace("$CONV", "         If `$VAR<`"1.2.4`"")) | Set-Content $Temp
$KIXOLD = (Get-Content $Temp)