更快地在文件夹中查找文件

Find file in folder faster way

我正在寻找最快和最小的 powershell 代码,以便在包含子文件夹的文件夹中查找 app.config 文件。

当找到 app.config 文件时,它将调用我的函数。 有什么建议吗?

评论:代码的小格式修复

在文件夹中快速查找文件

我正在寻找最快和最小的 powershell 代码,以便在包含子文件夹的文件夹中查找 app.config 文件。

当找到 app.config 文件时,它将调用我的函数。有什么建议吗?

我下面的代码只是 app/web.config 的转换,所以我缺少的是一个可以在目录中搜索并找到搜索方式的功能app.config 文件所在的位置。

所以可以说 C:/temp 应该被搜索。在这里我们有

 C:/temp/folder1/app.config 
 C:/temp/folder2/subfolder1/app.config

这将导致两个发现。所以我下面的函数需要调用两次。

param(
$XmlPath,
$XdtPath
)

function XmlDocTransform($xml, $xdt)
{    
    if (!$xml -or !(Test-Path -path $xml -PathType Leaf)) {
        throw "File not found. $xml";
    }

    if (!$xdt -or !(Test-Path -path $xdt -PathType Leaf)) {
        throw "File not found. $xdt";
    }

    $scriptPath = (Get-Variable MyInvocation -Scope 1).Value.InvocationName | split-path -parent
    Add-Type -LiteralPath "$scriptPath\Microsoft.Web.XmlTransform.dll"

    $xmldoc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument;
    $xmldoc.PreserveWhitespace = $true
    $xmldoc.Load($xml);

    $transf = New-Object Microsoft.Web.XmlTransform.XmlTransformation($xdt);

    if ($transf.Apply($xmldoc) -eq $false)
    {
        throw "Transformation failed."
    }

    $xmldoc.Save($xml);
}

XmlDocTransform $XmlPath $XdtPath
Get-ChildItem -Path C:\Temp -Recurse -Filter "app.config" | ForEach-Object { 
   $AppConfigPath = $_.FullName
   XmlDocTransform -XmlPath $AppConfigPath -XdtPath $yourotherpath
}

如果你真的需要它,那么我强烈建议使用 robocopy 来完成这样的任务。 它包含在 Windows 中已有一段时间了。

这是一个开始的代码片段:

$list = New-Object 'Collections.ArrayList'
$files = &robocopy /l "c:\" /s \localhost\c$\nul "app.config" /bytes /ns /njh /njs /np /nc /fp /ndl /xj
foreach($file in $files) {
    $data = $file.split("`t")
    $null = $list.add([tuple]::create([uint64]$data[3], $data[4]))
}
$list