问题
I need to amend the code given so that the code selects multiple files at once. After file selection, I want to save the amount of files selected in a variable. I also need a variable to save the directory path of the file.
For example: C: \Users\Andrew\Desktop
. And finally, I need another variable to save the extension of the selected files (I'm assuming all files have the same extension). Example: In the File.txt file, txt
is saved. I hope you can help me.
rem preparation command
set pwshcmd=powershell -noprofile -command "&{[System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null;$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog; $OpenFileDialog.ShowDialog()|out-null; $OpenFileDialog.FileName}"
rem exec commands powershell and get result in FileName variable
for /f "delims=" %%I in ('%pwshcmd%') do set "FileName=%%I"
echo %FileName%
回答1:
If not fluent in multiple script languages it's always difficult to combine them.
You should develop your solution in PowerShell and if really neccessary wrap it in batch once it works as expected.
OpenFileDialog
needs some more settings before invoking the .ShowDialog()
method:
$OpenFileDialog.Multiselect = $true
$OpenFileDialog.Filter = 'TXT (*.txt)| *.txt'
$OpenFileDialog.InitialDirectory = [Environment]::GetFolderPath('Desktop')
Also the result of a Multiselect is returned in the FileNames
property, note the plural.
The whole PowerShell part with the variable name shorted to $OFD
[System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms')|Out-Null
$OFD = New-Object System.Windows.Forms.OpenFileDialog
$OFD.Multiselect = $True
$OFD.Filter = 'TXT (*.txt)| *.txt'
$OFD.InitialDirectory = [Environment]::GetFolderPath('Desktop')
$OFD.ShowDialog()|out-null
$OFD.FileNames
As Aacini hinted use an array variable to receive the file names in batch
:: Q:\Test\2018\09\09\SO_52240766.cmd
@Echo off & Setlocal EnableDelayedExpansion
rem preparation command
set pwshcmd=powershell -NoP -C "[System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms')|Out-Null;$OFD = New-Object System.Windows.Forms.OpenFileDialog;$OFD.Multiselect = $True;$OFD.Filter = 'TXT (*.txt)| *.txt';$OFD.InitialDirectory = [Environment]::GetFolderPath('Desktop');$OFD.ShowDialog()|out-null;$OFD.FileNames"
rem exec commands powershell and get result in FileName variable
Set i=0
for /f "delims=" %%I in ('%pwshcmd%') do (
Set /A i+=1
set "FileName[!i!]=%%I"
)
If %i% gtr 0 (
Echo %i% files selected
Set FileName
) else (
Echo no files selected
)
Sample output
15:39:24 Q:\Test\2018\09\09________________________________________
> SO_52240766.cmd
2 files selected
FileName[1]=C:\Users\LotPings\Desktop\Dokument1.txt
FileName[2]=C:\Users\LotPings\Desktop\espressif-MAC1.txt
来源:https://stackoverflow.com/questions/52240766/how-to-select-multiple-files-using-the-batch-selector