Windows powershell com object

Creating .NET and COM Objects (New-Object)

There are software components with .NET Framework and COM interfaces that enable you to perform many system administration tasks. Windows PowerShell lets you use these components, so you are not limited to the tasks that can be performed by using cmdlets. Many of the cmdlets in the initial release of Windows PowerShell do not work against remote computers. We will demonstrate how to get around this limitation when managing event logs by using the .NET Framework System.Diagnostics.EventLog class directly from Windows PowerShell.

Using New-Object for Event Log Access

The .NET Framework Class Library includes a class named System.Diagnostics.EventLog that can be used to manage event logs. You can create a new instance of a .NET Framework class by using the New-Object cmdlet with the TypeName parameter. For example, the following command creates an event log reference:

Although the command has created an instance of the EventLog class, the instance does not include any data. That is because we did not specify a particular event log. How do you get a real event log?

Using Constructors with New-Object

To refer to a specific event log, you need to specify the name of the log. New-Object has an ArgumentList parameter. The arguments you pass as values to this parameter are used by a special startup method of the object. The method is called a constructor because it is used to construct the object. For example, to get a reference to the Application log, you specify the string ‘Application’ as an argument:

Since most of the .NET Framework core classes are contained in the System namespace, Windows PowerShell will automatically attempt to find classes you specify in the System namespace if it cannot find a match for the typename you specify. This means that you can specify Diagnostics.EventLog instead of System.Diagnostics.EventLog.

Storing Objects in Variables

You might want to store a reference to an object, so you can use it in the current shell. Although Windows PowerShell lets you do a lot of work with pipelines, lessening the need for variables, sometimes storing references to objects in variables makes it more convenient to manipulate those objects.

Windows PowerShell lets you create variables that are essentially named objects. The output from any valid Windows PowerShell command can be stored in a variable. Variable names always begin with $. If you want to store the Application log reference in a variable named $AppLog, type the name of the variable, followed by an equal sign and then type the command used to create the Application log object:

If you then type $AppLog, you can see that it contains the Application log:

Accessing a Remote Event Log with New-Object

The commands used in the preceding section target the local computer; the Get-EventLog cmdlet can do that. To access the Application log on a remote computer, you must supply both the log name and a computer name (or IP address) as arguments.

Now that we have a reference to an event log stored in the $RemoteAppLog variable, what tasks can we perform on it?

Clearing an Event Log with Object Methods

Objects often have methods that can be called to perform tasks. You can use Get-Member to display the methods associated with an object. The following command and selected output show some the methods of the EventLog class:

The Clear() method can be used to clear the event log. When calling a method, you must always follow the method name by parentheses, even if the method does not require arguments. This lets Windows PowerShell distinguish between the method and a potential property with the same name. Type the following to call the Clear method:

Type the following to display the log. You will see that the event log was cleared, and now has 0 entries instead of 262:

Creating COM Objects with New-Object

You can use New-Object to work with Component Object Model (COM) components. Components range from the various libraries included with Windows Script Host (WSH) to ActiveX applications such as Internet Explorer that are installed on most systems.

New-Object uses .NET Framework Runtime-Callable Wrappers to create COM objects, so it has the same limitations that .NET Framework does when calling COM objects. To create a COM object, you need to specify the ComObject parameter with the Programmatic Identifier or ProgId of the COM class you want to use. A complete discussion of the limitations of COM use and determining what ProgIds are available on a system is beyond the scope of this user’s guide, but most well-known objects from environments such as WSH can be used within Windows PowerShell.

You can create the WSH objects by specifying these progids: WScript.Shell, WScript.Network, Scripting.Dictionary, and Scripting.FileSystemObject. The following commands create these objects:

Although most of the functionality of these classes is made available in other ways in Windows PowerShell, a few tasks such as shortcut creation are still easier to do using the WSH classes.

Creating a Desktop Shortcut with WScript.Shell

One task that can be performed quickly with a COM object is creating a shortcut. Suppose you want to create a shortcut on your desktop that links to the home folder for Windows PowerShell. You first need to create a reference to WScript.Shell, which we will store in a variable named $WshShell:

