Writing help files windows

Содержание
  1. Writing Help for PowerShell Modules
  2. Types of Module Help
  3. Placement of Module Help
  4. Getting Module Help
  5. Supporting Updatable Help
  6. Supporting Online Help
  7. Рекомендации по записи в файлы Best practices for writing to files
  8. Удобство и управление Convenience vs. control
  9. Транзакционная модель The transactional model
  10. Распространенные коды ошибок при использовании методов Write классов FileIO и PathIO Common error codes for Write methods of the FileIO and PathIO classes
  11. Дополнительные рекомендации по состояниям файлов, которые могут привести к ошибкам Other considerations for file states that might lead to errors
  12. Данные записываются в файл только в том случае, если операция завершена Data was written to the file if and only if operation completed
  13. Устройства чтения Readers
  14. Файлы из KnownFolders Files from KnownFolders
  15. Конфликты при операциях ввода-вывода Conflicting I/O
  16. Рекомендации по типам файлов Considerations based on file types
  17. Операции ввода-вывода во время приостановки приложения I/O during app suspension
  18. Другие примеры и ресурсы Other examples and resources
  19. Пример кода для повтора файлового ввода-вывода Code example for retrying file I/O example
  20. Синхронизация доступа к файлу Synchronize access to the file

Writing Help for PowerShell Modules

PowerShell modules can include Help topics about the module and about the module members, such as cmdlets, providers, functions and scripts. The Get-Help cmdlet displays the module Help topics in the same format as it displays Help for other PowerShell items, and users use standard Get-Help commands to get the Help topics.

This document explains the format and correct placement of module Help topics, and it suggests guidelines for module Help content.

Types of Module Help

A module can include the following types of Help.

Cmdlet Help. The Help topics that describe cmdlets in a module are XML files that use the command help schema

Provider Help. The Help topics that describe providers in a module are XML files that use the provider help schema.

Function Help. The Help topics that describe functions in a module can be XML files that use the command help schema or comment-based Help topics within the function, or the script or script module

Script Help. The Help topics that describe scripts in a module can be XML files that use the command help schema or comment-based Help topics in the script or script module.

Conceptual («About») Help. You can use a conceptual («about») Help topic to describe the module and its members and to explain how the members can be used together to perform tasks. Conceptual Help topics are text files with Unicode (UTF-8) encoding. The filename must use the about_ .help.txt format, such as about_MyModule.help.txt . By default, PowerShell includes over 100 of these conceptual About Help topics, and they are formatted like the following example.

All of the schema files can be found in the $PSHOME\Schemas\PSMaml folder.

Placement of Module Help

The Get-Help cmdlet looks for module Help topic files in language-specific subdirectories of the module directory.

For example, the following directory structure diagram shows the location of the Help topics for the SampleModule module.

In the example, the placeholder represents one of the paths in the PSModulePath environment variable, such as $HOME\Documents\Modules , $PSHOME\Modules , or a custom path that the user specifies.

Getting Module Help

When a user imports a module into a session, the Help topics for that module are imported into the session along with the module. You can list the Help topic files in the value of the FileList key in the module manifest, but Help topics are not affected by the Export-ModuleMember cmdlet.

You can provide module Help topics in different languages. The Get-Help cmdlet automatically displays module Help topics in the language that is specified for the current user in the Regional and Language Options item in Control Panel. In Windows Vista and later versions of Windows, Get-Help searches for the Help topics in language-specific subdirectories of the module directory in accordance with the language fallback standards established for Windows.

Beginning in PowerShell 3.0, running a Get-Help command for a cmdlet or function triggers automatic importing of the module. The Get-Help cmdlet immediately displays the contents of the help topics in the module.

If the module does not contain help topics and there are no help topics for the commands in the module on the user’s computer, Get-Help displays auto-generated help. The auto-generated help includes the command syntax, parameters, and input and output types, but does not include any descriptions. The auto-generated help includes text that directs the user to try to use the Update-Help cmdlet to download help for the command from the internet or a file share. It also recommends using the Online parameter of the Get-Help cmdlet to get the online version of the help topic.

Supporting Updatable Help

