Powershell windows form label

Create and publish retention labels by using PowerShell

After you’ve decided to use retention labels to help you keep or delete documents and emails in Microsoft 365, you might have realized that you have many and possibly hundreds of retention labels to create and publish. The recommended method to create retention labels at scale is by using file plan from the Microsoft 365 compliance center. However, you can also use PowerShell.

Use the information, template files and examples, and script in this article to help you bulk-create retention labels and publish them in retention label policies. Then, the retention labels can be applied by administrators and users.

The supplied instructions don’t support retention labels that are auto-applied.

In Excel, create a list of your retention labels and a list of their retention label policies.

Use PowerShell to create the retention labels and retention label policies in those lists.

Disclaimer

The sample scripts provided in this article aren’t supported under any Microsoft standard support program or service. The sample scripts are provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages.

Step 1: Create a .csv file for the retention labels

Copy the following sample .csv file for a template and example entries for four different retention labels, and paste them into Excel.

Convert the text to columns: Data tab > Text to Columns > Delimited > Comma > General

Replace the examples with entries for your own retention labels and settings. For more information about the parameter values, see New-ComplianceTag.

Save the worksheet as a .csv file in a location that’s easy to find for a later step. For example: C:>Scripts\Labels.csv

If the .csv file contains a retention label with the same name as one that already exists, the script skips creating that retention label. No duplicate retention labels are created.

Don’t change or rename the column headers from the sample .csv file provided, or the script will fail.

Sample .csv file for retention labels

Step 2: Create a .csv file for the retention label policies

Copy the following sample .csv file for a template and example entries for three different retention label policies, and paste them into Excel.

Читайте также:  Чем удалить неудаляемые файлы windows

Convert the text to columns: Data tab > Text to Columns > Delimited > Comma > General

Replace the examples with entries for your own retention label policies and their settings. For more information about the parameter values for this cmdlet, see New-RetentionCompliancePolicy.

Save the worksheet as a .csv file in a location that’s easy to find for a later step. For example:

If the .csv file contains a retention label policy with the same name as one that already exists, the script skips creating that retention label policy. No duplicate retention label policies are created.

Don’t change or rename the column headers from the sample .csv file provided, or the script will fail.

Sample .csv file for retention policies

Step 3: Create the PowerShell script

Copy and paste the following PowerShell script into Notepad.

Save the file by using a file name extension of .ps1 in a location that’s easy to find. For example:

The script prompts you to provide the two source files that you created in the previous two steps:

  • If you don’t specify the source file to create the retention labels, the script moves on to create the retention label policies.
  • If you don’t specify the source file to create the retention label policies, the script creates the retention labels only.

The script generates a log file that records each action it took and whether the action succeeded or failed. See the final step for instructions how to locate this log file.

PowerShell script

Step 4: Run the PowerShell script

Then, run the script that creates and publishes the retention labels:

In your Security & Compliance Center PowerShell session, enter the path, followed by the characters .\ and the file name of the script, and then press ENTER to run the script. For example:

The script prompts you for the locations of the .csv files that you created in the previous steps. Enter the path, followed by the characters .\ and file name of the .csv file, and then press ENTER. For example, for the first prompt:

Step 5: View the log file with the results

Use the log file that the script created to check the results and identify any failures that need resolving.

You can find the log file at the following location, although the digits in the example file name vary.

Элемент управления Label (Windows Forms) Label Control (Windows Forms)

ToolStripLabelЭлемент управления заменяет и расширяет функциональные возможности Label элемента управления. The ToolStripLabel control replaces and adds functionality to the Label control. Можно использовать ToolStripLabel с другими новыми элементами управления, такими как ToolStripDropDown . You can use the ToolStripLabel with other new controls such as the ToolStripDropDown. Однако этот Label элемент управления сохраняется как для обратной совместимости, так и для использования в будущем, если вы решили. However, the Label control is retained for both backward compatibility and future use, if you choose.