Get-Member works with COM objects, so you can explore the members of the object by typing:

Get-Member has an optional InputObject parameter you can use instead of piping to provide input to Get-Member. You would get the same output as shown above if you instead used the command Get-Member -InputObject $WshShell. If you use InputObject, it treats its argument as a single item. This means that if you have several objects in a variable, Get-Member treats them as an array of objects. For example:

The WScript.Shell CreateShortcut method accepts a single argument, the path to the shortcut file to create. We could type in the full path to the desktop, but there is an easier way. The desktop is normally represented by a folder named Desktop inside the home folder of the current user. Windows PowerShell has a variable $Home that contains the path to this folder. We can specify the path to the home folder by using this variable, and then add the name of the Desktop folder and the name for the shortcut to create by typing:

When you use something that looks like a variable name inside double-quotes, Windows PowerShell tries to substitute a matching value. If you use single-quotes, Windows PowerShell does not try to substitute the variable value. For example, try typing the following commands:

Читайте также:  Windows server update services failed

We now have a variable named $lnk that contains a new shortcut reference. If you want to see its members, you can pipe it to Get-Member. The output below shows the members we need to use to finish creating our shortcut:

We need to specify the TargetPath, which is the application folder for Windows PowerShell, and then save the shortcut $lnk by calling the Save method. The Windows PowerShell application folder path is stored in the variable $PSHome, so we can do this by typing:

Using Internet Explorer from Windows PowerShell

Many applications (including the Microsoft Office family of applications and Internet Explorer) can be automated by using COM. Internet Explorer illustrates some of the typical techniques and issues involved in working with COM-based applications.

You create an Internet Explorer instance by specifying the Internet Explorer ProgId, InternetExplorer.Application:

This command starts Internet Explorer, but does not make it visible. If you type Get-Process, you can see that a process named iexplore is running. In fact, if you exit Windows PowerShell, the process will continue to run. You must reboot the computer or use a tool like Task Manager to end the iexplore process.

COM objects that start as separate processes, commonly called ActiveX executables, may or may not display a user interface window when they start up. If they create a window but do not make it visible, like Internet Explorer, the focus will generally move to the Windows desktop and you must make the window visible to interact with it.

By typing $ie | Get-Member, you can view properties and methods for Internet Explorer. To see the Internet Explorer window, set the Visible property to $true by typing:

You can then navigate to a specific Web address by using the Navigate method:

Using other members of the Internet Explorer object model, it is possible to retrieve text content from the Web page. The following command will display the HTML text in the body of the current Web page:

To close Internet Explorer from within PowerShell, call its Quit() method:

This will force it to close. The $ie variable no longer contains a valid reference even though it still appears to be a COM object. If you attempt to use it, you will get an automation error:

You can either remove the remaining reference with a command like $ie = $null, or completely remove the variable by typing:

There is no common standard for whether ActiveX executables exit or continue to run when you remove a reference to one. Depending on circumstances such as whether the application is visible, whether an edited document is running in it, and even whether Windows PowerShell is still running, the application may or may not exit. For this reason, you should test termination behavior for each ActiveX executable you want to use in Windows PowerShell.

Getting Warnings About .NET Framework-Wrapped COM Objects

In some cases, a COM object might have an associated .NET Framework Runtime-Callable Wrapper or RCW, and this will be used by New-Object. Since the behavior of the RCW may be different from the behavior of the normal COM object, New-Object has a Strict parameter to warn you about RCW access. If you specify the Strict parameter and then create a COM object that uses an RCW, you get a warning message:

Although the object is still created, you are warned that it is not a standard COM object.

Глава 3. Обнаружение объектов, свойств и методов Chapter 3 — Discovering objects, properties, and methods

Мое знакомство с компьютерами началось с Commodore 64, но первым современным компьютером был клон IBM на базе 286, с частотой 12 МГц, 1 МБ памяти, жестким диском объемом 40 МБ, одним дисководом 5,25 дюйма, монитором CGA и ОС Microsoft DOS 3.3. My first introduction to computers was a Commodore 64, but my first modern computer was a 286 12-Mhz IBM clone with 1 megabyte of memory, a 40-megabyte hard drive, and one 5-1/4 inch floppy disk drive with a CGA monitor running Microsoft DOS 3.3.