Users of PowerShell 3.0 and later versions of PowerShell can download and install updated help files for a module from the internet or from a local file share. The Update-Help and Save-Help cmdlets hide the management details from the user. Users run the Update-Help cmdlet and then use the Get-Help cmdlet to read the newest help files for the module at the PowerShell command prompt. Users do not need to restart Windows or PowerShell.

Users behind firewalls and those without internet access can use Updatable Help, as well. Administrators with internet access use the Save-Help cmdlet to download and install the newest help files to a file share. Then, users use the Path parameter of the Update-Help cmdlet to get the newest help files from the file share.

Module authors can include help files in the module and use Updatable Help to update the help files, or omit help files from the module and use Updatable Help both to install and to update them.

For more information about Updatable Help, see Supporting Updatable Help.

Supporting Online Help

Users who cannot or do not install updated help files on their computers often rely on the online version of module help topics. The Online parameter of the Get-Help cmdlet opens the online version of a cmdlet or advanced function help topic for the user in their default internet browser.

The Get-Help cmdlet uses the value of the HelpUri property of the cmdlet or function to find the online version of the help topic.

Beginning in PowerShell 3.0, you can help users find the online version of cmdlet and function help topics by defining the HelpUri attribute on the cmdlet class or the HelpUri property of the CmdletBinding attribute. The value of the attribute is the value of the HelpUri property of the cmdlet or function.

Рекомендации по записи в файлы Best practices for writing to files

Важные API Important APIs

Иногда разработчики сталкиваются с рядом распространенных проблем, когда используют методы Write классов FileIO и PathIO для выполнения операций ввода-вывода с файловой системой. Developers sometimes run into a set of common problems when using the Write methods of the FileIO and PathIO classes to perform file system I/O operations. Например, распространены следующие проблемы. For example, common problems include:

  • Файл записан частично. A file is partially written.
  • Приложение получает исключение при вызове одного из методов. The app receives an exception when calling one of the methods.
  • После выполнения операций остаются TMP-файлы с именем, аналогичным имени конечного файла. The operations leave behind .TMP files with a file name similar to the target file name.
Читайте также:  Canoscan 8600f драйвер windows 10

К методам Write классов FileIO и PathIO относятся следующие: The Write methods of the FileIO and PathIO classes include the following:

  • WriteBufferAsyncWriteBufferAsync
  • WriteBytesAsyncWriteBytesAsync
  • WriteLinesAsyncWriteLinesAsync
  • WriteTextAsyncWriteTextAsync

В этой статье описывается, как работают эти методы, чтобы разработчикам было понятнее, когда и как их использовать. This article provides details about how these methods work so developers understand better when and how to use them. В статье представлены рекомендации. Она не является решением для всех возможных проблем с файловым вводом-выводом. This article provides guidelines and does not attempt to provide a solution for all possible file I/O problems.

В этой статье рассматриваются методы FileIO, для которых приводятся примеры. This article focuses on the FileIO methods in examples and discussions. Тем не менее, методы PathIO следуют аналогичной схеме, и большинство рекомендаций и инструкций в этой статье также применимы к ним. However, the PathIO methods follow a similar pattern and most of the guidance in this article applies to those methods too.

Удобство и управление Convenience vs. control

Объект StorageFile не является дескриптором файла, как в собственной модели программирования Win32. A StorageFile object is not a file handle like the native Win32 programming model. Вместо этого StorageFile является представлением файла с методами для управления его содержимым. Instead, a StorageFile is a representation of a file with methods to manipulate its contents.

Понимание этой концепции пригодится при выполнении операций ввода-вывода с StorageFile. Understanding this concept is useful when performing I/O with a StorageFile. Например, в разделе Запись в файл представлены три способа записи в файл: For example, the Writing to a file section presents three ways to write to a file:

  • с помощью метода FileIO.WriteTextAsync; Using the FileIO.WriteTextAsync method.
  • путем создания буфера и последующего вызова метода FileIO.WriteBufferAsync; By creating a buffer and then calling the FileIO.WriteBufferAsync method.
  • посредством модели из четырех шагов с помощью потока: The four-step model using a stream:
    1. открытие файла для получения потока; Open the file to get a stream.
    2. получение потока вывода; Get an output stream.
    3. создание объекта DataWriter и вызов соответствующего метода Write; Create a DataWriter object and call the corresponding Write method.
    4. фиксация данных в модуле записи данных и запись на диск выходного потока. Commit the data in the data writer and flush the output stream.

