首页 > 解决方案 > 有人可以帮我制作这个 PowerShell Recursive

问题描述

我似乎无法让这个 PowerShell 递归遍历所有目录并进行我需要的更改,以确保当我的 terraform 脚本作为 Azure devops 中的构建帐户应用时,它们可以访问我的 git repos 中的模块。

$InputFiles = Get-Item "$(build.artifactstagingdirectory)/Terraform/*.tf"
$OldString  = "git::https://dev.azure.com"
$NewString  = "git::https://$(System.AccessToken)@dev.azure.com"
Write-Host $NewString
$InputFiles | ForEach {
    (Get-Content -Path $_.FullName).Replace($OldString, $NewString) | Set-Content -Path $_.FullName
}

此代码适用于顶级目录,但不处理任何子目录。

我认为某种通配符会起作用,即

$InputFiles = Get-Item "$(build.artifactstagingdirectory)/Terraform/**/*.tf"

但不,它没有。我在 PowerShell 上不是那么强,而且总是觉得它有点违反直觉,所以对于习惯它的人来说,这可能是一个简单的问题。

标签: powershellglob

解决方案


检查此脚本是否适合您:(您可以根据需要更改文件夹路径和字符串)

$FolderPath = "$(build.artifactstagingdirectory)/Terraform/"
$OldString  = "git::https://dev.azure.com"
$NewString  = "git::https://$(System.AccessToken)@dev.azure.com"

foreach($currentFile in Get-ChildItem -Path ($FolderPath) -Include *.tf -Recurse)
{
    If (Get-Content $currentFile.FullName | Select-String -Pattern $OldString) 
    {
        (Get-Content -path $currentFile.FullName -Raw) -replace $OldString, $NewString | Set-Content $currentFile.FullName
    }
}

Write-Information "Done"

推荐阅读