Как заставить Powershell читать 2 файла в подпапке? - PullRequest
0 голосов
/ 12 февраля 2020

В настоящее время у меня есть главная папка с подпапками в другой подпапке, содержащей файл .wav.

C:\TEST\Main Folder

  |Folder A
     |Folder A.1 
        |1.wav
        |2.wav
        |3.wav
        |4.wav

   |Folder B
     |Folder B.1 
        |1.wav
        |2.wav
        |3.wav
        |4.wav

Мне нужен Powershell для случайного выбора и воспроизведения 2 .wav файлов ИЗ КАЖДОГО подпапки в течение 15 секунд, и если есть звук, он помечается как "Да", ДАЛЕЕ "Нет". Эти результаты затем экспортируются в CSV.

Однако на основе этого кода мне удалось найти (и я добавил немного моего). Я получаю результаты только для 2 WAV-файлов в TOTAL . Это должно быть 2 .wav ОТ КАЖДОГО подпапки

Кажется, я не могу понять код:

# Test .wav Files
Add-Type -AssemblyName presentationCore
$mediaPlayer = New-Object system.windows.media.mediaplayer
$myDirectory = "C:\TEST\Main Folder"
$OUTPUT_CSV = "C:\TEST\Main Folder\Test_Audio.csv"

$numFiles = (Get-ChildItem -Path $myDirectory -Filter *.WAV).Count

clear-host;

Write-Host 

"
There are:

$numFiles .wav files detected

"

Read-host -prompt 'Press ENTER to start the Testing - These .wav files will be played for approximately 15 secs for validation. You may hear these play on your laptop/computer (There may be a slight delay due to the network)'

Get-ChildItem -Path $myDirectory -Recurse -Filter '*.wav' | Get-Random -count 2 | `
Foreach-Object{

$Path = $_.FullName
$Folder = $_.Directory.Parent.BaseName
$FolderName = $_.Directory.BaseName
$Filename = $_.Name
$mediaPlayer.open("$Path")
$mediaPlayer.Play()

Start-Sleep 15

    if ($mediaPlayer.HasAudio -eq "True" -and $mediaPlayer.Position -gt "00:00:00"){
        $retVal = "Yes"
        $mediaPlayer.Stop()
    }
    else{
        $retVal = "No"
        $mediaPlayer.Stop()
    }
    #return $retVal

$Path| Sort-Object $Folder | Select-Object `

    @{n="Parent Folder";e={$Folder}},`
    @{n="Subfolder";e={$Foldername}},`
    @{n="Link to File";e={$Path}},`
    @{n="Playing?";e={$retVal}}`

} | Export-Csv $OUTPUT_CSV -NoTypeInformation 

Write-Host 

"

Testing Complete

Extract saved here

$OUTPUT_CSV 

The Extract will automatically open now.

"

# start Excel
$excel = New-Object -comobject Excel.Application

#open file
$WorkBook = $excel.Workbooks.Open($OUTPUT_CSV)

#make it visible (just to check what is happening)
$excel.Visible = $true


Read-host -prompt "Please check the CSV extract. Press enter to complete this process..."
clear-host;

Ответы [ 2 ]

0 голосов
/ 13 февраля 2020

Что касается того, что вы ищете, это кажется немного не в порядке. Возьмите ваш код и настройте его только на go для основной c части получения файла и списка в файл CSV.

# Test .wav Files
Add-Type -AssemblyName presentationCore
$mediaPlayer = New-Object system.windows.media.mediaplayer
$myDirectory = "D:\Temp\ParentFolder"
$OUTPUT_CSV = "D:\Temp\ParentFolder\Test_Audio.csv"

<#
If you are after 2 wav files per folder, why are you only asking for the count here?
Each folder may have a different count and file name, right? 
#>

# $numFiles = (Get-ChildItem -Path $myDirectory -Filter *.WAV).Count