Первые два сценария чаще всего используются в приложениях. The first two scenarios are the ones most commonly used by apps. Запись в файл одной операцией проще программировать и поддерживать. Кроме того, это снимает с приложения ответственность за множество сложностей файлового ввода-вывода. Writing to the file in a single operation is easier to code and maintain, and it also removes the responsibility of the app from dealing with many of the complexities of file I/O. Тем не менее это удобство имеет свою цену: потеря контроля над всей операцией и возможности обнаруживать ошибки в определенных точках. However, this convenience comes at a cost: the loss of control over the entire operation and the ability to catch errors at specific points.

Транзакционная модель The transactional model

Методы Write классов FileIO и PathIO охватывают шаги третьей модели записи, описанной выше, с добавлением уровня. The Write methods of the FileIO and PathIO classes wrap the steps on the third write model described above, with an added layer. Этот уровень инкапсулирован в транзакции хранилища. This layer is encapsulated in a storage transaction.

Чтобы защитить целостность исходного файла в случае сбоя при записи данных, методы Write используют транзакционную модель, открывая файл с помощью метода OpenTransactedWriteAsync. To protect the integrity of the original file in case something goes wrong while writing the data, the Write methods use a transactional model by opening the file using OpenTransactedWriteAsync. В этом процессе создается объект StorageStreamTransaction. This process creates a StorageStreamTransaction object. После создания этого объекта транзакции интерфейсы API записывают данные, как это реализовано в примере доступа к файлам или в примере кода в статье StorageStreamTransaction. After this transaction object is created, the APIs write the data following a similar fashion to the File Access sample or the code example in the StorageStreamTransaction article.

На следующей схеме показаны базовые задачи, выполняемые методом WriteTextAsync в успешной операции записи. The following diagram illustrates the underlying tasks performed by the the WriteTextAsync method in a successful write operation. На этом рисунке показано упрощенное представление операции. This illustration provides a simplified view of the operation. Например, на нем пропущены такие действия, как кодирование и асинхронное завершение разных потоков. For example, it skips steps such as text encoding and async completion on different threads.

Преимущества использования методов Write классов FileIO и PathIO вместо более сложной модели из четырех шагов с использованием потока следующие: The advantages of using the Write methods of the FileIO and PathIO classes instead of the more complex four-step model using a stream are:

  • Один вызов API для обработки всех промежуточных шагов, включая ошибки. One API call to handle all the intermediate steps, including errors.
  • В случае сбоя исходный файл сохраняется. The original file is kept if something goes wrong.
  • Состояние системы сохраняется как можно более чистым. The system state will try to be kept as clean as possible.

Однако ввиду множества возможных промежуточных точек сбоя существует повышенная вероятность ошибки. However, with so many possible intermediate points of failure, there’s an increased chance of failure. При возникновении ошибки может быть сложно понять, где произошел сбой процесса. When an error occurs it may be difficult to understand where the process failed. В следующих разделах рассматриваются некоторые сбои, которые могут возникнуть при использовании методов Write, и предлагаются возможные решения. The following sections present some of the failures you might encounter when using the Write methods and provide possible solutions.

Распространенные коды ошибок при использовании методов Write классов FileIO и PathIO Common error codes for Write methods of the FileIO and PathIO classes

В этой таблице представлены распространенные коды ошибок, с которыми разработчики приложений могут столкнуться при использовании методов Write. This table presents common error codes that app developers encounter when using the Write methods. Шаги, описанные в таблице, соответствуют шагам на предыдущей схеме. The steps in the table correspond to steps in the previous diagram.

