将数组中的文件名与文件结构中的文件进行比较

时间:2015-06-12 15:46:10

标签: arrays powershell file-structure

$folder = filestructure
# Get a recursive list of all folders beneath the folder supplied by the operator
$AllFolders = Get-ChildItem -Recurse -Path $Folder |? {$_.psIsContainer -eq $True}

# Get a list of all files that exist directly at the root of the folder
# supplied by the operator
$FilesInRoot = Get-ChildItem -Path $Folder | ? {$_.psIsContainer -eq $False}
Foreach ($File in ($FilesInRoot))
{
    #Notify the operator that the file is being uploaded to a specific location
    if($Global:successfullymigrated -contains $File){
        Write-Host $File
    }
}

###this part doesn't work
foreach($CurrentFolder in $AllFolders)
{
    # Set the FolderRelativePath by removing the path of the folder supplied 
    # by the operator from the fullname of the folder

    $FolderRelativePath = ($CurrentFolder.FullName).Substring($Folder.Length)
    $FileSource = $Folder + $FolderRelativePath
    $FilesInFolder = Get-ChildItem -Path $FileSource | ? {$_.psIsContainer -eq $False}

    # For each file in the source folder being evaluated, call the UploadFile 
    # function to upload the file to the appropriate location
    Foreach ($File in ($FilesInFolder))
    {
        Write-Host $File
        if($Global:successfullymigrated -contains $File){
            Write-Host $File
        }
    }
}

我上面的代码应该通过一个文件结构并检查是否有任何文件名在数组中(这是一个包含文件名的字符串数组)。我的代码适用于根文件,打印出数组中的所有文件,但是当我们检查除root之外的其他文件夹中的文件时,它不起作用。即使它输出文件结构中的文件。我完全陷入困境。

1 个答案:

答案 0 :(得分:1)

请原谅我,如果我误解了,但我读了这个

  

我上面的代码应该通过一个文件结构并检查是否有任何文件名在数组中

并解释为您只是在寻找与您提供的名称列表完全匹配的文件的文件路径。

所以我有这样的样本应该做到这一点。

$Global:successfullymigrated = @("template.txt","winmail.dat")
$folder = "C:\temp"
Get-ChildItem $folder -recurse | Where-Object{$Global:successfullymigrated -contains $_.Name -and !$_.psIsContainer} | Select-Object -ExpandProperty FullName

您应该能够将此功能合并到您自己的代码中。它输出匹配文件的完整路径。我从根和子结构输出文件的示例。

C:\temp\winmail.dat
C:\temp\docs\template.txt

!$_.psIsContainer是为了确保我们不会在结果中返回文件夹。如果您使用的是PowerShell 3.0或更高版本,那么可以使用-File

Get-ChildItem开关替换它