Многие ИТ-специалисты, да и я тоже, не понаслышке знают о командной строке, но, когда дело касается объектов, свойств и методов, они впадают в ступор и говорят: «Я не разработчик». Many IT Pros, like myself, are no stranger to the command line, but when the subject of objects, properties, and methods comes up, they get the deer in the headlights look and say, «I’m not a developer.» И знаете что? Guess what? Для работы с PowerShell совершенно не обязательно быть разработчиком. You don’t have to be a developer to be successful with PowerShell. Не углубляйтесь в терминологию. Don’t get bogged down in the terminology. Сначала что-то может показаться непонятным и бессмысленным, но, когда вы немного попрактикуетесь, наступит миг озарения. Not everything may make sense initially, but after a little hands-on experience you’ll start to have those «light bulb» moments. «Ну, конечно! «Aha! Так вот о чем шла речь в книге!» So that’s what the book was talking about.»

Обязательно попробуйте выполнить примеры на своем компьютере, чтобы получить некий практический опыт. Be sure to try the examples on your computer to gain some of that hands-on experience.

Требования Requirements

В некоторых примерах, приведенных в этой главе, требуется модуль Active Directory PowerShell. The Active Directory PowerShell module is required by some of the examples shown in this chapter. Модуль входит в состав средств удаленного администрирования сервера (RSAT) для Windows. The module is part of the Remote Server Administration Tools (RSAT) for Windows. В сборке Windows 1809 (или более поздней версии) средства RSAT установлены в качестве компонента Windows. For the 1809 (or higher) build of Windows, the RSAT tools are installed as a Windows feature.

  • Сведения об установке средств RSAT см. в разделе Модули управления Windows. For information about installing the RSAT tools, see Windows Management modules.
  • При работе с более ранними версиями Windows см. статью RSAT для Windows. For older versions of Windows, see RSAT for Windows.

Get-Member Get-Member

Get-Member помогает определить доступные для команд объекты, свойства и методы. Get-Member helps you discover what objects, properties, and methods are available for commands. Все команды, создающие объектно-ориентированные выходные данные, могут быть переданы в Get-Member . Any command that produces object-based output can be piped to Get-Member . Свойство — это характеристика элемента. A property is a characteristic about an item. У водительского удостоверения есть свойство, называемое цветом глаз, а самыми распространенными значениями для этого свойства являются цвета: синий и карий. Your drivers license has a property called eye color and the most common values for that property are blue and brown. Метод — это действие, которое может быть выполнено с элементом. A method is an action that can be taken on an item. В примере с водительским удостоверением одним из методов является «Лишить», так как управление автомобильного транспорта может лишить вас удостоверения. In staying with the drivers license example, one of the methods is «Revoke» because the department of motor vehicles can revoke your drivers license.

Свойства Properties

В следующем примере будут получены сведения о службе времени Windows, работающей на компьютере. In the following example, I’ll retrieve information about the Windows Time service running on my computer.

Status, Name и DisplayName — это примеры свойств, как показано в предыдущем наборе результатов. Status, Name, and DisplayName are examples of properties as shown in the previous set of results. Свойство Status имеет значение Running , свойство Name имеет значение w32time , а свойство DisplayName имеет значение Windows Time . The value for the Status property is Running , the value for the Name property is w32time , and the value for DisplayName is Windows Time .

Читайте также:  Изменение метрики маршрута windows

Теперь эта же команда будет передана в Get-Member . Now I’ll pipe that same command to Get-Member :

В первой строке результатов в предыдущем примере содержится часть очень важных сведений. The first line of the results in the previous example contains one piece of very important information. TypeName сообщает, какой тип объекта был возвращен. TypeName tells you what type of object was returned. В этом примере был возвращен объект System.ServiceProcess.ServiceController. In this example, a System.ServiceProcess.ServiceController object was returned. Он часто сокращается до части свойства TypeName, идущей сразу после последней точки. В этом примере — ServiceController. This is often abbreviated as the portion of the TypeName just after the last period; ServiceController in this example.