foreach (
            $Dir in Get-ChildItem -Path $myDirectory -Recurse -Filter '*.wav' | 
            select -ExpandProperty DirectoryName -Unique
        ) 

        {
            $numFiles = (Get-ChildItem -Path $Dir -Filter *.WAV).Count

            Read-host -prompt "
            `nThe folder $Dir contains a total of $numFiles wav files.`n
            Press ENTER to start the Testing`n
            These .wav files will be played for 
            approximately 15 secs for validation. You may hear these play on your 
            laptop/computer (There may be a slight delay due to the network)
            "
            Get-ChildItem -Path $Dir | 
            Get-Random -Count 2
        }

<#

Also, note that gets random will not always give you that could be depending on the number for total files you may have in a folder and when/where you call it.

Example: 
Each of my folders only have 3 wav files.

# Results

The folder D:\Temp\ParentFolder contains a total of 3 wav files.

            Press ENTER to start the Testing

            These .wav files will be played for 
            approximately 15 secs for validation. You may hear these play on your 
            laptop/computer (There may be a slight delay due to the network)
            : 



    Directory: D:\Temp\ParentFolder


Mode                LastWriteTime         Length Name                                                                                                         
----                -------------         ------ ----                                                                                                         
d-----        12-Feb-20     12:37                ChildFolder                                                                                                  
-a----        28-Aug-07     13:08        2646058 ThumperLong.wav                                                                                              


The folder D:\Temp\ParentFolder\ChildFolder contains a total of 3 wav files.

            Press ENTER to start the Testing

            These .wav files will be played for 
            approximately 15 secs for validation. You may hear these play on your 
            laptop/computer (There may be a slight delay due to the network)
            : 



    Directory: D:\Temp\ParentFolder\ChildFolder


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        23-Apr-99     18:22         668440 WELCOM98.WAV
d-----        12-Feb-20     12:37                GrandchildFolder


The folder D:\Temp\ParentFolder\ChildFolder\GrandchildFolder contains a total of 3 wav files.

            Press ENTER to start the Testing

            These .wav files will be played for 
            approximately 15 secs for validation. You may hear these play on your 
            laptop/computer (There may be a slight delay due to the network)
            : 



    Directory: D:\Temp\ParentFolder\ChildFolder\GrandchildFolder


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        28-Aug-07     13:08        2646058 ThumperLong.wav
-a----        28-Aug-07     13:05         683670 ThumperShort.wav

So, to avoid this, do this...
#>


foreach (
            $Dir in Get-ChildItem -Path $myDirectory -Recurse -Filter '*.wav' | 
            select -ExpandProperty DirectoryName -Unique
        ) 

        {
            $numFiles = (Get-ChildItem -Path $Dir -Filter *.WAV).Count

            Read-host -prompt "
            `nThe folder $Dir contains a total of $numFiles wav files.`n
            Press ENTER to start the Testing`n
            These .wav files will be played for 
            approximately 15 secs for validation. You may hear these play on your 
            laptop/computer (There may be a slight delay due to the network)
            "
            Get-ChildItem -Path $Dir -file | 
            Get-Random -Count 2
        } 

<#
# Results

The folder D:\Temp\ParentFolder contains a total of 3 wav files.

            Press ENTER to start the Testing

            These .wav files will be played for 
            approximately 15 secs for validation. You may hear these play on you
r 
            laptop/computer (There may be a slight delay due to the network)
            : 



    Directory: D:\Temp\ParentFolder


Mode                LastWriteTime         Length Name                          
----                -------------         ------ ----                          
-a----        23-Apr-99     18:22         668440 WELCOM98.WAV                  
-a----        28-Aug-07     13:08        2646058 ThumperLong.wav               


The folder D:\Temp\ParentFolder\ChildFolder contains a total of 3 wav files.

            Press ENTER to start the Testing

            These .wav files will be played for 
            approximately 15 secs for validation. You may hear these play on your 
            laptop/computer (There may be a slight delay due to the network)
            : 



    Directory: D:\Temp\ParentFolder\ChildFolder


Mode                LastWriteTime         Length Name                          
----                -------------         ------ ----                          
-a----        28-Aug-07     13:05         683670 ThumperShort.wav              
-a----        28-Aug-07     13:08        2646058 ThumperLong.wav               


The folder D:\Temp\ParentFolder\ChildFolder\GrandchildFolder contains a total of
 3 wav files.

            Press ENTER to start the Testing

            These .wav files will be played for 
            approximately 15 secs for validation. You may hear these play on you
r 
            laptop/computer (There may be a slight delay due to the network)
            : 



    Directory: D:\Temp\ParentFolder\ChildFolder\GrandchildFolder


Mode                LastWriteTime         Length Name                          
----                -------------         ------ ----                          
-a----        28-Aug-07     13:05         683670 ThumperShort.wav              
-a----        28-Aug-07     13:08        2646058 ThumperLong.wav

Since you are looping thru file, put the Export -Append in the loop, not outside. THat error you are gettings is because the file creation is not valid. 
#>