Читайте также:  Для чего linux x64
Имя ошибки (значение) Error name (value) Действия Steps Причины Causes Решения Solutions
ERROR_ACCESS_DENIED (0X80070005) ERROR_ACCESS_DENIED (0X80070005) 5 5 Возможно, исходный файл помечен для удаления предыдущей операцией. The original file might be marked for deletion, possibly from a previous operation. Попробуйте повторить операцию. Retry the operation. Обеспечьте синхронизацию доступа к файлу. Ensure access to the file is synchronized.
ERROR_SHARING_VIOLATION (0x80070020) ERROR_SHARING_VIOLATION (0x80070020) 5 5 Исходный файл открыт другим сеансом монопольной записи. The original file is opened by another exclusive write. Попробуйте повторить операцию. Retry the operation. Обеспечьте синхронизацию доступа к файлу. Ensure access to the file is synchronized.
ERROR_UNABLE_TO_REMOVE_REPLACED (0x80070497) ERROR_UNABLE_TO_REMOVE_REPLACED (0x80070497) 19–20 19-20 Исходный файл (file.txt) не может быть заменен, так как он используется. The original file (file.txt) could not be replaced because it is in use. Другой процесс или операция получила доступ к файлу, прежде чем его удалось заменить. Another process or operation gained access to the file before it could be replaced. Попробуйте повторить операцию. Retry the operation. Обеспечьте синхронизацию доступа к файлу. Ensure access to the file is synchronized.
ERROR_DISK_FULL (0x80070070) ERROR_DISK_FULL (0x80070070) 7, 14, 16, 20 7, 14, 16, 20 Транзакционная модель создает дополнительный файл, и это требует дополнительного места на диске. The transacted model creates an extra file, and this consumes extra storage.
ERROR_OUTOFMEMORY (0x8007000E) ERROR_OUTOFMEMORY (0x8007000E) 14, 16 14, 16 Это может произойти из-за нескольких незавершенных операций ввода-вывода или большого размера файлов. This can happen due to multiple outstanding I/O operations or large file sizes. Более детальный подход с контролем потока может устранить эту ошибку. A more granular approach by controlling the stream might resolve the error.
E_FAIL (0x80004005) E_FAIL (0x80004005) Любые Any Прочее Miscellaneous Попробуйте повторить операцию. Retry the operation. Если проблема не исчезла, возможно, это ошибка платформы, и приложение должно быть завершено, так как оно находится в несогласованном состоянии. If it still fails, it might be a platform error and the app should terminate because it’s in an inconsistent state.

Дополнительные рекомендации по состояниям файлов, которые могут привести к ошибкам Other considerations for file states that might lead to errors

Помимо ошибок, возвращаемых методами Write, ознакомьтесь с некоторыми рекомендациями по реагированию приложения на запись в файл. Apart from errors returned by the Write methods, here are some guidelines on what an app can expect when writing to a file.

Данные записываются в файл только в том случае, если операция завершена Data was written to the file if and only if operation completed

Приложение не должно делать какие-либо предположения о данных в файле, пока выполняется операция записи. Your app should not make any assumption about data in the file while a write operation is in progress. Попытка обращения к файлу до завершения операции может привести к несогласованности данных. Trying to access the file before an operation completes might lead to inconsistent data. Ваше приложение должно отвечать за отслеживание незавершенных операций ввода-вывода. Your app should be responsible of tracking outstanding I/Os.

Устройства чтения Readers

