Powershell脚本,用于检查给定文件夹文件夹中是否存在文件列表中的所有文件

问题描述 投票:1回答:3

我需要编写一个powershell脚本,输入文件名列表并检查给定的文件夹。我需要它回显如果列表中的所有文件都存在于文件夹中(如果不是,那么),反之亦然 - 是输入的文件名列表中列出的文件夹中的所有文件。

我是PowerShell的新手,刚刚完成我的第一个脚本来重命名文件夹中的所有文件,我不知道如何输入列表并在检查文件夹中的文件名时迭代它。

我设法写了这样的东西:

$Dir2 = "C:\Users\Administrator\Desktop\testDir2"
$filenames = 'a.txt', 'b.txt', 'c.txt', 'd.txt'
foreach ($filename in $filenames) {
$found=$false; 
Get-ChildItem -Path $Dir2 -Recurse | ForEach-Object {if($filename -eq $_.Name) {Write-Host $filename ' Ok' -foregroundcolor green; $found=$true;CONTINUE }$found=$false;} -END {if($found -ne $true){ Write-Host $filename ' missing' -foregroundcolor red}}
}

我仍然需要检查相反的方式+我需要以某种方式将行从excel表转换为文件名列表

arrays powershell directory filenames
3个回答
1
投票

好的,我有适合我需要的代码:(文件列表在文件中给出,可以是csv)

$Dir2 = 'C:\Users\Administrator\Desktop\testDir2'
$filenames=Get-Content $Dir2\filenamesnoext.csv
foreach ($filename in $filenames) {
$found=$false; 
Get-ChildItem -Path $Dir2 -Recurse | ForEach-Object {if($filename -eq $_.BaseName) {Write-Host 'FILE ' $filename ' Ok' -foregroundcolor green; $found=$true;CONTINUE }$found=$false;} -END {if($found -ne $true){ Write-Host 'FILE ' $filename ' missing in the folder' -foregroundcolor red}}
}
Get-ChildItem -Path $Dir2 -Recurse | ForEach-Object  {$found=$false; foreach ($filename in $filenames) {if($filename -eq $_.BaseName) {Write-Host 'FILE ' $_.BaseName ' was found on the list' -foregroundcolor cyan; $found=$true;BREAK }} if($found -ne $true){ Write-Host 'FILE ' $_.BaseName ' missing on the list of files' -foregroundcolor Magenta} }

0
投票

要从文本文件中检索列表,请使用[Get-Content cmdlet]:

$FileList = Get-Content -Path .\myFileList.txt

要检索文件夹中的文件,请使用Get-ChildItem cmdlet

$Files = Get-ChildItem -Path C:\path\to\folder -File

使用Select-Object获取文件名:

$Files = $Files |Select-Object -Property Name

最后用Compare-Object比较两个列表:

$Discrepancies = @(Compare-Object $FileList $Files)

如果Compare-Object没有返回任何内容,则两个列表之间没有任何区别:

if($Discrepancies.Count -eq 0)
{
    Write-Host "Everything is as expected!"
}

0
投票

如果有人发现它更具可读性(没有跳过循环迭代,只获取文件名一次),这是另一个版本:

    $folder = 'D:\stuff'
    $files = @(
        "one.txt",
        "two.txt"
    )
    Write-Host "Folder: $folder."
    # Get only files and only their names
    $folderFiles = Get-ChildItem -Path $folder -Recurse -File -Name
    foreach ($f in $files) {
        if ($folderFiles -contains $f) { 
            Write-Host "File $f was found." -foregroundcolor green
        } else { 
            Write-Host "File $f was not found!" -foregroundcolor red 
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.