如何为每个匹配生成唯一Guid

时间:2017-09-13 14:21:13

标签: regex powershell guid

我试图编写一个在找到匹配项时生成新GUID的脚本。我的问题是我一直为所有匹配生成相同的GUID。 如何在不为所有匹配生成相同GUID的情况下执行此操作?

$testString = @"
    [assembly: Guid Should Replace]
    [assembly: Guid Should Replace]    
    [assembly: Guid Should Replace]
"@
    #expected output
    #[assembly: "unique guid"]


    function ReplaceWithNewGuid {
        param($content)
        $retval = ($content -ireplace '(?m)(\[assembly: Guid.*$)+', "[assembly: Guid(`"$([guid]::NewGuid())`"]`)")
        return $retval
    }

    ReplaceWithNewGuid($testString)

实际输出示例:

[议员:Guid(" 29e784aa-ba4a-4a45-85b8-d6b52916b539"])

[议员:Guid(" 29e784aa-ba4a-4a45-85b8-d6b52916b539"])

[议员:Guid(" 29e784aa-ba4a-4a45-85b8-d6b52916b539"])

更新

@Mathias R. Jessen的回答帮助我得到了我需要的东西。我想我可以在powershell中使用.net框架库来实现这一点但是,这可以按预期工作。

function ReplaceWithNewGuid {
    param($content)
    $retval = [regex]::Replace($testString, '(?m)(\[assembly: Guid.*$)+', {param($m) return "[assembly: Guid(`""+ (New-Guid).Guid + "`")]"}, 'IgnoreCase')
    return $retval
}

2 个答案:

答案 0 :(得分:5)

您可以直接使用Regex.Replace(),允许您传递一个脚本块来代替MatchEvaluator委托参数:

$testString = @"
[assembly: Guid Should Replace]
[assembly: Guid Should Replace]    
[assembly: Guid Should Replace]
"@

[regex]::Replace($testString, 'Guid Should Replace', {param($m) return (New-Guid).Guid}, 'IgnoreCase')

你应该看到它返回3个不同的标识符

答案 1 :(得分:-1)

(New-Guid).Guid

Presto,Guid按需提供。

你的功能得到了修复:

function ReplaceWithNewGuid
{
    param($content)

    $retval = ForEach ($Line in ($content -split "`n"))
    {
        $Line -replace 'guid.*$',"Guid(`"$((New-Guid).Guid)`"]"
    }
    Return $retval
}