После того как будет известен тип объекта, создаваемый командой, эти сведения можно использовать для поиска команд, которые принимают этот тип объекта в качестве входных данных. Once you know what type of object a command produces, you can use this information to find commands that accept that type of object as input.

У всех этих команд есть параметр, принимающий тип объекта ServiceController по конвейеру, входным данным параметра или обоим условиям. All of those commands have a parameter that accepts a ServiceController object type by pipeline, parameter input, or both.

Обратите внимание, что доступны и дополнительные свойства, а не только те, которые отображаются по умолчанию. Notice that there are more properties than are displayed by default. Хотя эти дополнительные свойства не отображаются по умолчанию, их можно выбрать из конвейера путем передачи команды в командлет Select-Object и использования параметра Property. Although these additional properties aren’t displayed by default, they can be selected from the pipeline by piping the command to the Select-Object cmdlet and using the Property parameter. В следующем примере все свойства выбираются путем передачи результатов Get-Service в Select-Object и указания подстановочного знака * в качестве значения параметра Property. The following example selects all of the properties by piping the results of Get-Service to Select-Object and specifying the * wildcard character as the value for the Property parameter.

Можно также выбрать конкретные свойства, указав список с разделителями-запятыми в качестве значения параметра Property. Specific properties can also be selected using a comma-separated list for the value of the Property parameter.

По умолчанию четыре свойства возвращаются в таблице, а пять или более — в списке. By default, four properties are returned in a table and five or more are returned in a list. Для переопределения количества свойств, отображаемых по умолчанию в таблице, некоторые команды используют пользовательское форматирование. Some commands use custom formatting to override how many properties are displayed by default in a table. Существует несколько командлетов Format-* , которые можно использовать для переопределения этих значений по умолчанию вручную. There are several Format-* cmdlets that can be used to manually override these defaults. Самыми распространенными являются Format-Table и Format-List . Они будут рассматриваться в следующей главе. The most common ones are Format-Table and Format-List , both of which will be covered in an upcoming chapter.

При указании имен свойств с помощью Select-Object можно использовать подстановочные знаки. Wildcard characters can be used when specifying the property names with Select-Object .

В предыдущем примере параметру Property было задано значение Can* для возврата всех свойств, начинающихся с Can . In the previous example, Can* was used as one of the values for the Property parameter to return all the properties that start with Can . К ним относятся CanPauseAndContinue, CanShutdown и CanStop. These include CanPauseAndContinue, CanShutdown, and CanStop.

Методы Methods

Метод — это действие, которое может быть выполнено. Methods are an action that can be taken. Параметр MemberType позволяет сузить результаты Get-Member так, чтобы отображались только методы для Get-Service . Use the MemberType parameter to narrow down the results of Get-Member to only show the methods for Get-Service .

Как видите, методов довольно много. As you can see, there are many methods. Метод Stop можно использовать для остановки службы Windows. The Stop method can be used to stop a Windows service.

Теперь убедитесь, что служба времени Windows действительно остановлена. Now to verify the Windows time service has indeed been stopped.

Я сам редко использую методы, но о них нужно знать. I rarely find myself using methods, but they’re something you need to be aware of. Может возникнуть ситуация, когда вам встретится команда Get-* , не имеющая соответствующей команды для изменения этого элемента. There are times that you’ll come across a Get-* command without a corresponding command to modify that item. Зачастую выполнить действие для изменения элемента можно с помощью метода. Often, a method can be used to perform an action that modifies it. Хорошим примером является командлет Get-SqlAgentJob в модуле PowerShell для SqlServer. The Get-SqlAgentJob cmdlet in the SqlServer PowerShell module is a good example of this. Модуль устанавливается в составе SQL Server Management Studio (SSMS). The module installs as part of SQL Server Management Studio (SMSS). Соответствующий командлет Set-* отсутствует, но для выполнения той же задачи можно использовать метод. No corresponding Set-* cmdlet exists, but a method can be used to complete the same task.

