运行脚本时Powershell set-content无法正常工作 - 可能的编译器错误?

时间:2017-06-28 13:04:32

标签: powershell

我想我会发疯但希望能解释这种奇怪的行为。我有一个脚本将KIX文件复制到新位置,检查新旧版本的EXE上的文件版本,然后在多个位置修改KIX文件。以下是简化版。

第一个和最后一个set-content始终有效。检查文件版本后出现的set-content总是在我运行整个脚本时失败(总的来说,对于不同的文件版本,有set-content的多个实例,它们都失败了)。

但是,如果我放入一个断点,或者只是突出显示该部分并运行它,它确实有效。我知道该部分受到了影响,因为我在此块中没有进一步处理,例如多个copy-item

当我说失败时,我的意思是内容没有在文件中更新。没有错误,它只是不更新​​。

我已尝试在每行之间插入多秒start-sleep,但这无济于事。我也尝试通过声明版本而不是运行fileversioninfo来尽可能简单,但它仍然失败。我很难排除故障,因为当我输入断点时,它可以工作。

#Declare Paths
$Temp = "\\NewLocation\e$\Temp"
$path = "\\share\folder"
$FinalDest = "\\FinalRestingPlace\Folder"

#Copy file to Temp
Copy-item "\\OtherShare\file1.kix" $Temp 

#Get-Content
$KIXOLD = (get-content $Temp\file1.kix)

#Increment Version Number
[decimal]$OLDVER = 12.0
$NEWVER = ($oldver + .1)

本作品

#Update Version Number in File 
$VerLine = select-string -Pattern $oldver -path $temp\file1.kix | select -ExpandProperty LineNumber | select -Index 1
$KIXOLD[$VerLine - 1] = "`$ScriptVer = `"$NEWVER`"                                                ; Current Script Version Number"
$KIXOLD | set-content $temp\file1.kix

这失败

if(Test-Path $path)
{
    if(Test-Path "$path\File1.exe")
    {
    #Check Old And new versions
    $NewVersion = [System.Diagnostics.FileVersionInfo]::GetVersionInfo("$path\file1.exe").FileVersion
    $OLDVersion = [System.Diagnostics.FileVersionInfo]::GetVersionInfo("$FinalDest\file1.exe").FileVersion

    #Find the old version in the text file and replace with new
    #This FAILS unless there's a breakpoint or it's run separately
    $CONV = $KIXOLD | where {$_ -like "*If `$VAR<`"$OLDVersion*`""}
    ($kixold).Replace("$CONV", "         If `$VAR<`"$NewVersion`"") | set-content $Temp\file1.kix
    }  
}

本作品

#Update notes to contain current version - THIS WORKS
$linenum = select-string -Pattern $oldver -path $Temp\file1.kix | select -ExpandProperty LineNumber | select -Index 0
$NewLine = [int]$linenum +1
$KIXOLD[$linenum] = ";$NewVer - MyName"
$KIXOLD | set-content $temp\file1.kix

有没有人见过类似的东西,或者对于它失败的原因有任何想法?我已经在Windows Server 2012 R2和Windows 10上测试了相同的结果。

1 个答案:

答案 0 :(得分:0)

我又问了这个问题,得到了答案。对于任何人看:

。应用于对象的替换方法不会更改该对象。使用

$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)