foreach (
            $Dir in Get-ChildItem -Path $myDirectory -Recurse -Filter '*.wav' | 
            select -ExpandProperty DirectoryName -Unique
        ) 

        {
            $numFiles = (Get-ChildItem -Path $Dir -Filter *.WAV).Count

            Read-host -prompt "
            `nThe folder $Dir contains a total of $numFiles wav files.`n
            Press ENTER to start the Testing`n
            These .wav files will be played for 
            approximately 15 secs for validation. You may hear these play on your 
            laptop/computer (There may be a slight delay due to the network)
            "
            Get-ChildItem -Path $Dir | 
            Select-Object -Property Directory, PSChildName, FullName | 
            Get-Random -Count 2 | 
            Export-Csv -NoTypeInformation  -Path $OUTPUT_CSV -Append
        }

Import-Csv -Path $OUTPUT_CSV

# Results
<#
Directory                                         PSChildName                FullName                                                                    
---------                                         -----------                --------                                                                    
D:\Temp\ParentFolder                              ParentWELCOM98.WAV         D:\Temp\ParentFolder\ParentWELCOM98.WAV                                     
D:\Temp\ParentFolder                              ParentThumperLong.wav      D:\Temp\ParentFolder\ParentThumperLong.wav                                  
D:\Temp\ParentFolder\ChildFolder                  ChildThumperShort.wav      D:\Temp\ParentFolder\ChildFolder\ChildThumperShort.wav                      
D:\Temp\ParentFolder\ChildFolder                  ChildThumperLong.wav       D:\Temp\ParentFolder\ChildFolder\ChildThumperLong.wav                       
D:\Temp\ParentFolder\ChildFolder\GrandchildFolder GrandchildWELCOM98.WAV     D:\Temp\ParentFolder\ChildFolder\GrandchildFolder\GrandchildWELCOM98.WAV    
D:\Temp\ParentFolder\ChildFolder\GrandchildFolder GrandchildThumperShort.wav D:\Temp\ParentFolder\ChildFolder\GrandchildFolder\GrandchildThumperShort.wav
#>


"
`nTesting Complete and is saved here. The extract will automatically open now.
"
# Open file - csv in MS Excel
Start-Process -FilePath 'excel.exe' -ArgumentList $OUTPUT_CSV

Хотя я не совсем уверен, почему подробный текст подскажите ваши усилия, поскольку, если у них есть файл Excel, закрытие, которое завершает сценарий использования, и вы не показали код, который действительно что-то делает после этого. Итак, этот последний Read-Host избыточен.

0 голосов
/ 12 февраля 2020

Вы должны получать случайные предметы из каждого каталога. Изменить:

Get-ChildItem -Path $myDirectory -Recurse -Filter '*.wav' | Get-Random -count 2 | `
Foreach-Object{

$Path = $_.FullName
$Folder = $_.Directory.Parent.BaseName
$FolderName = $_.Directory.BaseName
$Filename = $_.Name
$mediaPlayer.open("$Path")
$mediaPlayer.Play()

Start-Sleep 15

    if ($mediaPlayer.HasAudio -eq "True" -and $mediaPlayer.Position -gt "00:00:00"){
        $retVal = "Yes"
        $mediaPlayer.Stop()
    }
    else{
        $retVal = "No"
        $mediaPlayer.Stop()
    }
    #return $retVal

$Path| Sort-Object $Folder | Select-Object `

    @{n="Parent Folder";e={$Folder}},`
    @{n="Subfolder";e={$Foldername}},`
    @{n="Link to File";e={$Path}},`
    @{n="Playing?";e={$retVal}}`

} | Export-Csv $OUTPUT_CSV -NoTypeInformation

На:

foreach ($Dir in Get-ChildItem -Path $myDirectory -Recurse -Filter '*.wav' | select -ExpandProperty DirectoryName -Unique) {
    Get-ChildItem -Path $Dir | Get-Random -Count 2 | Foreach-Object {
        $Path = $_.FullName
        $Folder = $_.Directory.Parent.BaseName
        $FolderName = $_.Directory.BaseName
        $Filename = $_.Name
        $mediaPlayer.open("$Path")
        $mediaPlayer.Play()

        Start-Sleep 15

            if ($mediaPlayer.HasAudio -eq "True" -and $mediaPlayer.Position -gt "00:00:00"){
                $retVal = "Yes"
                $mediaPlayer.Stop()
            }
            else{
                $retVal = "No"
                $mediaPlayer.Stop()
            }
            #return $retVal

        $Path| Sort-Object $Folder | Select-Object `

            @{n="Parent Folder";e={$Folder}},`
            @{n="Subfolder";e={$Foldername}},`
            @{n="Link to File";e={$Path}},`
            @{n="Playing?";e={$retVal}}`

    } | Export-Csv $OUTPUT_CSV -NoTypeInformation -Append
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...