Еще одна причина, по которой следует знать о методах, заключается в том, что многие новички считают, что команды Get-* не способны вызывать разрушительные изменения. Another reason to be aware of methods is that many beginners assume destructive changes can’t be made with Get-* commands. Однако при неправильном применении эти команды на самом деле могут приводить к серьезным проблемам. But they indeed can cause serious problems if used inappropriately.

Оптимальным вариантом для выполнения действия будет использование командлета (если таковой существует). A better option is to use a cmdlet to perform the action if one exists. Запустите службу времени Windows, на этот раз с помощью командлета для запуска служб. Go ahead and start the Windows Time service, except this time use the cmdlet for starting services.

По умолчанию Start-Service не возвращает никаких результатов, как и метод запуска Get-Service . By default, Start-Service doesn’t return any results just like the start method of Get-Service . Но одно из преимуществ использования командлета в том, что он несколько раз предлагает дополнительные функции, недоступные в методе. But one of the benefits of using a cmdlet is that many times the cmdlet offers additional functionality that isn’t available with a method. В предыдущем примере использовался параметр PassThru. In the previous example, the PassThru parameter was used. В результате командлет, который обычно не создает выходные данные, генерирует их. This causes a cmdlet that doesn’t normally produce output, to produce output.

Будьте внимательны, делая предположения о выходных данных командлета. Be careful with assumptions about the output of a cmdlet. Мы все знаем, что происходит, когда что-то предполагается. We all know what happens when you assume things. Я получу информацию о процессе PowerShell, выполняемом на компьютере Windows 10 с лабораторной средой. I’ll retrieve information about the PowerShell process running on my Windows 10 lab environment computer.

Читайте также:  Операционные системы семейства windows лекция

Теперь эта же команда будет передана в Get-Member. Now I’ll pipe that same command to Get-Member:

Обратите внимание, что доступны дополнительные свойства, а не только те, которые отображаются по умолчанию. Notice that there are more properties listed than are displayed by default. Некоторые отображаемые свойства по умолчанию не отображаются как свойства при просмотре результатов Get-Member . A number of the default properties displayed don’t show up as properties when viewing the results of Get-Member . Это связано с тем, что многие из показанных значений, такие как NPM(K) , PM(K) , WS(K) и CPU(s) , являются вычисляемыми свойствами. This is because many of the displayed values, such as NPM(K) , PM(K) , WS(K) , and CPU(s) , are calculated properties. Чтобы определить фактические имена свойств, необходимо передать команду в Get-Member . To determine the actual property names, the command must be piped to Get-Member .

Если команда не создает выходные данные, она не может быть передана в Get-Member . If a command does not produce output, it can’t be piped to Get-Member . Так как команда Start-Service по умолчанию не выводит никаких выходных данных, при попытке передать ее в Get-Member возникает ошибка. Since Start-Service doesn’t produce any output by default, it generates an error when you try to pipe it to Get-Member .

Параметр PassThru можно указать с помощью командлета Start-Service , чтобы создать выходные данные, которые затем передаются в Get-Member без ошибок. The PassThru parameter can be specified with the Start-Service cmdlet make it produce output, which is then piped to Get-Member without error.

Для передачи в Get-Member команда должна создавать выходные данные на основе объекта. To be piped to Get-Member , a command must produce object-based output.

Out-Host выполняет запись непосредственно на узел PowerShell, но не создает для конвейера выходные данные на основе объекта. Out-Host writes directly to the PowerShell host, but it doesn’t produce object-based output for the pipeline. Поэтому ее нельзя передать в Get-Member . So it can’t be piped to Get-Member .

Active Directory Active Directory

Для выполнения действий в этом разделе необходимы средства удаленного администрирования сервера, приведенные в разделе требований этой главы. The Remote Server Administration Tools listed in the requirements section of this chapter are required to complete this section. Кроме того, как отмечалось во введении к этой книге, компьютер Windows 10 с лабораторной средой должен входить в домен лабораторной среды. Also, as mentioned in the introduction to this book, your Windows 10 lab environment computer must be a member of the lab environment domain.

