繁体   English   中英

如何使用值(从.ps1文件读取)更新另一个.ps1文件的值

[英]How do I use the values (read from a .ps1 file) to update the values of another .ps1 file

我有一个4.ps1文件,看起来像这样

#akabradabra
$one = 'o'

#bibi
$two = 't'

$three = 't'              #ok thr


#four
$four = 'four'

还有一个3.ps1文件,看起来像这样

#akabradabra
$one = 'one'

#biblibablibo
$two = 'two'

$three = 'three'              #ok threer

我的目标是读取来自键值对4.ps1并更新值3.ps1 ,如果新的键值对在介绍4.ps1 ,只需将它们添加到结束3.ps1

我的想法是使用诸如.Split('=').Replace(' ', '')类的字符串函数来提取键,如果键匹配, 3.ps1的整行替换为4.ps1找到的行4.ps1

我知道使用Get-Variable可能会成功,而且如果我将所有键值对转换为.xml.json文件,使用数据也将容易.json但是有人可以告诉我如何我以自己愚蠢的方式工作吗?

这是我的代码

# Ignore this function, this is used to skip certain key-value pairs
#----------------------------------------------------------------------------
Function NoChange($something) {

    switch ($something) {

        '$CurrentPath' {return $true}
        '$pathToAdmin' {return $true}
        '$hostsPathTocompare' {return $true}
        '$logs' {return $true}
        '$LogFile' {return $true}
        default {return $false}

    }
}
#----------------------------------------------------------------------------

$ReadFromVARS = Get-Content $PSScriptRoot\4.ps1
$WriteToVARS = Get-Content $PSScriptRoot\3.ps1

foreach ($oldVar in $ReadFromVARS) {

    if (('' -eq $oldVar) -or ($oldVar -match '\s*#+\w*')) {
        continue
    } elseif ((NoChange ($oldVar.Split('=').Replace(' ', '')[0]))) {
        continue
    } else {
        $var = 0
        #$flag = $false
        while ($var -ne $WriteToVARS.Length) {
            if ($WriteToVARS[$var] -eq '') {
                $var += 1
                continue
            } elseif ($WriteToVARS[$var] -match '\s*#+\w*') {
                $var += 1
                continue
            } elseif ($oldVar.Split('=').Replace(' ', '')[0] -eq $WriteToVARS[$var].Split('=').Replace(' ', '')[0]<# -and !$flag#>) {
                $oldVar
                $WriteToVARS.replace($WriteToVARS[$var], $oldVar) | Set-Content -Path $PSScriptRoot\3.ps1 -Force
                break
                #$var += 1
                #$flag = $true
            } elseif (<#!$flag -and #>($var -eq $WriteToVARS.Length)) {
                Add-Content -Path $PSScriptRoot\3.ps1 -Value $oldVar -Force
                $var += 1
            } else {
                $var += 1
            }
        }
    }
}

我没有遇到任何错误,但是它只更新了一个键值对( $two = t ),并且没有在末尾附加新的键值对。 这是我得到的结果

#akabradabra
$one = 'one'

#biblibablibo
$two = 't'

$three = 'three'              #ok threer

如果我正确理解了您的问题,我认为您正在追求点采购

PowerShell点源运算符将脚本文件带入当前会话范围。 这是一种重用脚本的方法。 脚本文件中定义的所有脚本功能和变量都将成为点源脚本的一部分。 这就像将脚本文件中的文本直接复制并粘贴到脚本中一样。

为了使其可见,请使用点源从文件3.ps1中读取变量,并显示变量及其值。 下一个点源文件4.ps1并再次显示变量:

. 'D:\3.ps1'

Write-Host "Values taken from file 3.ps1" -ForegroundColor Yellow

"`$one   : $one"
"`$two   : $two"
"`$three : $three"
"`$four  : $four"   # does not exist yet

. 'D:\4.ps1'

Write-Host "Values after dot-sourcing file 4.ps1" -ForegroundColor Yellow

"`$one   : $one"
"`$two   : $two"
"`$three : $three"
"`$four  : $four"

结果是

 Values taken from file 3.ps1 $one : one $two : two $three : three $four : Values after dot-sourcing file 4.ps1 $one : o $two : t $three : t $four : four 