Если файл, в который выполняется запись, также используется «мягким» средством чтения (то есть открыт с помощью FileAccessMode.Read), то последующие операции чтения будут завершаться ошибкой ERROR_OPLOCK_HANDLE_CLOSED (0x80070323). If the file that being written to is also being used by a polite reader (that is, opened with FileAccessMode.Read, subsequent reads will fail with an error ERROR_OPLOCK_HANDLE_CLOSED (0x80070323). Иногда приложения пытаются повторно открыть файл для чтения, пока выполняется операция Write. Sometimes apps retry opening the file for read again while the Write operation is ongoing. Это может привести к состязанию за доступ, и операция Write в итоге завершится сбоем, пытаясь перезаписать исходный файл, так как он не сможет быть заменен. This might result in a race condition on which the Write ultimately fails when trying to overwrite the original file because it cannot be replaced.

Файлы из KnownFolders Files from KnownFolders

Ваше приложение может быть не единственным приложением, которое пытается получить доступ к файлу, расположенному в любой из папок KnownFolders. Your app might not be the only app that is trying to access a file that resides on any of the KnownFolders. Нет никакой гарантии, что после успешного выполнения операции содержимое, которое приложение записало в файл, останется без изменений при следующей попытке считать этот файл. There’s no guarantee that if the operation is successful, the contents an app wrote to the file will remain constant the next time it tries to read the file. Кроме того, в этом сценарии распространены ошибки совместного использования и отказа в доступе. Also, sharing or access denied errors become more common under this scenario.

Конфликты при операциях ввода-вывода Conflicting I/O

Вероятность ошибок параллельной обработки можно снизить, если ваше приложение использует методы Write для файлов в своих локальных данных, но по-прежнему следует проявлять осторожность. The chances of concurrency errors can be lowered if our app uses the Write methods for files in its local data, but some caution is still required. Если одновременно отправляется несколько операций Write с файлом, нет никакой гарантии того, какие данные в итоге окажутся в этом файле. If multiple Write operations are being sent concurrently to the file, there’s no guarantee about what data ends up in the file. Чтобы избежать этого, мы рекомендуем, чтобы ваше приложение сериализовало операции Write с файлом. To mitigate this, we recommend that your app serializes Write operations to the file.

Иногда, если операция принудительно отменяется (например, когда приложение приостановлено или завершено операционной системой), транзакция не фиксируется или не закрывается соответствующим образом. Occasionally, if the operation is forcefully cancelled (for example, if the app was suspended or terminated by the OS), the transaction is not committed or closed appropriately. После этого могут остаться файлы с расширением

TMP. This can leave behind files with a (.

TMP) extension. Рассмотрите возможность удаления этих временных файлов (если они существуют в локальных данных приложения) при обработке активации приложения. Consider deleting these temporary files (if they exist in the app’s local data) when handling the app activation.

Рекомендации по типам файлов Considerations based on file types

Некоторые ошибки могут преобладать в зависимости от типа файлов, частоты обращения к ним и их размера. Some errors can become more prevalent depending on the type of files, the frequency on which they’re accessed, and their file size. Как правило, приложению доступны три категории файлов: Generally, there are three categories of files your app can access:

  • Файлы, созданные и измененные пользователем в папке локальных данных вашего приложения. Files created and edited by the user in your app’s local data folder. Они создаются и изменяются только при использовании вашего приложения и существуют только в нем. These are created and edited only while using your app, and they exist only within the app.
  • Метаданные приложения. App metadata. Ваше приложение использует эти файлы для отслеживания собственного состояния. Your app uses these files to keep track of its own state.
  • Другие файлы в расположениях файловой системы, для которых ваше приложение объявило возможность доступа. Other files in locations of the file system where your app has declared capabilities to access. Чаще всего они находятся в одной из папок KnownFolders. These are most commonly located in one of the KnownFolders.

Ваше приложение имеет полный контроль над первыми двумя категориями файлов, так как они являются частью файлов пакета приложения и используются исключительно вашим приложением. Your app has full control on the first two categories of files, because they’re part of your app’s package files and are accessed by your app exclusively. Что касается файлов из последней категории, ваше приложение должно читывать, что к ним могут одновременно обращаться другие приложения и службы ОС. For files in the last category, your app must be aware that other apps and OS services may be accessing the files concurrently.

В зависимости от приложения, частота обращения к файлам может быть разной: Depending on the app, access to the files can vary on frequency:

  • Очень низкая. Very low. Обычно это файлы, открываемые сразу после запуска приложения и сохраняемые при приостановке работы приложения. These are usually files that are opened once when the app launches and are saved when the app is suspended.
  • Низкая. Low. Это файлы, с которыми пользователь специально выполняет действия (такие как сохранение или загрузка). These are files that the user is specifically taking an action on (such as save or load).
  • Средняя или высокая. Medium or high. Это файлы, в которых приложению требуется постоянно обновлять данные (например, для автосохранения или постоянного отслеживания метаданных). These are files in which the app must constantly update data (for example, autosave features or constant metadata tracking).

Данные по размеру файлов и производительности можно изучить на следующей диаграмме для метода WriteBytesAsync. For file size, consider the performance data in the following chart for the WriteBytesAsync method. На этой диаграмме сравниваются длительность операции и размер файла. На ней отображается средняя производительность 10 000 операций для размера файла в управляемой среде. This chart compares the time to complete an operation vs file size, over an average performance of 10000 operations per file size in a controlled environment.

На этой диаграмме намеренно пропущены значения времени на оси y, так как разное оборудование и конфигурации дадут разные абсолютные значения времени. The time values on the y-axis are omitted intentionally from this chart because different hardware and configurations will yield different absolute time values. Тем не менее мы наблюдали следующие устойчивые тенденции в тестах. However, we have consistently observed these trends in our tests:

  • Небольшие файлы (не более 1 МБ): время выполнения операций устойчиво небольшое. For very small files (
  • Более крупные файлы (более 1 МБ): время выполнения операций начинает увеличиваться экспоненциально. For larger files (> 1 MB): The time to complete the operations starts to increase exponentially.

Операции ввода-вывода во время приостановки приложения I/O during app suspension

Приложение должно обрабатывать приостановку, если вы хотите сохранить сведения о состоянии или метаданные для использования в последующих сеансах. Your app must designed to handle suspension if you want to keep state information or metadata for use in later sessions. Общие сведения о приостановке приложений доступны в разделе Жизненный цикл приложения и в этой записи блога. For background information about app suspension, see App lifecycle and this blog post.

Если только операционная система не предоставляет приложению режим расширенного выполнения, при приостановке у приложения есть 5 секунд на то, чтобы освободить все свои ресурсы и сохранить данные. Unless the OS grants extended execution to your app, when your app is suspended it has 5 seconds to release all its resources and save its data. Чтобы обеспечить наилучшую надежность и взаимодействие, всегда учитывайте, что время, выделяемое на обработку задач приостановки, ограничено. For the best reliability and user experience, always assume the time you have to handle suspension tasks is limited. Используйте приведенные ниже рекомендации во время 5-секундного интервала времени, выделяемого для обработки задач приостановки. Keep in mind the following guidelines during the 5 second time period for handling suspension tasks:

  • Пытайтесь свести к минимуму операции ввода-вывода, чтобы избежать состязания за доступ из-за операций записи на диск и освобождения. Try to keep I/O to a minimum to avoid race conditions caused by flushing and release operations.
  • Избегайте операций записи в файлы, требующих сотен миллисекунд или больше для выполнения. Avoid writing files that require hundreds of milliseconds or more to write.
  • Если приложение использует методы Write, учитывайте все промежуточные шаги, обязательные для этих методов. If your app uses the Write methods, keep in mind all the intermediate steps that these methods require.

Если приложение работает с небольшим объемом данных о состоянии во время приостановки, в большинстве случаев можно использовать методы Write для записи данных на диск. If your app operates on a small amount of state data during suspension, in most cases you can use the Write methods to flush the data. Тем не менее, если приложение использует большой объем данных о состоянии, рассмотрите возможность использования потоков для непосредственного сохранения данных. However, if your app uses a large amount of state data, consider using streams to directly store your data. Это может снизить задержки, связанные с транзакционной моделью методов Write. This can help reduce the delay introduced by the transactional model of the Write methods.

Вы можете ознакомиться с примером BasicSuspension. For an example, see the BasicSuspension sample.

Другие примеры и ресурсы Other examples and resources

Ниже приведено несколько примеров и другие ресурсы для конкретных сценариев. Here are several examples and other resources for specific scenarios.

Пример кода для повтора файлового ввода-вывода Code example for retrying file I/O example

Ниже приведен пример псевдокода для повтора записи (C#) при условии, что запись требуется выполнить после того, как пользователь выберет файл для сохранения. The following is a pseudo-code example on how to retry a write (C#), assuming the write is to be done after the user picks a file for saving:

Синхронизация доступа к файлу Synchronize access to the file

Блог по параллельному программированию для .NET является превосходным источником рекомендаций по параллельному программированию. The Parallel Programming with .NET blog is a great resource for guidance about parallel programming. В частности, в записи блога о AsyncReaderWriterLock описывается, как обеспечить монопольный доступ к файлу для записи, предоставляя параллельный доступ для чтения. In particular, the post about AsyncReaderWriterLock describes how to maintain exclusive access to a file for writes while allowing concurrent read access. Следует помнить, что сериализация операций ввода-вывода будет влиять на производительность. Keep in mind that serializing I/O will impact performance.

Читайте также:  Диагностика аппаратного raid linux
Оцените статью