Используйте Get-Command с параметром Module, чтобы определить, какие команды были добавлены в состав модуля PowerShell для ActiveDirectory при установке средств удаленного администрирования сервера. Use Get-Command with the Module parameter to determine what commands were added as part of the ActiveDirectory PowerShell module when the remote server administration tools were installed.

В модуль PowerShell для ActiveDirectory было добавлено всего 147 команд. A total of 147 commands were added as part of the ActiveDirectory PowerShell module. Некоторые команды по умолчанию возвращают только часть доступных свойств. Some commands of these commands only return a portion of the available properties by default.

Вы заметили что-то необычное в именах команд в этом модуле? Did you notice anything different about the names of the commands in this module? В именной части команд есть префикс AD. The noun portion of the commands has an AD prefix. Это распространенное явление для команд в большинстве модулей. This is common to see on the commands of most modules. Префикс предназначен для предотвращения конфликтов имен. The prefix is designed to help prevent naming conflicts.

Даже если вы лишь смутно знакомы с Active Directory, вам, вероятно, известно, что учетная запись пользователя имеет больше свойств, чем показано в этом примере. Even if you’re only vaguely familiar with Active Directory, you’re probably aware that a user account has more properties than are shown in this example.

У командлета Get-ADUser есть параметр Properties, который используется для указания дополнительных возвращаемых свойств (не заданных по умолчанию). The Get-ADUser cmdlet has a Properties parameter that is used to specify the additional (non-default) properties you want to return. Если указать подстановочный знак * , будут возвращены все свойства. Specifying the * wildcard character returns all of them.

Теперь это выглядит примерно так. Now that looks more like it.

Можете ли вы представить себе причину, по которой свойства учетной записи пользователя Active Directory будут настолько ограничены по умолчанию? Can you think of a reason why the properties of an Active Directory user account would be so limited by default? Представьте, что возвращены все свойства для каждой учетной записи пользователя в производственной среде Active Directory. Imagine if you returned every property for every user account in your production Active Directory environment. Подумайте о снижении производительности не только самих контроллеров домена, но и сети. Think of the performance degradation that you could cause, not only to the domain controllers themselves, but also to your network. Маловероятно, что вам потребуются все свойства. It’s doubtful that you’ll actually need every property anyway. Возврат всех свойств для одной учетной записи пользователя вполне допустим, когда вы пытаетесь определить, какие свойства существуют. Returning all of the properties for a single user account is perfectly acceptable when you’re trying to determine what properties exist.

Нередко при создании прототипов команды запускаются несколько раз. It’s not uncommon to run a command many times when prototyping it. Если вам нужно выполнить огромный запрос, сделайте это один раз и сохраните результаты в переменную. If you’re going to perform some huge query, query it once and store the results in a variable. Затем вы сможете работать с содержимым переменной, а не запускать ресурсоемкий запрос многократно. Then work with the contents of the variable instead of repeatedly using some expensive query.

Используйте содержимое переменной $Users , а не выполняйте предыдущую команду несколько раз. Use the contents of the $Users variable instead of running the previous command numerous times. Помните, что содержимое переменной не обновляется при внесении изменений для этого пользователя в Active Directory. Keep in mind that the contents of the variable aren’t updated when changes are made to that user in Active Directory.

Чтобы определить доступные свойства, переменную $Users можно передать в Get-Member . You could pipe the $Users variable to Get-Member to discover the available properties.

Затем выберите отдельные свойства, передав $Users в Select-Object . При этом запрос в Active Directory отправляется не более одного раза. Then select the individual properties by piping $Users to Select-Object , all without ever having to query Active Directory more than one time.

Чтобы запросить Active Directory несколько раз, воспользуйтесь параметром Properties для указания необходимых свойств, не являющихся заданными по умолчанию. If you are going to query Active Directory more than once, use the Properties parameter to specify any non-default properties you want.

Сводка Summary

В этой главе вы узнали, как определить тип объекта, выводимый командой, как определить доступные для команды свойства и методы, а также то, как работать с командами, которые ограничивают свойства, возвращаемые по умолчанию. In this chapter, you’ve learned how to determine what type of object a command produces, how to determine what properties and methods are available for a command, and how to work with commands that limit the properties that are returned by default.

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