比较两个逗号分隔的文本文件

时间:2013-07-04 19:01:10

标签: powershell text

我有两个文本文件,一个包含来自远程服务器的注册表设置列表,另一个包含首选注册表设置。文件的格式相同,即:

ServValues.txt

HKLM:\software\Wow6432Node\Policies\Citrix\, Evidence, DesktopKind, Private
HKLM:\software\Wow6432Node\Policies\Citrix\, MultimediaPolicies, EnableRAVE, 1
HKLM:\software\Wow6432Node\Policies\Citrix\, ICAPolicies, ACRLogEvents, 1
HKLM:\software\Wow6432Node\Policies\Citrix\, ICAPolicies, ACRRequireAuth, 0

CorrectValues.txt

HKLM:\software\Wow6432Node\Policies\Citrix\, Evidence, DesktopKind, Private
HKLM:\software\Wow6432Node\Policies\Citrix\, MultimediaPolicies, EnableRAVE, 1
HKLM:\software\Wow6432Node\Policies\Citrix\, ICAPolicies, ACRLogEvents, 0
HKLM:\software\Wow6432Node\Policies\Citrix\, ICAPolicies, ACRRequireAuth, 2

我正在尝试编写一个powershel脚本来比较这两个文件,并且在找到差异时(比如第三行和第四行)创建一个新的日志文件,如:

Discrepancies.txt

  

RemoteSever> HKLM:\ software \ Wow6432Node \ Policies \ Citrix \,ICAPolicies,ACRLogEvents设置为1,应为0

     

RemoteServer>> HKLM:\ software \ Wow6432Node \ Policies \ Citrix \,ICAPolicies,ACRRequireAuth设置为0,应为2

我只是比较任意一行中最后一个逗号之后的值,其余的假设是相同的。 我很难过,有什么小窍门吗?

1 个答案:

答案 0 :(得分:1)

您是否尝试过Compare-Object

如果这不起作用,则必须使用标准for循环:

filter Split-RegSettingLine
{
    param(
        [Parameter(ValueFromPipeline=$true)]
        $Line
    )
    if( $Line -notmatch '^(.*), ([^,]+)$' )
    {
        Write-Error ('Invalid line: {0}' -f $Line)
        return
    }
    $matches[1],$matches[2]
}

$ServerSettings = Get-Content ServValues.txt
$CorrectSettings = Get-Content CorrectValues.txt

if( $ServerSettings.Length -ne $CorrectSettings.Length )
{
    Write-Warning ('Files have different number of lines.  WATCH OUT!')
}

for( $idx = 0 $idx -lt $ServerSettings.Length -and $idx -lt $CorrectSettings.Length; ++$idx )
{
    $serverKey,$serverValue = $ServerSettings[$idx] | Split-RegSettingLine
    $correctKey,$correctValue = $CorrectSettings[$idx] | Split-RegSettingLine

    if( $serverKey -ne $correctKey )
    {
        Write-Error ('Line {0}: mismatched keys: <{1}> <=> <{2}>' -f $idx,$serverKey,$correctKey)
        continue
    }

    if( $serverValue -ne $correctValue )
    {
        Write-Error ('Line {0}: key {1}: set to <{2}>, should be <{3}>' -f $idx,$serverKey,$serverValue,$correctValue
    }
}