- VBScript: вызов интерактивного диалога открытия файла
- Сообщения 8
- 1 Тема от The gray Cardinal 2006-07-19 22:50:33
- Тема: VBScript: вызов интерактивного диалога открытия файла
- 2 Ответ от The gray Cardinal 2006-07-19 22:51:50
- Re: VBScript: вызов интерактивного диалога открытия файла
- 3 Ответ от mozers 2007-11-30 11:02:35 (изменено: mozers, 2007-12-01 00:41:02)
- Re: VBScript: вызов интерактивного диалога открытия файла
- 4 Ответ от The gray Cardinal 2007-11-30 22:35:50
- Re: VBScript: вызов интерактивного диалога открытия файла
- 5 Ответ от The gray Cardinal 2007-12-13 22:35:38
- Re: VBScript: вызов интерактивного диалога открытия файла
- 6 Ответ от The gray Cardinal 2009-02-28 13:25:51
- Re: VBScript: вызов интерактивного диалога открытия файла
- 7 Ответ от The gray Cardinal 2009-02-28 14:52:10
- Re: VBScript: вызов интерактивного диалога открытия файла
- 8 Ответ от wisgest 2020-11-10 03:14:01 (изменено: wisgest, 2020-11-10 03:41:45)
- Re: VBScript: вызов интерактивного диалога открытия файла
- Диалог выбора файла /папки из пакетного скрипта Windows
- 8 ответов
- Браузер файлов
- Браузер папок
- Windows Script Host
- Выбор файла
- Выбор папки
- Пакетное + PowerShell + C # решение для полиглота
- File / folder chooser dialog from a Windows batch script
- 9 Answers 9
- File Browser
- Folder Browser
- Hey, Scripting Guy! Can I Open a File Dialog Box with Windows PowerShell?
VBScript: вызов интерактивного диалога открытия файла
Чтобы отправить ответ, вы должны войти или зарегистрироваться
Сообщения 8
1 Тема от The gray Cardinal 2006-07-19 22:50:33
- The gray Cardinal
- Участник
- Неактивен
- Рейтинг : [ 5 | 0 ]
Тема: VBScript: вызов интерактивного диалога открытия файла
Это работает в Windows XP и выше и обеспечивает выбор единственного файла (без множественного выбора файлов). Это диалоговое окно открытия файла фактически используется в апплете панели управления «Учетные записи пользователей» (C:\WINDOWS\system32\nusrmgr.cpl). Вы можете задать фильтры по расширениям файлов (свойство Filter), выбрать фильтр по умолчанию (свойство FilterIndex), задать начальный каталог (свойство InitialDir).
2 Ответ от The gray Cardinal 2006-07-19 22:51:50
- The gray Cardinal
- Участник
- Неактивен
- Рейтинг : [ 5 | 0 ]
Re: VBScript: вызов интерактивного диалога открытия файла
Другой способ выбора файла: библиотека C:\WINDOWS\system32\safrcdlg.dll предоставляет объект «SAFRCFileDlg.FileOpen». Здесь нет практически никаких настроек. Это работает в Windows XP и выше.
3 Ответ от mozers 2007-11-30 11:02:35 (изменено: mozers, 2007-12-01 00:41:02)
- mozers
- Разработчик
- Неактивен
- Рейтинг : [ 23 | 0 ]
Re: VBScript: вызов интерактивного диалога открытия файла
Еще один вариант (работает под любой виндой):
P.S.При возникновении проблем с лицензированием, ответ подскажет Google
4 Ответ от The gray Cardinal 2007-11-30 22:35:50
- The gray Cardinal
- Участник
- Неактивен
- Рейтинг : [ 5 | 0 ]
Re: VBScript: вызов интерактивного диалога открытия файла
Можно вызвать диалог выбора файла, используя ActiveX-объект «InternetExplorer.Application»: создаём страницу с элементом FileUpload ( ) и вызываем его метод click(), что в случае IE имитирует щелчок по кнопке «Обзор»:
Окошко минимизируем, но делаем видимым, т.к. иначе, если будут открыты другие окна IE, диалог будет выводится под ними и о его существовани нельзя будет догадаться; а так он будет либо сам выводится на переднем плане, либо на панели задач будет мигатющая кнопка, позволяющая переключится на него.
Автор примера — wisgest.5 Ответ от The gray Cardinal 2007-12-13 22:35:38
- The gray Cardinal
- Участник
- Неактивен
- Рейтинг : [ 5 | 0 ]
Re: VBScript: вызов интерактивного диалога открытия файла
Ещё один вариант использования MSComDlg.CommonDialog, на этот раз на JScript.
Пример опубликовал Large Null.
6 Ответ от The gray Cardinal 2009-02-28 13:25:51
- The gray Cardinal
- Участник
- Неактивен
- Рейтинг : [ 5 | 0 ]
Re: VBScript: вызов интерактивного диалога открытия файла
Бесплатный COM-сервер JSDlgBox.dll предоставляет упрощённые методы для вывода окон выбора и сохранения файлов, а также окон выбора цвета. Методы не имеют никаких параметров. Дистрибутив (архив) компонента имеет размер чуть более 10 Кб. Пример:
Похожие методы предоставляет бесплатный компонент JSForm.dll.
7 Ответ от The gray Cardinal 2009-02-28 14:52:10
- The gray Cardinal
- Участник
- Неактивен
- Рейтинг : [ 5 | 0 ]
Re: VBScript: вызов интерактивного диалога открытия файла
Бесплатный COM-сервер JSSys3.dll предоставляет методы для вывода окон выбора файлов (в т.ч. нескольких), для сохранения файла, для вывода окон выбора цвета, выбора папки. Пример:
8 Ответ от wisgest 2020-11-10 03:14:01 (изменено: wisgest, 2020-11-10 03:41:45)
- wisgest
- Разработчик
- Неактивен
- Рейтинг : [ 25 | 0 ]
Re: VBScript: вызов интерактивного диалога открытия файла
Проверил работоcпособность совместно с IE11 моего решения 2007 года: оказалось, каталог в пути к выбранному файлу подменяется на C:\fakepath\ (подобное поведение, по-видимому, имеет место и в немного более ранних выпусках IE).
Но всё работает как надо, если заменить
Диалог выбора файла /папки из пакетного скрипта Windows
Как правило, обращение к пользователю с просьбой указать имя файла для пакетного сценария — сложная задача, не требующая орфографических ошибок, кавычек вокруг путей с пробелами и т. д. К сожалению, пользователи не очень известны за точность. В ситуациях, когда местоположение входного файла неизвестно до времени выполнения, использование графического интерфейса пользователя для выбора файла снижает вероятность ошибки пользователя.
Есть ли способ вызвать средство выбора файлов графического интерфейса или папки в стиле File. Open из пакетного сценария Windows?
Если у пользователя сценария установлен PowerShell или .NET, это возможно. Смотрите ответ ниже.
Мне также интересно посмотреть, какие другие решения может предложить кто-либо еще.
8 ответов
Браузер файлов
Обновление 2016.3.20.
Поскольку PowerShell в настоящее время является встроенным компонентом практически всех современных установок Windows, я заявляю, что откат C # больше не нужен. Если вам все еще нужна совместимость с Vista или XP, я переместил его в новый ответ . Начиная с этого редактирования, я переписываю сценарий как гибрид Batch + PowerShell и включаю возможность выполнять множественный выбор. Гораздо проще читать и настраивать по мере необходимости.
Это приводит к диалогу выбора файла.
Результат выбора выводит You chose C:\Users\me\Desktop\tmp.txt на консоль. Если вы хотите принудительно выбрать один файл, просто измените свойство $f.Multiselect на $false .
(команда PowerShell безжалостно выведена из Просто возиться с блогом .) См. класс OpenFileDialog документация для других свойств, которые вы можете установить, например, Title и InitialDirectory .
Браузер папок
Обновление 2015.08.10.
Поскольку уже существует метод COM для вызова средства выбора папок , довольно легко создать однострочную оболочку PowerShell. который может открыть средство выбора папки и вывести путь.
В методе BrowseForFolder() четвертый аргумент указывает корень иерархии. См. ShellSpecialFolderConstants для список допустимых значений.
В результате появляется диалоговое окно выбора папки.
Результат выбора выводит You chose C:\Users\me\Desktop на консоль.
См. класс FolderBrowserDialog для получения документации. другие свойства, которые вы можете установить, такие как RootFolder . Мои оригинальные решения .NET System.Windows.Forms PowerShell и C # можно найти в редакция 4 этого ответа, если необходимо, но этот метод COM гораздо проще для чтения и обслуживания.
Это должно работать с XP и выше и не требует файла гибрида, он просто запускает mshta с длинной командной строкой:
Windows Script Host
Выбор файла
В Windows XP был загадочный UserAccounts.CommonDialog объект WSH , что позволило VBScript и JScript запустить приглашение выбора файла. По-видимому, это было считается угрозой безопасности и удален в Vista.
Выбор папки
Однако объект WSH Shell.Application BrowseForFolder по-прежнему позволяет создавать диалоговое окно выбора папки. Вот гибридный пакет + пример JScript. Сохраните его с расширением .bat .
В методе BrowseForFolder() четвертый аргумент указывает корень иерархии. Смотрите ShellSpecialFolderConstants список допустимых значений.
Выбор файла /папки может быть сделан с помощью чистого пакета, как показано ниже. Конечно, ощущения и внешний вид не так приятны, как с графическим интерфейсом, но они работают очень хорошо, и, на мой взгляд, они проще в использовании, чем версия с графическим интерфейсом. Метод выбора основан на команде CHOICE, поэтому он должен будет загрузить его в версиях Windows, в которых он отсутствует, и слегка изменить его параметры. Конечно, код может быть легко изменен для использования SET /P вместо CHOICE, но это изменение исключит очень простой и быстрый метод выбора, который требует только одного нажатия клавиши для навигации и выбора.
Еще два способа.
1.Используя гибридный скрипт .bat /hta (должен быть сохранен как bat ). Он может использовать vbscript или javascript, но пример с javascrtipt. Не создает временные файлы. Выбор папки не так прост и потребует внешних библиотек javascript, но выбор файла прост
1.1 — без формы отправки, предложенной rojo (см. комментарии):
2. Так как вы уже используете powershell /net, вы можете создать самоскомпилированный гибрид jscript.net. Для компиляции он не потребует файл temp cs, а будет напрямую использовать встроенный компилятор jscrript.net. код гораздо удобнее для чтения:
Пакетное + PowerShell + C # решение для полиглота
Это то же решение, что и гибрид Batch + PowerShell , но с добавленным в XP запасным компонентом C #, вновь добавленным для XP и совместимость с Vista. Выбор нескольких файлов был добавлен по запросу xNightmare67x .
Для выбора папки для XP или Vista используйте решение WSH или HTA-решение npocmaka .
Другое решение с командой прямого запуска PowerShell в пакетном режиме
Утилита зависит от wxWidgets 3.1.x, так что вы можете собрать ее для других операционных систем.
File / folder chooser dialog from a Windows batch script
Typically, asking the user to supply a file name to a batch script is a messy affair, requiring no misspellings, quotes around paths with spaces, and so forth. Unfortunately, users aren’t well-known for accuracy. In situations where input file location is not known until runtime, using a GUI for file selection input reduces the likelihood of user error.
Is there a way to invoke a File. Open style gui file chooser or folder chooser from a Windows batch script?
If the script user has PowerShell or .NET installed, it is possible. See the answer below.
I’m also interested to see what other solutions anyone else can offer.
9 Answers 9
File Browser
Update 2016.3.20:
Since PowerShell is a native component of pretty much all modern Windows installations nowadays, I’m declaring the C# fallback as no longer necessary. If you still need it for Vista or XP compatibility, I moved it to a new answer. Starting with this edit, I’m rewriting the script as a Batch + PowerShell hybrid and incorporating the ability to perform multi-select. It’s profoundly easier to read and to tweak as needed.
This results in a file chooser dialog.
The result of a selection outputs You chose C:\Users\me\Desktop\tmp.txt to the console. If you want to force single file selection, just change the $f.Multiselect property to $false .
(PowerShell command mercilessly leeched from the Just Tinkering Blog.) See the OpenFileDialog Class documentation for other properties you can set, such as Title and InitialDirectory .
Folder Browser
Update 2015.08.10:
Since there is already a COM method for invoking a folder chooser, it’s pretty easy to build a PowerShell one-liner that can open the folder chooser and output the path.
In the BrowseForFolder() method, the fourth argument specifies the root of the hierarchy. See ShellSpecialFolderConstants for a list of valid values.
This results in a folder chooser dialog.
The result of a selection outputs You chose C:\Users\me\Desktop to the console.
Hey, Scripting Guy! Can I Open a File Dialog Box with Windows PowerShell?
September 1st, 2009
Hey, Scripting Guy! I am a faithful reader of the Hey, Scripting Guy! articles and have been a Dr. Scripto fan for years. I love your new TechNet Script Center Gallery too by the way. It is much easier to use and to locate scripts than what you had before. I had no idea you had so many scripts up there. WOW! Anyway, I have this script that I have used for a while that I got off the old Script Repository that creates a common dialog box to open a file explorer window. The problem is the script does not work on Windows Vista, and I have also tried it on Windows 7 and it does not work there either. Is there any easy way to open a file dialog box so that I can use a file picker to select a file path instead of having to type in a long file name and location?
Hello PG, Microsoft Scripting Guy Ed Wilson here. Ah, the old UserAccounts.CommonDialog problem. There was an article posted way back in January 2005 called, How Can I Show Users a Dialog Box for Selecting Files? Along with the script you found on the Script Repository, that is about it for documentation. As far as I can recall, I never saw any documentation about the UserAccounts.CommonDialog object on MSDN, so it was an undocumented object. (I actually had another question a while back that I answered during Quick-Hits Friday .) Using undocumented objects is always an iffy proposition at best, but it is also fun — until your scripts start to break. The UserAccounts.CommonDialog object was removed from Windows Vista because of security concerns.
You can accomplish the same thing, in a very similar manner as a matter of fact, by using Windows PowerShell. I have taken the liberty of writing a pretty cool function that is called Get-FileName that you will be able to use to accomplish your file-picking needs. The good thing is that the Get-FileName function uses a standard .NET Framework class that is documented on MSDN, so it will be easy for you to add additional capabilities to the function if you desire to do so. I have placed the function in a script that I call Get-FileNameFunction.ps1, so you will be able to easily play around with the function, get familiar with it, and do some exploration with it. After you get it tuned the way you like it, you may want to consider placing it in a function library or even putting it in your Windows PowerShell profile. The complete Get-FileNameFunction.ps1 script is seen here.
Function Get-FileName($initialDirectory)
<
[System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) |
Out-Null$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
> #end function Get-FileName# *** Entry Point to Script ***
Get-FileName -initialDirectory “c:fso”
The Get-FileName function begins by using the Function keyword to define the function, followed by the function name, and then the input parameter. The function name uses the two part Verb-Noun naming standard that is important for Windows PowerShell 2.0. The input parameter is defined inside the parentheses by the variable $initialDirectory. This variable will have a scope inside the Get-FileName function. The function then opens with a script block, which is delimited by a pair of curly brackets. The opening curly bracket immediately follows the function declaration. The function declaration, input variable, and opening curly bracket are seen here.
Next we will need to load the .NET Framework assembly that contains the ability to create Windows forms. To do this in Windows PowerShell 1.0, you must use the LoadWithPartialName static method from the System.Reflection.Assembly .NET Framework class.
(Actually there is another method to load the assembly, but it is worse than this one, and I will not go over it right now. To be fully transparent, the LoadWithPartialName static method is deprecated. However, it has been deprecated for several versions of the .NET Framework, and has not been made obsolete yet, I suspect partially because the other method is so much worse. )
The LoadWithPartialName static method takes the name of the assembly that contains the .NET Framework classes you want to use. This is important because you will not always know the name of the assembly, unless you look it up on MSDN. Today we will be using the System.Windows.Forms.OpenFileDialog .NET Framework class. When we look at the class reference information on MSDN at the top of the class page, it tells you the namespace and the assembly. In this example, the OpenFileDialog class resides in the System.Windows.Forms namespace. The assembly is also named System.Windows.Forms. (Sometimes, the assembly name and the namespace name are different. These are occasions when you must get familiar with the MSDN documentation.) This is seen here:
Because I always refer to .NET Framework classes by their full name, I always know the namespace. This is because the System.Windows.Forms.OpenFileDialog class resides in the System.Windows.Forms namespace. Only the last part of the name is the actual class name. The first portion (System.Windows.Forms) points to the namespace in which the class resides. Knowing about the .NET Framework class namespaces is a great way to find other classes that are related to a common topic. Because this week we are looking at creating Windows PowerShell scripts that use graphical components, it makes sense to open MSDN and peruse the System.Windows.Forms .NET Framework namespace. This is kind of like going to the library, finding a single book on a topic such as big band music in the United States, going to the open stacks, and looking around in that general area for other books about big band music. It is a great way to find interesting books, and by extraction, the technique is a great way to find interesting .NET Framework classes.
When you call the LoadWithPartialName static method, it provides feedback when the assembly is loaded. If the assembly is not loaded, because it is not found or it is spelled incorrectly, no error is generated. Because of this, you will want to insure that the code is working properly. I like to test this inside a Windows PowerShell console. This is seen here:
PS C:> [System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”
)GAC Version Location
— ——- ——–
True v2.0.50727 C:WINDOWSassemblyGAC_MSILSystem.Windows.Forms2.0….Once I know it is working properly, I pipe the returned information to the Out-Null cmdlet to remove the distracting feedback mechanism. This is seen here:
It is time to create an instance of the System.Windows.Forms.OpenFileDialog .NET Framework class. To do this you will want to use the New-Object cmdlet and give it the full name of the .NET Framework class you are working with. Store the resulting instance of an OpenFileDialog class in a variable named $OpenFileDialog. This is seen here:
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
After you have an instance of the OpenFileDialog class, you can assign values for a couple of properties. The initialDirectory property is used to control where the file dialog box will open. This is something that is best left up to the script to decide, so I decided to use a variable here (the same one that is passed to the function) to control the initial location. A cool thing to do is to store the location in the registry and to read the value from the registry each time the function is called. In this way, the file dialog box will always return to the last used location. The Filter property is used to configure which files are displayed in the dialog box. The filter string contains a description of the filter, followed by the vertical bar (|), and the filter pattern. You are allowed to have multiple filters as long as you separate each filter by a semicolon. The filter pattern I have defined is a simple one that shows all files. This is seen here:
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”To show the dialog box, you call the ShowDialog method. Because the method will return status information to the Windows PowerShell console, I pipe the return to the Out-Null cmdlet as seen here:
Windows PowerShell functions always return a value. There is little need to use the Return statement to return the value. When the filename property is neither captured in a variable nor written out, it will be returned to the calling code. This makes it easy to use the returned filename that was selected in the dialog box for other purposes. After we have returned the file name and closed the curly brackets, the function is complete. When closing curly brackets to close out a function, I consider it to be a best practice to always include an ending comment character that states the curly bracket is ending the function and the name of the function. This practice makes your code much easier to read. This is seen here:
> #end function Get-FileName
The entry point to the script is simple; I pass a path to the initialDirectory parameter when I call the Get-FileName function. This is seen here:
Get-FileName -initialDirectory “c:fso”
When the script runs, the Open dialog box that is seen here appears:
PG, thank you for your kind words, and thank you for asking us to look at Open file dialog boxes. Join us tomorrow as graphical Windows PowerShell week continues. If you want to know what we will be looking at tomorrow, follow us on Twitter or Facebook. If you have any questions, send e-mail to scripter@microsoft.com or post it on the Official Scripting Guys Forum. See you tomorrow. Until then, take care and happy scripting.
Ed Wilson and Craig Liebendorfer, Scripting Guys