PowerShell has an excellent command-line tool that helps you discover other PowerShell commands. It is called Get-Command
.
In this tutorial, we will learn the PowerShell Get-Command
cmdlet, which we can use to find other commands.
- Examples.
- Command Options.
We will start by looking at several practical examples to learn how the Get-Command
cmdlet works.
Examples
List all available Cmdlets, Functions, and Aliases:
Get-Command
Using one of the following commands, you can list all commands that are installed on your computer:
Get-Command *
Get-Command -Type All
List all available cmdlets:
Get-Command -Type Cmdlet
List all functions:
Get-Command -Type Function
Find commands that have the word dns in their name:
Get-Command *dns*
Find commands whose names start with the word restart:
Get-Command restart*
Find commands end with the word computer:
Get-Command *computer
List all commands starting with the verb get:
Get-Command -Verb get
List commands that have the string event in the noun part:
Get-Command -Noun *event*
Find commands of the verb set that has the word firewall in the noun part:
Get-Command -Verb set -Noun *firewall*
List all commands that belong to the NetTCPIP
module:
Get-Command -Module NetTCPIP
Find the commands that use the -ComputerName
parameter:
Get-Command -ParameterName ComputerName
The following command returns the syntax of the Get-Service
cmdlet:
Get-Command Get-Service -Syntax
List only the commands imported to the current session:
Get-Command -ListImported
Get the path to the executable file of the Ping command:
(Get-Command ping).Definition
Run the following command to view the full documentation of the Get-Command
cmdlet:
Get-Help Get-Command -Full
Command Options
The following table lists the most common parameters of Get-Command
cmdlets. You can get the list of all parameters by running the Get-Help Get-Command -Parameter *
command.
-Type, -CommandType | Use this option to Specify the types of commands you want to find (e.g., cmdlets, functions, script, and aliases). |
-ListImported | Displays only the commands imported to the current session. |
-Module | Use this option to find commands in a specific module(s). |
-Verb | Finds the commands that include the specified verb. |
-Noun | Use this option to search a specific word or string in the noun part. |
-ParameterName | Use this option to find commands that use specific parameters. |
-ShowCommandInfo | Displays command information. |
-TotalCount | Use this option to limit the number of results. |
In Windows PowerShell, we use Get-Command
to discover other commands. When you enter Get-Command
without any option, it shows a list of all cmdlets, functions, and aliases:
Get-Command
By default, it includes all cmdlets, functions, and aliases. To list a specific type, use the -Type
parameter. For example, Get-Command -Type Cmdlet
list all cmdlets:
The following table shows acceptable values for the -Type
parameter.
All |
Alias |
Application |
Cmdlet |
ExternalScript |
Filter |
Function |
Script |
The Get-Command
supports wildcard searches. To search a text anywhere in the command name, put two asterisks (*) at the start and end of the search string.
For example, if the search term is computer, the search will return all commands with the letters «computer» anywhere in the name.
To find commands that start with a particular text put an asterisk (*) at the end of the search term.
Start the search term with an asterisk (*) to find commands ending with a particular word or text.
All built-in PowerShell commands follow the verb-noun naming format. We can search for a specific text in the verb and noun parts using the -Verb
and -Noun
parameters.
In the following example, we use the -Verb
parameter to find all cmdlets that stop something:
Get-Command -Verb *stop*
This command gets all cmdlets that work with Windows Services:
Get-Command -Noun *service
Use the -ParameterName
to find all commands that use the specific parameter(s). For example following command list all cmdlets that use the -ComputerName
parameter:
Get-Command -Type Cmdlet -ParameterName ComputerName
Another important parameter is the -Module
which you can use to list commands belonging to a specific PowerShell module.
Get-Command -Module NetTCPIP
In the above example, we list all commands belonging to the NetTCPIP
module. You can get a list of all available PowerShell modules by running the Get-Module -ListAvailable
command.
Conclusion
That brings the end of this tutorial about the Get-Command
cmdlet. We learned how to use Get-Command
to list PowerShell Command by looking at several examples.
In the next tutorial, we will learn the Get-Help cmdlet.
Something that I use very often is Get-Command. It shows you what module the cmdlet is from, what cmdlets a module has, etc. In this last blog post of 2024, I will show you how it works 🙂
- What is Get-Command?
- Parameters
- All
- CommandType
- FullyQualifiedModule
- FuzzyMinimumDistance
- ListImported
- Module
- Name
- Noun
- ParameterSetName
- ParameterSetType
- ShowCommandInfo
- Syntax
- TotalCount
- UseAbbreviationExpansion
- UseFuzzyMatching
- Verb
- Examples
- Get all cmdlets for a specific module
- Find out from what Module a specific cmdlet is from
- Check what Test cmdlets are available on the system
- See what was imported in my current PowerShell session
- Wrapping up
“The Get-Command
cmdlet gets all commands that are installed on the computer, including cmdlets, aliases, functions, filters, scripts, and applications. Get-Command
gets the commands from PowerShell modules and commands that were imported from other sessions. To get only commands that have been imported into the current session, use the ListImported parameter.
Without parameters, Get-Command
gets all the cmdlets, functions, and aliases installed on the computer. Get-Command *
gets all types of commands, including all the non-PowerShell files in the Path environment variable ($env:PATH
), which it lists in the Application command type.
Get-Command
that uses the exact name of the command, without wildcard characters, automatically imports the module that contains the command so that you can use the command immediately. To enable, disable, and configure automatic importing of modules, use the $PSModuleAutoLoadingPreference
preference variable. For more information, see about_Preference_Variables.
Get-Command
gets its data directly from the command code, unlike Get-Help
, which gets its information from help topics.
Starting in Windows PowerShell 5.0, results of the Get-Command
cmdlet display a Version column by default. A new Version property has been added to the CommandInfo class.”
Source: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/get-command?view=powershell-7.4
Parameters
In the chapters below, I will cover the Parameters for Get-Command:
All
Using the -All Parameter, Get-Command will return all commands, including commands of the same type with the same name. Depending on how many modules you have installed, this could take some time to process 🙂 On my system, it took 50 seconds to count the 98430 (!) cmdlets.
CommandType
When using the -CommandType Parameter, you can search for specific types of cmdlets. Valid types are:
- Alias, this will retrieve the aliases of all PowerShell commands
- All, this will return all kinds, and if the same as using *
- Application, this will search in the $Env:Path / $Env:PatheXT for non-PowerShell executable files.
- Cmdlet, returned all cmdlets
- ExternalScript, returns all .ps1 files in the $Env:Path variable.
- Filter, returns all simple and advanced Filters
- Function, returns all simple and advanced Functions.
- Script, returns all Script Blocks and should be used with the ExternalScript value to scan all .ps1 files.
You can use multiple values separated by a comma; for example, Get-Command -CommandType ExternalScript, Script will return all the Script Blocks inside the .ps1 file in $Env:path.
FullyQualifiedModule
Using the -FullyQualifiedModule Parameter, you can specify a module name, full module specification, or the path to a module file. This can’t be used with the -Module Parameter.
FuzzyMinimumDistance
The -FuzzyMinimumDistance Parameter allows you to be more or less accurate in your search. Using this, with the Uint32 type, you can get more accurate results with a lower value, with 0 being an exact match.
ListImported
Using the -ListImported Parameter, you can only display all the commands from the current session. This would return all basis cmdlets, including mkdir, prompt, drive letters, etc., and everything from the Functions and Modules imported by your PowerShell profile.
Module
With the -Module Parameter, you can specify an array of modules to retrieve the cmdlets. For example, Get-Command -Module Microsoft.Graph.Sites, Microsoft.Graph.Teams would return the cmdlets for both modules. This can’t be used with the -FullyQualifiedModule Parameter.
Name
You can specify an array of names using the -Name Parameter, and Get-Command will return information for those if found. Wildcards are allowed, and if two cmdlets have the same name, Get-Command will return the information for the one that runs when you type the cmdlet’s name. For example, Get-Command -Name Get-VM, Get-Host will return two cmdlets with their source module name.
Noun
Using the -Noun Parameter, you can let Get-Command return all cmdlets, Functions, or Aliases that include the specified noun or nouns. You can select one or more, including wildcards. For example, Get-Command -Noun JSON, XML will return all the ConvertFrom-XML, ConvertFrom-JSON but also the ConvertTo-XML, ConvertToJSON cmdlets, etc.
ParameterSetName
Using the -ParameterSetName Parameter, you can get all commands in the session using the specified parameters. You can enter Name, Aliases, or Wildcards.
ParameterSetType
Using the -ParameterSetType Parameter, you can get all commands in the session that have Parameters using the specified Type. You can enter Name, Aliases, or Wildcards.
ShowCommandInfo
When using the -ShowCommandInfo Parameter, Get-Command will return more information on the cmdlets found, including Parameters and Parameter Sets.
Syntax
Using the -Syntax Parameter, Get-Command will return the following data about the cmdlets: Aliases, Cmdlets, Functions and Filters, Scripts, Applications, or Files.
TotalCount
With the -TotalAcount Parameter, you can limit the number of cmdlets returned. For example, Get-Command -Name ConvertFrom-* -TotalCount 1 would only return the first one found instead of the 112 on my system.
UseAbbreviationExpansion
Using the -UseAbbreviationExpansion Parameter, you can match the characters you supplied to an upper-case character in the result. For example, Get-Command -UseAbbreviationExpansion i-psdf would match Import-PowerShellDataFile.
UseFuzzyMatching
Using the -UseFuzzyMatching Parameter, you will use a fuzzy matching algorithm to find cmdlets. The output will be ordered from the closest match to the least likely match. It can’t be used together with wildcards.
Verb
Similar to the -Noun Parameter, the -Verb Parameter can be used to find cmdlets, Functions, and Aliases based on how the array of verbs is supplied. For example, Get-Command -Verb Select, Show returns all cmdlets that start with either Select or Show.
Examples
In the chapters below are a few examples I often use to discover things.
Get all cmdlets for a specific module
In the example below, I use Get-Command to retrieve all cmdlets from the Microsoft.Graph.Teams module:
Find out from what Module a specific cmdlet is from
In the example below, I use Get-Command to determine where the Out-ConsoleGridView cmdlet is from. (Easy if you want to use it on another system and are not sure from what module it originates from)
Check what Test cmdlets are available on the system
In the example below, I use Get-Command to return all the cmdlets starting with the Test Verb: (987 to be precise)
See what was imported in my current PowerShell session
In the example below, I use Get-Command to list all the imported commands: (433 to be precise)
Wrapping up
That’s the last blog post for 2024! 🙂 I covered how you can use Get-Command to search for and find information about everything available on your system; it’s just a nice way of discovering things!
Have a great New Year’s Eve, and I will see you next year!
Photo from last year in Amsterdam (Museumplein)
Most of us prefer PowerShell due to its automation capabilities. It’s a command-line shell with a fully developed scripting language. You can use the built-in cmdlets or write your own script to automate the administrative tasks of Windows and other compatible operating systems. It allows you to do everything that you can do with the GUI apps and more.
However, mastering the functionality and flexibility of PowerShell involves a steep learning curve. If you are just getting started with PowerShell, here are the essential commands you can learn to master this scripting language in the long run.
1. Get-Help
Get-Help, as the name suggests, is part of PowerShell’s integrated help system. It helps you find necessary information for the command, concepts, and functions, identify alias, scripts, and more.
To get help for a PowerShell cmdlet, you need to use the Get-help cmdlet followed by a cmdlet name. For example, to view the synopsis and syntaxes associated with the get-process cmdlet, type:
Get-Help Get-Process
This command can read both comment-based and XML-based help provided by the function author.
Alternatively, you can use the Get-Help -online command to get help for a PowerShell cmdlet online. For example, to view Microsoft’s online documentation for the Get-Content cmdlet, type:
Get-Help Get-Content -online
2. Get-Process
The Get-Process command helps you retrieve and show a list of all the active system processes with their identifiers (IDs). You can use it as an efficient alternative to Windows Task Manager to view, stop and restart system processes.
For example, if you need to stop the GameBar process, first you need to find the process ID associated with it. So, type:
Get-Process
This command will show all the running system processes. Next, find the ID associated with the process you want to stop. To stop the process, type:
Get-Process -ID 20496 | Stop-Process
Here -ID 20496 is the ID of the process (GameBar) you want to stop.
3. Start-Process
You can use the Start-Process cmdlet in PowerShell to start one or more processes on a local computer. To use the cmdlet, type Start-Process followed by the process name. For example, if you want to start a new notepad process, type:
Start-Process notepad
Additionally, you can use the parameters of Start-Process to specify options. For example, if you need to launch a process as administrator, type:
Start-Process -FilePath "notepad" -Verb runAs
4. Get-Command
The Get-Command lets you view all the PowerShell commands installed on your computer. Similar to Get-Help, you can use the Get-Command followed by a search query to find commands for a specific feature.
Since the Get-Command displays all the commands, you can specify parameters to find features with a specific name and CommandType. For example, to find cmdlets (CommandTypes) that start with A (Name), type:
Get-Command -Name A* -CommandType cmdlet
Alternatively, type Get-Help Get-Command -Examples to view more examples.
5. Get-Service
The Get-Service cmdlet lets you view your computer’s status and list of services. By default, the Get-Service command returns all the (stopped and running) services.
You can use the parameters to specify and find services depending on their status, name, and dependent services. For example, to view all the services starting with the name Win, type:
Get-Service -Name "Win*"
6. Get-ChildItem
You can use PowerShell to search through directories. The Get-ChildItem command is a handy cmdlet to look for folders and files and quickly perform content-based searches without using File Explorer.
To view all the top-level folders in the C:\ directory, type:
Get-ChildItem "C:\"
Additionally, use the -Path parameter to view a particular folder, sub-folders, and content. For example, to view all the sub-folders and files in the Programs Files folder, type:
Get-ChildItem -Path "C:\Program Files"
Additionally, use the —Recurse parameter to view all the files in the specified folder and the -Name parameter to view item names in a directory.
Get-ChildItem -Path "C:\Program Files\Fodler_Name" -Recurse | Select FullName
In the above command, replace sub-folder with the folder name to view its content.
7. Copy-Item
The Copy-Item cmdlet lets you copy-paste files and folders and their contents to a different directory. To copy files and folders, type Copy-Item followed by the source —Path, -Destination parameter, and destination address. For example, to copy E:\Folder1 and its contents to E:\Folder2, type:
Copy-Item "E:\Folder1" -Destination "E:\Folder2" -Recurse
Note that the -Recurse parameter in the above command is responsible for moving all the folder contents. Without it, PowerShell will only copy the top-level folder (Folder1) and files specified in the command.
8. Move-Item
Similarly, to move an item, you can use the Move-Item cmdlet. For example, to move the folder, files, sub-folders, and all its contents to your specified destination, type:
Move-Item -Path "E:\Folder1" -Destination "E:\Folder2"
9. Remove-Item
The Remove-Item cmdlet lets you delete files, folders, functions, and other data types from the specified directory. For example, to delete the Test.txt file in the E:\Folder1 folder, type:
Remove-Item E:\Folder1\Test.txt
10. Get-Content
The Get-Content cmdlet lets you view the content of an item item without using a text editor. For example, to retrieve the contents of the Test.txt file, type:
Get-Content "E:\Folder1\Test.txt"
You can further specify the content length to view using the -TotalCount parameter.
11. Clear-Content
You can use the Clear-Content cmdlet to delete the contents of a specified file without deleting the file itself. Useful for task automation where you have a hard-coded file name but want to have a clean file each time the script runs.
To test the command, create a text file with some content in it. Next, type:
Clear-Content -Path "E:\Folder1\Test1.txt"
This will delete the contents of the file without deleting the file.
12. Set-ExecutionPolicy
The default execution policy in PowerShell is set to Restricted. This prevents the execution of malicious scripts in the PowerShell environment. However, when you execute a local PowerShell script, you may encounter the execution script is disabled on this system error.
The Set-ExecutionPolicy cmdlets let you change the security levels for script execution. To know your current execution policy, type:
Get-ExecutionPolicy
If you need to execute an unsigned script, in an elevated PowerShell prompt, type:
Set-ExecutionPolicy RemoteSigned
Other valid Set-ExecutionPolicy values include Restricted, AllSigned, and Unrestricted.
13. Set-Location
By default, PowerShell uses C:\Users\Username as the default working directory. The Set-Location cmdlet lets you set the current working directory to a specified location. Useful if you want to run a script or command from a specific location without having to specify the path each time.
For example, to set C:\Users\Username\Documents as the current working directory, type:
Set-Location "C:\Users\usrename\Documents"
This is a temporary measure as PowerShell will reset the working directory back to its default directory after the restart.
14. Export-CSV
If you want to export and present PowerShell output in a more organized way, you can use the Export-CSV cmdlet. It takes the output file for the specified command and converts it to a CSV file.
To test the command, try the following command:
Get-Process | Export-CSV PSprocess.csv
The above command will create a psporcess.csv file with all the active processes’ data.
15. ConvertTo-HTML
If you would rather create an HTML report, you can use the ConvertTo-HTML Cmdlet. To create an HTML report for all the running process on your PC, type :
Get-Process | ConvertTo-HTML > PSprocess.html
In the above command, psprocess is the name of the export file, and HTML is the extension. You can access the exported HTML file in the current working directory located at C:\Users\username.
16. Get-History
You can use the Up-Down arrow key to scroll through the recently executed commands in PowerShell. However, to view a list of all the recently executed commands in your current session at once, you can use the Get-History cmdlet.
It will display a list of all the recently executed commands with their ID. Useful if you want to view the complete context of the previously executed commands. To do this, type:
Get-History Id | fl
For example, to view the execution details such as status, start and end time, and duration for the third command, type:
get-history 3 | fl,
To rerun any command from the list, type:
Invoke-History followed by the command id
For example, type Invoke-History 3 to rerun a previously executed command without typing it again.
Additionally, use Clear-History to clear history for the current session.
Now that you have a basic idea of PowerShell commands, go ahead and explore our guide on best PowerShell Cmdlets to improve your Windows admin skills. Here, you can learn to work with data using cmdlets, format tables and list, and a quick overview of the Get-Member command.
PowerShell Commands to Streamline Your Tasks
PowerShell is known for its automation capabilities. This can help you automate hundreds of activities in your development work to save time and improve productivity.
While we have only covered the basic commands, try to explore the syntax, alias, and variables, functions available on many of these commands to master this highly efficient scripting language.
Время на прочтение3 мин
Количество просмотров122K
Наверное, все слышали о PowerShell, но наверняка не всем довелось с ним работать. Для тех, кто только начинает прокладывать свой путь в дебри PowerShell, мы приводим перевод поста, вышедшего на портале 4sysops.com. В нем рассказано о 7 командах, которые помогут тем, кто только начал работать с PowerShell. За подробностями – добро пожаловать под кат.
GET-HELP
Самый первый и самый главный командлет PowerShell – вызов справки. С помощью командлета Get-Help можно проверить синтаксис, посмотреть примеры использования и детальное описание параметров любого PowerShell командлета. Этот командлет примечателен тем, что вы просто можете набрать Get-Help Services, чтобы получить список всех командлетов, которые подходят для работы со службами.
Пример:
PS C:\> Get-Help Service
Вы можете выбрать любой командлет из списка, выведенного по запросу выше, чтобы получить справку о нем. Например,
PS C:\> Get-Help -Name Get-Service
Вы получаете всю информацию о командлете Get-Service (будет рассмотрен ниже).
GET-CONTENT
Чтение содержимого файлов – наиболее частое требование для новичков, которые пытаются выучить PowerShell. Процедура чтения файлов с PowerShell упрощается. Даже неспециалист может читать содержимое файла, просто передав его в командлет Get-Content.
Пример.
PS C:\> Get-Content C:\scripts\Computers.txt
mytestpc1
techibee.com
dummynotresolvinghost.com
PS C:\>
Необходимо больше информации о командлете? Воспользуйтесь Get-Help:
PS C:\> Get-Help Get-Content -Detailed
GET-SERVICE
Этот командлет перечисляет все службы, установленные на компьютере. Вы можете использовать его для получения информации о конкретной службе, совокупности служб или просто обо всех службах на компьютере.
Пример:
PS C:\> Get-Service wwansvc, spooler
Status Name DisplayName
------ ---- -----------
Running spooler Print Spooler
Stopped wwansvc WWAN AutoConfig
PS C:\>
Здесь мы запросили информацию о двух службах wwansvc и spooler
Выводится таблица со статусом службы, ее именем и отображаемым именем.
Мы можем видеть что служба spooler запущена, а wwansvc остановлена
STOP-SERVICE И START-SERVICE
Запуск и остановка служб – достаточно важный момент в работе администратора Windows. В PowerShell имеются встроенные командлеты, которые упрощают работу администратора, не требуя открытия консоли MMC. Используя эти командлеты Вы можете останавливать/запускать службы как на локальных, так и на удаленных компьютерах.
Примеры:
Запуск/остановка службы на локальном компьютере (на примере службы spooler):
PS C:\> Stop-Service -Name Spooler
PS C:\> Start-Service -Name Spooler
Запуск/остановка службы на удаленном компьютере (spooler):
PS C:\> $ServiceObj = Get-Service -ComputerName MyPC1 -Name spooler
PS C:\> Stop-Service -InputObj $ServiceObj
PS C:\> Start-Service -InputObj $ServiceObj
GET-PROCESS
Этот командлет позволяет быть в курсе, какие процессы запущены на локальных или удаленных компьютерах. Показываются имя и ID процесса, а также путь к исполняемому файлу, имя компании, версия исполняемого файла и память, используемая процессом.
Примеры:
Получение информации о процессах, запущенных на локальном компьютере:
PS C:\> Get-Process
Введите следующий командлет для получения подробной информации о запущенных процессах
PS C:\> Get-Process | Format-List * -Force
Получение информации о процессах, запущенных на удаленном компьютере:
PS C:\> Get-Process -ComputerName MYPC1 | Format-List * -Force
MYPC1 необходимо заменить на имя того компьютера, с которого вы хотите получить информацию о запущенных процессах.
STOP-PROCESS
Этот командлет остановливает процесс на локальном или удаленном компьютере. Он берет имя или ID процесса и завершает этот процесс. Это полезно в тех случаях, когда приложение не отвечает.
Пример:
Остановить процесс с ID 22608 на локальном компьютере:
PS C:\> Stop-Process -Id 22608
Остановить все процессы Excel на локальном компьютере:
PS C:\> Stop-Process -name excel
Совет: Хотя у командлета Stop-Process отсутствует параметр -ComputerName, Вы все равно можете использовать его для завершения удаленных процессов, используя предложенный ниже совет:
PS C:\> $Obj = Get-Process -Name excel -ComputerName MYPC1
PS C:\> Stop-Process -InputObject $Obj
Upd:
В посте приведен перевод статьи с портала 4sysops.com
Top 7 PowerShell commands for beginners
P.S. Смотрите также интересные посты на Хабре, посвященные работе с PowerShell
Аудит доступа к файлам
Аудит Active Directory (Часть 1 и 2)
Актуализируем учетные данные Active Directory
Аудит создания учетных записей в AD
Командлетов в Windows PowerShell много поэтому сегодня я предлагаю рассмотреть небольшой список наиболее полезных и часто используемых командлетов с кратким описанием того, что они умеют. Данный справочник поможет Вам быстрей найти интересующую Вас команду Windows PowerShell и ориентирован он на начинающих системных администраторов.
Ранее в материале «Основы Windows PowerShell» мы с Вами узнали, что вообще такое PowerShell, а также рассмотрели основные его возможности. Поэтому данная статья подразумевает, что Вы уже имеете представление о том, что такое Windows PowerShell и сейчас мы не будем заострять на этом внимание, а сразу перейдем к рассмотрению командлетов.
Конечно же, ниже представлен неполный перечень командлетов, так как их на самом деле очень много, полный список командлетов в системе Вы можете получить, выполнив следующую команду в оболочке PowerShell.
Get-Command -CommandType cmdlet
Если Вы, выполнив вышеуказанную команду у себя на компьютере, не нашли командлет из представленного ниже списка (или тот который Вам нужен), то скорей всего у Вас не установлен необходимый модуль. Модули PowerShell для соответствующих ролей и компонентов сервера устанавливаются автоматически одновременно с ними. В случае если Вы хотите воспользоваться данными модулями на системе без установленных ролей и компонентов, то Вы всегда можете установить соответствующие «Средства удаленного администрирования сервера», которые добавляют не только оснастки управления, но и необходимые командлеты. Например, для того чтобы администрировать Active Directory с помощью Windows PowerShell на компьютере, который не является контроллером домена, необходимо установить модуль Active Directory для Windows PowerShell (RSAT-AD-PowerShell).
Примечание! Данный справочник составлен на основе командлетов версии PowerShell 5.0 в операционной системе Windows Server 2016.
Содержание
- Полезные командлеты Windows PowerShell
- Работа с переменными
- Форматирование в Windows PowerShell
- Импорт и экспорт
- Работа с сетью в Windows PowerShell
- Работа с элементами
- Командлеты для работы с Active Directory (AD)
- Работа с Hyper-V
- Работа с фоновыми заданиями
- Работа с объектами
- Командлеты PowerShell для удаленного управления
- Работа со службами и процессами
- Работа с компьютером
- Работа с контентом
- Другие командлеты Windows PowerShell
В данном разделе я перечислю командлеты PowerShell, которые Вы точно будете использовать.
- Get-Help – показывает справку по командлету, функции и общую справку по Windows PowerShell. Справка бывает нескольких типов: краткая, детальная, полная и вывод только примеров;
- Update-Help — загружает и устанавливает новые файлы справки, т.е. обновление справки;
- Get-Command – командлет поиска нужной команды, можно искать как по глаголу, так и по существительному, также возможно использование маски, если Вы не знаете точное наименование глагола или существительного;
- Get-Alias – показывает псевдонимы, все или конкретной команды;
- Get-PSDrive – показывает подключенные диски;
- Get-Member – выводит свойства и методы, которые есть у объекта;
- Get-WindowsFeature – выводит сведения о доступных ролях и компонентах сервера;
- Install-WindowsFeature (эквивалентен Add-WindowsFeature) — устанавливает роли или компоненты на указанный сервер;
- Uninstall-WindowsFeature (эквивалентен Remove-WindowsFeature) – удаляет роли или компонента сервера;
- Get-History — возвращает список команд, введенных в ходе текущей сессии.
Работа с переменными
В PowerShell для того чтобы создать переменную, задать ей значение или получить это значение обычно используют знак доллар $ (коротко и удобно), но для этих целей существуют специальные командлеты.
- Get-Variable – выводит список переменных и их значения (или одну указанную переменную);
- New-Variable – создает новую переменную;
- Set-Variable – задает значение переменной. Если переменная с указанным именем не существует, то она будет создана;
- Clear-Variable — удаляет значение переменной;
- Remove-Variable — удаляет переменную и ее значение.
Заметка! Программирование на языке PowerShell.
Форматирование в Windows PowerShell
В Windows PowerShell существует набор командлетов, которые предназначены для форматирования вывода результата работы командлета. Они позволяют пользователю отобразить результат в том виде, в котором ему удобно просматривать данный результат.
- Format-List – вывод результата команды в формате списка свойств, где на каждой новой строке отдельное свойство;
- Format-Table — вывод результата команды в виде таблицы;
- Format-Wide — вывод результата команды в виде широкой таблицы, в которой отображается только одно свойство каждого объекта;
- Format-Custom – в данном случае форматирование вывода происходит с использованием пользовательского представления.
Импорт и экспорт
PowerShell позволяет импортировать и экспортировать данные в разных распространенных форматах, например, CSV или XML, а также перенаправлять вывод результата работы команды во внешний файл или на принтер.
- Export-Csv – экспорт данных в формат CSV;
- Import-Csv – импортирует данные из CSV файла;
- Export-Clixml — экспорт данных в формат XML;
- Import-Clixml — импортирует файл CLIXML и создает соответствующие объекты в оболочке Windows PowerShell;
- Out-File — посылает вывод результата работы командлета во внешний файл (например, в TXT);
- Out-Printer — вывод результата работы команды на принтер;
- Import-Module — добавляет модули в текущей сессии.
Работа с сетью в Windows PowerShell
Для администрирования сети в Windows PowerShell существуют такие командлеты как:
- Disable-NetAdapter – командлет отключает сетевой адаптер;
- Enable-NetAdapter – данный командлет включает сетевой адаптер;
- Rename-NetAdapter — переименовывает сетевой адаптер;
- Restart-NetAdapter — перезапускает сетевой адаптер;
- Get-NetIPAddress – выводит информацию о конфигурации IP-адреса;
- Set-NetIPAddress — изменяет конфигурацию IP-адреса;
- New-NetIPAddress — создает и настраивает IP-адрес;
- Remove-NetIPAddress — удаляет IP-адрес и его конфигурацию;
- Get-NetRoute — выводит таблицу маршрутизации IP;
- Set-NetRoute — изменяет таблицу маршрутизации IP;
- New-NetRoute — создает запись в таблице маршрутизации IP;
- Remove-NetRoute — удаляет одну или несколько записей (IP маршрутов) из таблицы маршрутизации IP;
- Get-NetIPv4Protocol — выводит информацию о конфигурации протокола IPv4;
- Get-NetIPv6Protocol — выводит информацию о конфигурации протокола IPv6;
- Get-NetIPInterface — выводит информацию о свойствах интерфейса IP;
- Get-NetTCPSetting — показывает информацию о настройках и конфигурации TCP;
- Test-Connection – командлет посылает ICMP пакеты к одному или нескольким компьютерам, т.е. «пингует» компьютеры.
Заметка! Описание и назначение ролей сервера в Windows Server 2016.
Работа с элементами
В Windows PowerShell есть командлеты, которые умеют работать с элементами, под элементами здесь можно понимать: файлы, папки, ключи реестра и так далее.
- Clear-Item — очищает содержимое элемента, но не удаляет сам элемент;
- Copy-Item – копирует элемент;
- Get-Item — получает элемент в указанном месте;
- Invoke-Item — выполняет действие по умолчанию над указанным элементом;
- Move-Item – перемещает элемент;
- New-Item – создает новый элемент;
- Remove-Item – удаляет указанные элементы;
- Rename-Item — переименовывает элемент в пространстве имен поставщика Windows PowerShell;
- Set-Item — изменяет элемент;
- Get-ChildItem — возвращает элементы и дочерние элементы в одном или нескольких определенных местах;
- Get-Location – выводит информацию о текущем местонахождении.
Командлеты для работы с Active Directory (AD)
Windows PowerShell, конечно же, позволяет работать со службой каталогов Active Directory. Для этих целей существует немало командлетов, вот некоторые из них:
- New-ADUser – создание нового пользователя в Active Directory;
- Get-ADUser – выводит информацию о пользователях Active Directory;
- Set-ADUser — изменяет пользователя Active Directory;
- Remove-ADUser — удаляет пользователя Active Directory;
- New-ADGroup – командлет создает группу в Active Directory;
- Get-ADGroup – выводит информацию о группе или выполняет поиск, чтобы получить несколько групп из Active Directory;
- Set-ADGroup – командлет изменяет группу в Active Directory;
- Remove-ADGroup — удаление группы в Active Directory;
- Add-ADGroupMember — командлет добавляет учетные записи пользователей, компьютеров или групп в качестве новых членов группы Active Directory;
- Get-ADGroupMember — выводит информацию о членах группы Active Directory;
- Remove-ADGroupMember — удаление элементов из группы Active Directory;
- Set-ADAccountPassword — сброс пароля учетной записи Active Directory;
- Disable-ADAccount — отключает учетную запись Active Directory.
- Enable-ADAccount — включает учетную запись Active Directory;
- Unlock-ADAccoun — разблокирует учетную запись Active Directory;
- New-ADComputer — создание новой учетной записи компьютера в Active Directory;
- Get-ADComputer — выводит информацию об одном или нескольких компьютерах в Active Directory;
- Set-ADComputer — изменение учетной записи компьютера в Active Directory;
- Remove-ADComputer — удаление компьютера из Active Directory.
Работа с Hyper-V
Для работы с Hyper-V в Windows PowerShell существует много командлетов, вот небольшой перечень:
- New-VM — создание новой виртуальной машины;
- Set-VM — настройка виртуальной машины;
- Start-VM — запуск виртуальной машины;
- Stop-VM — закрытие, выключение или сохранение виртуальной машины;
- Import-VM — импорт виртуальной машины из файла;
- Move-VM — перемещение виртуальной машины на новый Hyper-V хост;
- Remove-VM — удаление виртуальной машины;
- Rename-VM — переименование виртуальной машины;
- New-VHD — создание одного или нескольких новых виртуальных жестких дисков;
- Set-VHD – настройка виртуального жесткого диска;
- Test-VHD — тестирование виртуального жесткого диска на предмет обнаружения проблем, которые сделали бы его непригодным для использования;
- Add-VMDvdDrive — добавляет DVD диск к виртуальной машине;
- Remove-VMDvdDrive — удаляет DVD-диск из виртуальной машины;
- Add-VMHardDiskDrive — добавляет жесткий диск к виртуальной машине;
- Remove-VMHardDiskDrive — удаляет один или несколько виртуальных жестких дисков (VHD) из виртуальной машины;
- Add-VMNetworkAdapter — добавляет виртуальный сетевой адаптер на виртуальной машине;
- Remove-VMNetworkAdapter — удаляет один или несколько виртуальных сетевых адаптеров из виртуальной машины;
- Copy-VMFile — копирование файлов на виртуальную машину;
- Get-VMVideo – выводит информацию о настройках видео для виртуальных машин;
- Move-VMStorage — перемещение хранилища виртуальной машины.
Заметка! Описание компонентов сервера в Windows Server 2016.
Работа с фоновыми заданиями
В Windows PowerShell есть возможность запускать задачи в фоновом режиме, для того чтобы, не дожидаясь окончания работы команды (для случаев, когда задача выполняется долго), продолжать работать в текущей сессии. Для работы с фоновыми заданиями в PowerShell есть следующие командлеты:
- Start-Job – запустить фоновую задачу;
- Stop-Job – остановить фоновую задачу
- Get-Job – посмотреть список фоновых задач;
- Receive-Job – посмотреть результат выполнения фоновой задачи;
- Remove-Job – удалить фоновую задачу;
- Wait-Job – перевести фоновую задачу на передний план, для того чтобы дожидаться ее окончания.
Работа с объектами
Так как PowerShell работает с объектами, он позволяет выполнять некие действия над этими объектами, например:
- Measure-Object – командлет позволяет рассчитывать на основе свойств объектов такие числовые агрегирующие параметры как: минимальное, максимальное, среднее значение, сумму и количество. Например, Вы хотите узнать максимальный или средний размер файла в определенном каталоге, или просто узнать количество файлов (запущенных процессов, служб и так далее);
- Select-Object – с помощью данного командлета можно выбрать определенные объекты или свойства этих объектов, например Вы хотите выводить только название файла и его размер;
- Sort-Object — сортирует объекты по значениям свойств;
- Where-Object – командлет для того чтобы ставить условие для выборки объектов на основе значений их свойств;
- Group-Object – группирует объекты, которые содержат одинаковое значение для заданных свойств;
- ForEach-Object – перебор объектов с целью выполнения определенной операции над каждым из этих объектов.
Командлеты PowerShell для удаленного управления
С помощью Windows PowerShell можно выполнять команды не только на локальном компьютере, но и на одном или даже на нескольких удаленных компьютерах.
- Enter-PSSession — запускает интерактивный сеанс с удаленным компьютером;
- Exit-PSSession — завершает интерактивный сеанс с удаленным компьютером;
- New-PSSession — создает постоянное подключение к локальному или удаленному компьютеру;
- Remove-PSSession — закрывает один или несколько сеансов Windows PowerShell;
- Disconnect-PSSession — отсоединяется от сеанса;
- Connect-PSSession — подключается к отключенным сеансам;
- Get-PSSession — получает сеансы Windows PowerShell на локальных и удаленных компьютерах;
- Invoke-Command — выполняет команды на локальном и удаленных компьютерах.
Работа со службами и процессами
PowerShell, конечно же, умеет управлять службами и процессами в Windows, для этого существуют такие командлеты как:
- Get-Process – выводит информацию о запущенных процессах на компьютере;
- Start-Process – запускает один или несколько процессов на компьютере;
- Stop-Process — останавливает один или несколько запущенных процессов;
- Get-Service – выводит информацию о службах;
- Restart-Service – перезапускает службу;
- Start-Service – запускает службу;
- Stop-Service — останавливает службу;
- Suspend-Service – приостанавливает работу службы;
- Set-Service – с помощью данного командлета можно изменить свойства службы, например, описание, отображаемое имя и режим запуска. Также его можно использовать для запуска, остановки или приостановки службы.
Заметка! Установка файлового сервера (File Server) на Windows Server 2016.
Работа с компьютером
Windows PowerShell позволяет выполнять административные задачи для операционной системы и компьютера в целом, например, перезапустить операционную систему или переименовать компьютер.
- Restart-Computer – командлет перезапускает операционную систему (перезагружает компьютер);
- Stop-Computer – выключает компьютер;
- Rename-Computer – переименовывает компьютер;
- Checkpoint-Computer — создает точку восстановления системы на локальном компьютере;
- Restore-Computer — запускает восстановление системы на локальном компьютере;
- Disable-ComputerRestore — отключает функцию восстановления системы на указанном диске файловой системы;
- Enable-ComputerRestore — включает функцию восстановления системы на указанном диске файловой системы;
- Remove-Computer — удаляет локальный компьютер из домена;
- Get-EventLog – выводит информацию о событиях в журнале событий, или список журналов событий на локальном или удаленном компьютере;
- Clear-EventLog — удаляет записи из указанных журналов событий.
Работа с контентом
Для управления контентом, например, текстом в файле в Windows PowerShell существуют специальные командлеты, такие как:
- Get-Content – получает содержимое элемента (например, считывает файл);
- Add-Content – добавляет содержимое в заданные элементы, например, текст в файл;
- Clear-Content — удаляет содержимое элемента, но не удаляет сам элемент;
- Set-Content — записывает или заменяет содержимое в элемент с новым содержанием.
Другие командлеты Windows PowerShell
Также хотелось бы выделить следующие командлеты Windows PowerShell, которые наверняка Вам понадобятся и будут полезны.
- Get-ExecutionPolicy – с помощью данного командлета можно узнать действующую политику выполнения Windows PowerShell для текущего сеанса;
- Set-ExecutionPolicy – командлет изменяет политику выполнения Windows PowerShell;
- Write-Host – выводит информацию на экран (пишет текст);
- Read-Host – считывает строку ввода из консоли;
- Write-Warning – выводит предупреждающее сообщение;
- Write-Error – командлет объявляет ошибку и выводит ее в поток ошибок;
- Get-Date – возвращает текущую дату и время;
- Set-Date – командлет изменяет системную дату и время на компьютере.
Заметка! Курсы по SQL для начинающих на примере Microsoft SQL Server.
Вот мы с Вами и рассмотрели полезные и часто используемые командлеты Windows PowerShell, надеюсь, этот справочник будет Вам полезен, удачи!