LabelЭлементы управления Windows Forms используются для вывода текста или изображений, которые не могут быть изменены пользователем. Windows Forms Label controls are used to display text or images that cannot be edited by the user. Они используются для обнаружения объектов в форме — для предоставления описания того, что может делать определенный элемент управления, например, или для вывода сведений в ответ на событие или процесс во время выполнения в приложении. They are used to identify objects on a form—to provide a description of what a certain control will do if clicked, for example, or to display information in response to a run-time event or process in your application. Поскольку Label элемент управления не может получать фокус, он также может использоваться для создания ключей доступа для других элементов управления. Because the Label control cannot receive focus, it can also be used to create access keys for other controls.

Читайте также:  Как правильно выставить виртуальную память windows 10

в этом разделе In This Section

Общие сведения об элементе управления Label Label Control Overview
Описание элемента управления, его основных возможностей и свойств. Explains what this control is and its key features and properties.

Практическое руководство. Определение клавиш доступа с помощью элементов управления Label в Windows Forms How to: Create Access Keys with Windows Forms Label Controls
Описывает использование метки для определения ключа доступа для другого элемента управления. Describes how to use a label to define an access key for another control.

Справочник Reference

Label
Описание класса и всех его членов. Describes this class and has links to all its members.

Элементы управления для использования в формах Windows Forms Controls to Use on Windows Forms
Полный список элементов управления Windows Forms со ссылками на информацию об их применении. Provides a complete list of Windows Forms controls, with links to information on their use.

Клёвый код

Скриптописание и кодинг

Решаем задачи Абрамян на C. Matrix78

Matrix78. Дана матрица размера $$M \times N$$. Упорядочить ее строки так, чтобы их минимальные элементы образовывали убывающую последовательность.

Решаем задачи Абрамян на C. Matrix77

Matrix77. Дана матрица размера $$M \times N$$. Упорядочить ее столбцы так, чтобы их последние элементы образовывали убывающую последовательность.

Решаем задачи Абрамян на C. Matrix76

Matrix76. Дана матрица размера $$M \times N$$. Упорядочить ее строки так, чтобы их первые элементы образовывали возрастающую последовательность.

Решаем задачи Абрамян на C. Matrix75

Matrix75. Дана матрица размера $$M \times N$$. Элемент матрицы называется ее локальным максимумом, если он больше всех окружающих его элементов. Поменять знак всех локальных максимумов данной матрицы на противоположный. При решении допускается использовать вспомогательную матрицу.

Решаем задачи Абрамян на C. Matrix74

Matrix74. Дана матрица размера $$M \times N$$. Элемент матрицы называется ее локальным минимумом, если он меньше всех окружающих его элементов. Заменить все локальные минимумы данной матрицы на нули. При решении допускается использовать вспомогательную матрицу.

Решаем задачи Абрамян на C. Matrix73

Matrix73. Дана матрица размера $$M \times N$$. После последнего столбца, содержащего только отрицательные элементы, вставить столбец из нулей. Если требуемых столбцов нет, то вывести матрицу без изменений.

Решаем задачи Абрамян на C. Matrix72

Matrix72. Дана матрица размера $$M \times N$$. Перед первым столбцом, содержащим только положительные элементы, вставить столбец из единиц. Если требуемых столбцов нет, то вывести матрицу без изменений.

Решаем задачи Абрамян на C. Matrix71

Matrix71. Дана матрица размера $$M \times N$$. Продублировать столбец матрицы, содержащий ее минимальный элемент.

Решаем задачи Абрамян на C. Matrix70

Matrix70. Дана матрица размера $$M \times N$$. Продублировать строку матрицы, содержащую ее максимальный элемент.

Решаем задачи Абрамян на C. Matrix69

Matrix69. Дана матрица размера $$M \times N$$ и целое число $$K$$ $$(1 \le K \le $$N$$)$$. После столбца матрицы с номером $$K$$ вставить столбец из единиц.

Создание настраиваемого поля ввода Creating a Custom Input Box

Создание сценария настраиваемого графического поля ввода с помощью функций создания форм Microsoft .NET Framework в Windows PowerShell 3.0 и более поздних версиях. Script a graphical custom input box by using Microsoft .NET Framework form-building features in Windows PowerShell 3.0 and later releases.

Создание настраиваемого графического поля ввода Create a custom, graphical input box

Скопируйте и вставьте следующий код в интегрированную среду сценариев Windows PowerShell, а затем сохраните файл как сценарий Windows PowerShell (PS1-файл). Copy and then paste the following into Windows PowerShell ISE, and then save it as a Windows PowerShell script (.ps1).

Сценарий начинается с загрузки двух классов .NET Framework: System.Drawing и System.Windows.Forms. The script begins by loading two .NET Framework classes: System.Drawing and System.Windows.Forms. Затем вы запускаете новый экземпляр класса .NET Framework System.Windows.Forms.Form, предоставляющий пустую форму или окно, в которые можно добавить элементы управления. You then start a new instance of the .NET Framework class System.Windows.Forms.Form; that provides a blank form or window to which you can start adding controls.

Читайте также:  Reset password windows ubuntu

После создания экземпляра класса «Форма» назначьте значения для трех свойств этого класса. After you create an instance of the Form class, assign values to three properties of this class.

Text. Text. Это будет заголовком окна. This becomes the title of the window.

Size. Size. Это размер формы в пикселях. This is the size of the form, in pixels. Предыдущий сценарий создает форму шириной 300 пикселей и высотой 200 пикселей. The preceding script creates a form that’s 300 pixels wide by 200 pixels tall.

StartingPosition. StartingPosition. Для этого дополнительного свойства задается значение CenterScreen в предыдущем сценарии. This optional property is set to CenterScreen in the preceding script. Если это свойство не добавлено, Windows выберет расположение после открытия формы. If you don’t add this property, Windows selects a location when the form is opened. Если для StartingPosition задать значение CenterScreen, форма будет автоматически отображаться в центре экрана при загрузке. By setting the StartingPosition to CenterScreen, you’re automatically displaying the form in the middle of the screen each time it loads.

Далее создайте кнопку для формы. Next, create an OK button for your form. Укажите размер и поведение кнопки ОК. Specify the size and behavior of the OK button. В этом примере кнопка расположена на 120 пикселей ниже верхней границы формы и на 75 пикселей правее левой границы. In this example, the button position is 120 pixels from the form’s top edge, and 75 pixels from the left edge. Высота кнопки — 23 пикселя, а длина — 75 пикселей. The button height is 23 pixels, while the button length is 75 pixels. Сценарий использует предопределенные типы Windows Forms для определения поведения кнопок. The script uses predefined Windows Forms types to determine the button behaviors.

Аналогичным образом создайте кнопку Отмена. Similarly, you create a Cancel button. Кнопка Отмена расположена на 120 пикселей ниже верхней границы и на 150 пикселей правее левой границы окна. The Cancel button is 120 pixels from the top, but 150 pixels from the left edge of the window.

Далее введите текст метки в окне, который должны получить пользователи. Next, provide label text on your window that describes the information you want users to provide.

Добавьте элемент управления (в данном случае текстовое поле), который позволит пользователям указать сведения, описанные в тексте метки. Add the control (in this case, a text box) that lets users provide the information you’ve described in your label text. Помимо текстового поля существует много других элементов управления, которые можно применить. Их описание см. в статье Пространство имен System.Windows.Forms. There are many other controls you can apply besides text boxes; for more controls, see System.Windows.Forms Namespace.

Задайте для свойства Topmost значение $true, чтобы принудительно открыть окно поверх других диалоговых окон. Set the Topmost property to $true to force the window to open atop other open windows and dialog boxes.

Затем добавьте следующую строку кода, чтобы активировать форму и установить фокус на текстовое поле, которое вы создали. Next, add this line of code to activate the form, and set the focus to the text box that you created.

Добавьте следующую строку кода для отображения формы в Windows. Add the following line of code to display the form in Windows.

Наконец, код внутри блока If указывает Windows, что следует делать с формой после того, как пользователь выберет параметр из списка и нажмет кнопку ОК или клавишу ВВОД. Finally, the code inside the If block instructs Windows what to do with the form after users provide text in the text box, and then click the OK button or press the Enter key.

Оцените статью