- GUI и PSRemoting в PowerShell CLI
- 2 ответа
- Out-GridView
- Синтаксис
- Описание
- Параметры
- -InputObject
- Использование командлета Out-Gridview для выбора в табличных данных в скриптах PowerShell
- Out-Grid View
- Syntax
- Description
- Examples
- Example 1: Output processes to a grid view
- Example 2: Use a variable to output processes to a grid view
- Example 3: Display a selected properties in a grid view
- Example 4: Save output to a variable, and then output a grid view
- Example 5: Output processes for a specified computer to a grid view
- Example 6: Output data from remote computers to a grid view
- Example 7: Pass multiple items through `Out-GridView`
- Example 8: Create a Windows shortcut to `Out-GridView`
- Parameters
- Inputs
- Outputs
- Notes
GUI и PSRemoting в PowerShell CLI
Недавно я создал скрипт, который использует GUI, такие как Out-GridView и Winforms, и поместил этот модуль на удаленный сервер Windows 2012. Это должно было позволить пользователям устанавливать удаленные сеансы PSSession и выполнять сценарии из централизованного расположения.
Например:
1. при попытке вызвать winform я получаю следующую ошибку:
2 . При попытке поместить результаты в Out-GridView я получаю следующую ошибку:
Существуют ли обходные пути, которые позволили бы мне использовать OGV и Winforms?
Примечание: Я открыт, чтобы позволить пользователю экспортировать модуль на свою физическую рабочую станцию, чтобы позволить им использовать эти опции, если это необходимо — OGV и Winforms, — только если есть эффективные / безопасные средства для этого. С другой стороны, я открыт на разные предложения.
2 ответа
Вам нужно использовать пользовательский интерфейс на локальном компьютере, а не на удаленном. Получать данные удаленно, отображать локально.
Invoke-Command -ComputerName RemoteServer -Scriptblock < Get-Process >| Out-Gridview
Использование gridview внутри блока скриптов попытается запустить пользовательский интерфейс на RemoteServer и выдаст ошибку, о которой вы упоминали.
Invoke-Command Я думаю, здесь было бы лучше, потому что вы говорите удаленному компьютеру, что делать, вместо того, чтобы просить напрямую взаимодействовать с удаленным компьютером, используя Enter-PSSession или New-PSSession .
Источник
Out-GridView
Отправляет результаты в интерактивную таблицу в отдельном окне.
Синтаксис
Описание
Командлет Out-GridView пересылает результаты выполнения команды в окно таблицы, в котором они отображаются в виде интерактивной таблицы. Для использования этого компонента требуется Microsoft .NET Framework 3.5 с пакетом обновления 1 (SP1).
Для работы с данными можно использовать следующие функции таблицы.
— Скрытие, показ и изменение порядка столбцов. Чтобы скрыть, показать или изменить порядок столбцов, щелкните заголовок столбца правой кнопкой мыши и выберите команду «Выбор столбцов».
— Сортировка. Чтобы отсортировать данные, щелкните заголовок столбца. Щелкните еще раз, чтобы перейти от сортировки по возрастанию к сортировке по убыванию.
— Быстрый фильтр. Поле «Фильтр» в верхней части окна позволяет выполнять поиск по тексту таблицы. Можно искать текст в конкретном столбце, искать по символам или по нескольким словам.
— Фильтрация по критериям. Для создания правил фильтрации данных используйте раскрывающееся меню добавления критериев. Эта функция бывает очень полезной при работе с крупными наборами данных, например с журналами событий.
— Копирование и вставка. Чтобы скопировать строки с данными из таблицы Out-GridView, используйте сочетание клавиш CTRL+C (копирование). Затем эти данные можно вставить в программу для работы с текстом или электронными таблицами.
Чтобы получить инструкции по использованию этих функций, введите команду «Get-Help out-gridview -full» и ознакомьтесь с подразделом «Использование функций окна таблицы» в разделе ПРИМЕЧАНИЯ.
Параметры
-InputObject
Принимает входные значения для командлета Out-GridView.
При использовании параметра InputObject для отправки коллекции из более чем одного объекта в командлет Out-GridView командлет Out-GridView обрабатывает коллекцию как один объект коллекции и отображает одну строку, представляющую эту коллекцию. Чтобы отобразить каждый из объектов в коллекции, необходимо передавать объекты командлету Out-GridView с помощью оператора конвейера (|).
Источник
Использование командлета Out-Gridview для выбора в табличных данных в скриптах PowerShell
Командлет Out-GridView позволяет вывести данные в виде интерактивной графической таблицы с возможностью фильтрации и сортировки по различным признакам. Вы можете использовать командлет Out-Gridview в скриптах, где нужно предоставить простейший GUI интерфейс для выбора объектов пользователю.
Рассмотрим простейший пример использования командлета для вывода списка служб Windows и некоторых их свойств:
Get-Service | Select DisplayName,Status,ServiceName,Can* | Out-GridView
Как вы видите перед вами открылась графическая форма с таблицей, представляющей список свойств служб Windows. Командлет автоматически именует столбцы на основе свойства объекта и типа данных, расширяет свойства PSObject, если определение формата недоступно.
Прямо из этой формы вы можете выполнять поиск либо с помощью поля для ввода Filter:
Либо с помощью кнопки Add criteria. На следующем скриншоте я создал простейший фильтр со списком запущенных служб, в имени которых есть символы VMW. Фильтр создается прямо по значениям свойств объектов.
Или, например, выведем список ТОП 10 процессов, которые сильнее всего используют CPU (с помощью параметра –Title я изменил заголовок окна Out-GridView):
Get-Process | Sort-Object CPU -Descending | Select -First 10 | Out-GridView -Title «Top 10 CPU processes»
Можно быстро отсортировать содержимое таблицы по убыванию/возрастанию, щелкнув по названию столбца.
Однако наиболее мощной возможностью Out-Gridview, которая предоставляет новый уровень удобного графического интерфейса для ваших PowerShell скриптов, является параметр –PassThru.
Данный параметр доступен начиная с версии PowerShell 3.0 и позволяет пользователю выбрать в таблице одну или несколько объектов и передать их по конвейеру через стандартный пайп на вход следующим командлетам в скрипте PowerShell.
Например, следующий PowerShell скрипт выведет в таблицу список запущенных служб Windows. Пользователь должен выбрать в таблице нужную службу и нажать Ok.
Get-Service | Where-Object <$_.status -eq 'running'>| Out-GridView -Title «Select service to restart» –PassThru -OutputMode Multiple | Restart-service –verbose
Скрипт перезапустит только выбранную пользователем службу.
Вы можете сохранить объекты, выбранный пользователем в переменную:
$Svcs = Get-Service | Where-Object <$_.status -eq 'running'>| Out-GridView -Title «Select services» –PassThru
Или можно сохранить только значения определенного свойства. Для этого добавьте к предыдущей команде:
| Select -ExpandProperty Name
Вы можете разрешить пользователю выбирать только один элемент в таблице или сразу несколько с помощью параметров:
-OutputMode Single и -OutputMode Multiple
Еще несколько интересных сценариев использования командлета Out-GridView.
Вывести список предыдущих команд из истории PowerShell и повторно выполнить выбранные команды:
Get-History | Out-GridView -PassThru | Invoke-Expression
Вывести список дополнительных компонентов Windows и установить выделенные компоненты (например инструменты управления Active Directory из RSAT и SSH клиент):
Get-WindowsCapability -Online | Where-Object <$_.State –eq “NotPresent”>| Out-GridView -PassThru |Add-WindowsCapability –Online
Получить список RDP сессии с Connection Broker в RDS ферме и подключиться к выбранному пользователю с помощью теневого подключения:
import-module remotedesktop
$cbserver = «srv-rdsbroker1.winitpro.ru»
$id = get-rdusersession -ConnectionBroker $cbserver | Out-GridView -title «RD Connection» -PassThru | select hostserver, unifiedsessionid
$id2 = $id | select -ExpandProperty unifiedsessionid
$srv = $id | select -ExpandProperty hostserver
mstsc /v:»$srv» /shadow:»$id2″ /control /noconsentprompt
С помощью командлета Get-ADUser из модуля AD PowerShell можно вывести список включенных пользователей в определенном OU и сбросить пароль в домене.
Import-Module ActiveDirectory
$NewPasswd=Read-Host «Введите новый пароль пользователя» –AsSecureString
Get-ADUser -filter
Через Invoke-Command можно получить данные с удаленных компьютеров и представить их в таблице:
Invoke-Command -ComputerName msk-dc01, msk-dc02, msk-dc03 -ScriptBlock
Но вы можете использовать для обращения к Server Core параметр –ComputerName, который есть у большинства командлетов. Например:
Get-Service -ComputerName msk-dc02 | Where-Object <$_.status -eq 'running'>| Out-GridView –Title «Select service to restart» -OutputMode Single|Restart-Service -Verbose
Microsoft по какой-то причине убрала командлет Out-GridView из PowerShell Core 6.x, но в 7.0 версии его вернули. Если у вас используется версиях PowerShell 6.x, обновите ее до последние командой:
Как вы видите, Out-GridView позволяет добавить удобный графический интерфейс вашим скриптам PowerShell
Источник
Out-Grid View
Sends output to an interactive table in a separate window.
Syntax
Description
The Out-GridView cmdlet sends the output from a command to a grid view window where the output is displayed in an interactive table.
Because this cmdlet requires a user interface, it does not work on Windows Server Core or Windows Nano Server.
You can use the following features of the table to examine your data:
- Hide, Show, and Reorder Columns
- Sort rows
- Quick Filter
- Add Criteria Filter
- Copy and paste
For full instructions, see the Notes section of this article.
Examples
Example 1: Output processes to a grid view
This example gets the processes running on the local computer and sends them to a grid view window.
Example 2: Use a variable to output processes to a grid view
This example also gets the processes running on the local computer and sends them to a grid view window.
The output of the Get-Process cmdlet is saved in the $P variable. Then, $P is piped to Out-GridView .
Example 3: Display a selected properties in a grid view
This example displays selected properties of the running processes in a grid view.
The output of Get-Process is piped to Select-Object to select the Name, WorkingSet, and PeakWorkingSet properties. Another pipeline operator sends the filtered objects to the Sort-Object cmdlet to sort them in descending order by the value of the WorkingSet property. Then, the sorted results are piped to Out-GridView . You can now use the features of the grid view to search, sort, and filter the data.
Example 4: Save output to a variable, and then output a grid view
This example saves cmdlet output in a variable then sends it to Out-GridView .
Get-ChildItem gets all the files in the PowerShell installation directory and its subdirectories using the the $PSHOME automatic variable. The parentheses in the command establish the order of operations. As a result, the output from the Get-ChildItem command is saved in the $A variable before it is sent to Out-GridView .
Example 5: Output processes for a specified computer to a grid view
This example displays the processes that are running on the Server01 computer in a grid view window.
The examle uses ogv , which is the alias for the Out-GridView cmdlet. The Title parameter specifies the window title.
Example 6: Output data from remote computers to a grid view
This example shows how to send data collected from remote computers to Out-GridView .
Invoke-Command runs Get-Culture on three remote computers. The resulting data is piped to Out-GridView . Notice that the script block that runs on the remote computer does not include the Out-GridView command. If it did, the command would fail when it tried to open a grid view window on each of the remote computers.
Example 7: Pass multiple items through `Out-GridView`
This example lets you select multiple processes from the Out-GridView window. The processes that you select are passed to the Export-Csv command and written to the ProcessLog.csv file.
The PassThru parameter of Out-GridView lets you send multiple items down the pipeline. The PassThru parameter is equivalent to using the Multiple value of the OutputMode parameter.
Example 8: Create a Windows shortcut to `Out-GridView`
This example shows how to use the Wait parameter of Out-GridView to create a Windows shortcut to the Out-GridView window.
This command line can be used in a Windows shortcut. Without the Wait parameter, PowerShell would exit as soon as the Out-GridView window opened, which would close the Out-GridView window almost immediately.
Parameters
Specifies object that the cmdlet accepts as input for Out-GridView .
When you use the InputObject parameter to send a collection of objects to Out-GridView , Out-GridView treats the collection as one collection object, and it displays one row that represents the collection. To display the each object in the collection, use a pipeline operator (|) to send objects to Out-GridView .
| Type: | PSObject |
| Position: | Named |
| Default value: | None |
| Accept pipeline input: | True |
| Accept wildcard characters: | False |
Specifies the items that the interactive window sends down the pipeline as input to other commands. By default, this cmdlet does not generate any output. To send items from the interactive window down the pipeline, click to select the items and then click OK.
The values of this parameter determine how many items you can send down the pipeline.
- None. No items. This is the default value.
- Single. Zero items or one item. Use this value when the next command can take only one input object.
- Multiple. Zero, one, or many items. Use this value when the next command can take multiple input objects. This value is equivalent to the Passthru parameter.
This parameter was introduced in Windows PowerShell 3.0.
| Type: | OutputModeOption |
| Accepted values: | None, Single, Multiple |
| Position: | Named |
| Default value: | None |
| Accept pipeline input: | False |
| Accept wildcard characters: | False |
Indicates that the cmdlet sends items from the interactive window down the pipeline as input to other commands. By default, this cmdlet does not generate any output. This parameter is equivalent to using the Multiple value of the OutputMode parameter.
To send items from the interactive window down the pipeline, click to select the items and then click OK. Shift-click and Ctrl-click are supported.
| Type: | SwitchParameter |
| Position: | Named |
| Default value: | False |
| Accept pipeline input: | False |
| Accept wildcard characters: | False |
Specifies the text that appears in the title bar of the Out-GridView window. By default, the title bar displays the command that invokes Out-GridView .
| Type: | String |
| Position: | Named |
| Default value: | None |
| Accept pipeline input: | False |
| Accept wildcard characters: | False |
Indicates that the cmdlet suppresses the command prompt and prevents Windows PowerShell from closing until the Out-GridView window is closed. By default, the command prompt returns when the Out-GridView window opens.
This feature lets you use the Out-GridView cmdlets in Windows shortcuts. When Out-GridView is used in a shortcut without the Wait parameter, the Out-GridView window appears only momentarily before PowerShell closes.
| Type: | SwitchParameter |
| Position: | Named |
| Default value: | False |
| Accept pipeline input: | False |
| Accept wildcard characters: | False |
Inputs
You can send any object to this cmdlet.
Outputs
None
Normally, Out-GridView does not return any objects. When using the PassThru parameter, the objects representing the selected rows are returned to the pipeline.
Notes
You cannot use a remote command to open a grid view window on another computer.
The command output that you send to Out-GridView cannot be formatted using the Format cmdlets, such as Format-Table or Format-Wide cmdlets. To select properties, use the Select-Object cmdlet.
Deserialized output from remote commands might not be formatted correctly in the grid view window.
Keyboard Shortcuts for Out-GridView
| Use this key: | To perform this action: |
|---|---|
| Tab | Moves the cursor from the Filter box to the Add criteria menu to the table and back. |
| UpArrow | Move up one row. Moves to column headers from first row of data. |
| DownArrow | Move down one row. |
| LeftArrow | In column header row, move left one column. |
| RightArrow | In column header row, move right one column. |
| ContextMenuKey | In column header row, displays the Select Columns option. |
| Enter or Spacebar | In column header row, sort column data (toggle A-Z, Z-A). |
How to Use the Grid View Window Features
To hide or show a column:
- Right-click any column header and click Select Columns.
- In the Select Columns dialog box, use the arrow keys to move the columns between the Selected columns to the Available columns boxes. Only columns in the Select Columns box appear in the grid view window.
To reorder columns:
You can drag and drop columns into the desired location. Or use the following steps:
- Right-click any column header and click Select Columns.
- In the Select Columns dialog box, use the Move up and Move down buttons to reorder the columns. Columns at the top of the list appear to the left of columns at the bottom of the list in the grid view window.
How to Sort Table Data
- To sort the data, click a column header.
- To change the sort order, click the column header again. Each time you click the same header, the sort order toggles between ascending to descending order. The current order is indicated by a triangle in the column header.
How to Select Table Data
- To select a row, select the row or use the up or down arrow to navigate to the row.
- To select all rows (except for the header row), press CTRL + A .
- To select consecutive rows, press and hold the SHIFT key while clicking the rows or using the arrow keys.
- To select nonconsecutive rows, press the CTRL key and click to add a row to the selection.
- You cannot select columns, and you cannot select the entire column header row.
How to Copy Rows
To copy one or more rows from the table, select the rows and then press CTRL+C.
You can paste the data into any text or spreadsheet program. You cannot copy columns or parts of rows and you cannot copy the column header row.
How to Search in the Table (Quick Filter)
Use the Filter box to search for data in the table. When you type in the box, only items that include the typed text appear in the table.
Search for text. To search for text in the table, in the Filter box, type the text to find.
Search for multiple words. To search for multiple words in the table, type the words separated by spaces. Out-GridView displays rows that include all the words (logical AND).
Search for literal phrases. To search for phrases that include spaces or special characters, enclose the phrase in quotation marks. Out-GridView displays rows that include an exact match for the phrase.
Search in columns. To search for text in one or more columns, use the following format:
For example, to find «Net» in the DisplayName column, in the Filter box, type:
To find rows with «Net» in the DisplayName and Name columns, in the Filter box, type:
Turn off search. To display the entire table again, click the red X button in the top right corner of the Filter box or delete the text from the Filter box.
Use Criteria to Filter the Table
You can use rules or criteria to determine which items are displayed in the table. Items appear only when they satisfy all the criteria that you establish. The available criteria are determined by the properties of the objects displayed in the grid view window and the .NET Framework types of those properties.
Each criterion has the following format:
Criteria for different properties are connected by AND. Criteria for the same property are connected by OR. You cannot change the logical connectors.
The criteria only affects the display. It does not delete items from the table.
How to Add Criteria
- To display the Add criteria menu button, in the upper right corner of the window, click the Expand arrow.
- Click the Add Criteria menu button.
- Click to select columns (properties). You can select one or many properties.
- When you are finished selecting properties, click the Add button.
- To cancel the additions, click Cancel.
- To add more criteria, click the Add Criteria button again.
How to Edit a Criterion
- To change an operator, click the blue operator value, and then select a different operator from the drop-down list.
- To enter or change a value, type a value in the value box. If you enter a value that is not valid, a circular X icon appears. To remove it, change the value.
- To create an OR statement, add a criteria with the same property.
How to Delete Criteria
- To delete selected criteria, click the red X beside each criterion.
- To delete all criteria, click the Clear All button.
Источник