如果要将这些变量写回到ps1脚本文件中,则可以:

'one','two','three','four' | Get-Variable | ForEach-Object { 
    '${0} = "{1}"' -f $_.Name,$_.Value
} | Set-Content 'D:\5.ps1' -Force

Theo的答案提供了更简单的方法来做同样的事情

另外,将您的Config文件转换为JSON或XML也将使工作变得更加容易

我最初的想法是同时读取4.ps13.ps1 (这是我的配置文件,我只在其中存储变量并使用switch语句来帮助选择正确的变量),然后用发现的所有差异覆盖3.ps1 ,但我无法让它工作,所以我创建了一个新的5.ps1 ,只需将我需要的所有内容5.ps1

这是我的代码,如果您想将其用于自己的项目:-)

对我来说,障碍是我有switch语句和某些$variables (我在实际项目中)要忽略,因此我使用了一些Regex来避免它。

$ReadFromVARS = Get-Content $PSScriptRoot\4.ps1
$WriteToVARS = Get-Content $PSScriptRoot\3.ps1
New-Item -ItemType File -Path $PSScriptRoot\5.ps1 -Force

Function NoChange($something) {

    switch ($something) {

        '$CurrentPath' {return $true}
        '$pathToAdmin' {return $true}
        '$hostsPathTocompare' {return $true}
        '$logs' {return $true}
        '$LogFile' {return $true}
        default {return $false}

    }
}

$listOfOldVars = @()
$switchStatementStart = "^switch(\s)*\(\`$(\w)+\)(\s)*(\n)*\{"
$switchStatementContent = "(\s)*(\n)*(\t)*\'\w+(\.\w+)+\'(\s)*\{(\s)*\`$\w+(\s)*=(\s)*\@\((\s)*\'\w+(\.\w+)+\'(\s)*(,(\s)*\'\w+(\.\w+)+\'(\s)*)*\)\}"
$switchStatementDefault = "(\s)*(\n)*(\t)*Default(\s)*\{\`$\w+(\s)*=(\s)*\@\((\s)*\'\w+(\.\w+)+\'(\s)*(,(\s)*\'\w+(\.\w+)+\'(\s)*)*\)\}\}"
$switchStatementEnd = "(\s)*(\n)*(\t)*\}"


foreach ($oldVar in $ReadFromVARS) {

    if (('' -eq $oldVar) -or ($oldVar -match '^#+\w*')) {
        continue
    } elseif ((NoChange $oldVar.Split('=').Replace(' ', '')[0])) {
        continue
    } else {
        $var = 0
        while ($var -ne $WriteToVARS.Length) {
            if ($WriteToVARS[$var] -eq '') {
                $var += 1
                continue
            } elseif ($WriteToVARS[$var] -match '^#+\w*') {
                $var += 1
                continue
            } elseif ($oldVar -match $switchStatementStart -or $oldVar -match $switchStatementContent -or $oldVar -match $switchStatementDefault -or $oldVar -match $switchStatementEnd) {
                Add-Content -Path "$PSScriptRoot\5.ps1" -Value $oldVar -Force
                $listOfOldVars += ($oldVar)
                break
            } elseif ($oldVar.Split('=').Replace(' ', '')[0] -eq $WriteToVARS[$var].Split('=').Replace(' ', '')[0]) {
                Add-Content -Path "$PSScriptRoot\5.ps1" -Value $oldVar -Force
                $listOfOldVars += ($oldVar.Remove(0,1).Split('=').Replace(' ', '')[0])
                break
            } else {
                $var += 1
            }
        }
    }
}

foreach ($newVar in $WriteToVARS) {
    if ($newVar.StartsWith('#') -or $newVar -eq '') {
        continue
    } elseif ($newVar -match $switchStatementStart -or $newVar -match $switchStatementContent -or $newVar -match $switchStatementDefault -or $newVar -match $switchStatementEnd) {

    } elseif (($newVar.Remove(0,1).Split('=').Replace(' ', '')[0]) -in $listOfOldVars) {
        continue
    } else {
        Add-Content -Path "$PSScriptRoot\5.ps1" -Value $newVar -Force
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM