Com object explorer windows

InternetExplorer object

Controls an instance of Windows Internet Explorer through automation.

Members

The InternetExplorer object has these types of members:

Events

The InternetExplorer object has these events.

Fires before navigation occurs in the given object (on either a window or frameset element).

Fires when the enabled state of a command changes.

Fires when a document is completely loaded and initialized.

Fires when a navigation operation begins.

Fires when a navigation operation finishes, is halted, or fails.

Fires after a navigation to a link is completed on either a window element or a frameSet element.

Fires after a navigation to a link is completed on a window element or a frameSet element.

Creates a new process to handle the navigation.

Fires when a new window is to be created.

Fires when a new window is to be created.

Raised when a new window is to be created. Extends NewWindow2 with additional information about the new window.

Fires when the FullScreen property is changed.

Fires when the MenuBar property is changed.

Fires before the Internet Explorer application quits.

Fires when the StatusBar property is changed.

Fires when the TheaterMode property is changed.

Fires when the ToolBar property is changed.

Fires when the Visible property of the object is changed.

Fires when a print template is instantiated.

Fires when a print template is destroyed.

Fires when the progress of a download operation is updated on the object.

Fires when the PutProperty method of the object changes the value of a property.

Fires when the status bar text of the object has changed.

Fires when the title of a document in the object becomes available or changes.

Fires when the visibility state of a content window, such as the browser window or a tab, changes.

Methods

The InternetExplorer object has these methods.

Event Description
BeforeNavigate

Executes a command and returns the status of the command execution using the IOleCommandTarget interface.

Gets the value associated with a user-defined property name.

Navigates backward one item in the history list.

Navigates forward one item in the history list.

Navigates to the current home or start page.

Navigates to the current search page.

Navigates to a resource identified by a URL or to a file identified by a full path.

Navigates the browser to a location that might not be expressed as a URL, such as a PIDL for an entity in the Windows Shell namespace.

Associates a user-defined name/value pair with the object.

Queries the object for the status of commands using the IOleCommandTarget interface.

Reloads the file that is currently displayed in the object.

Reloads the file that is currently displayed with the specified refresh level.

Cancels a pending navigation or download, and stops dynamic page elements, such as background sounds and animations.

Properties

The InternetExplorer object has these properties.

Method Description
ExecWB

Sets or gets a value indicating whether the address bar of the object is visible or hidden.

Gets the automation object for the application that is hosting the WebBrowser Control.

Gets a value that indicates whether the object is engaged in a navigation or downloading operation.

Gets an object reference to a container.

Gets the automation object of the active document, if any.

Retrieves the fully qualified path of the Internet Explorer executable.

Sets or gets a value that indicates whether Internet Explorer is in full-screen mode or normal window mode.

Sets or gets the height of the object.

Sets or gets the coordinate of the left edge of the object.

Retrieves the path or title of the resource that is currently displayed.

Gets the URL of the resource that is currently displayed.

Sets or gets a value that indicates whether the Internet Explorer menu bar is visible.

Sets or gets a value that indicates whether the object is operating in offline mode.

Gets the parent of the object.

Retrieves the system folder of the Internet Explorer executable.

Gets the ready state of the object.

Sets or gets a value that indicates whether the object is registered as a top-level browser window.

Sets or gets a value that indicates whether the object is registered as a drop target for navigation.

Sets or gets a value that indicates whether the object can be resized.

Sets or gets a value that indicates whether the object can display dialog boxes.

Sets or gets a value that indicates whether the status bar for the object is visible.

Sets or gets whether the object is in theater mode.

Sets or gets whether toolbars for the object are visible.

Sets or gets the coordinate of the top edge of the object.

Gets a value that indicates whether the object is a top-level container.

Gets the user type name of the contained document object.

Sets or gets a value that indicates whether the object is visible or hidden.

Sets or gets the width of the object.

Remarks

Windows Internet ExplorerВ 8. On WindowsВ Vista, to create an instance of Internet Explorer running at a medium integrity level, pass CLSID_InternetExplorerMedium (defined in exdisp.idl) to CoCreateInstance. The resulting InternetExplorerMedium object supports the same events, methods, and properties as the InternetExplorer object.

Examples

The following example uses CreateObject in Visual Basic to launch an instance of Internet Explorer.

The following C# example launches an instance of Internet Explorer and navigates to a Web page. The code also demonstrates how to create an event handler to listen for the BeforeNavigate2 event. The project requires a reference to the Microsoft Internet Controls (SHDocVw) type library.

Создание объектов .NET и COM (New-Object) Creating .NET and COM Objects (New-Object)

Существуют программные компоненты с интерфейсами платформы .NET Framework и COM, которые позволяют выполнять множество задач системного администрирования. There are software components with .NET Framework and COM interfaces that enable you to perform many system administration tasks. Windows PowerShell позволяет использовать эти компоненты, поэтому доступные задачи не ограничиваются только применением командлетов. Windows PowerShell lets you use these components, so you are not limited to the tasks that can be performed by using cmdlets. Множество командлетов в первом выпуске Windows PowerShell не работают с удаленными компьютерами. Many of the cmdlets in the initial release of Windows PowerShell do not work against remote computers. Мы покажем, как преодолеть это ограничение при управлении журналами событий с помощью класса System.Diagnostics.EventLog .NET Framework непосредственно из Windows PowerShell. 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.

Использование командлета New-Object для доступа к журналу событий Using New-Object for Event Log Access

Библиотека классов платформы .NET Framework включает класс System.Diagnostics.EventLog , позволяющий управлять журналами событий. The .NET Framework Class Library includes a class named System.Diagnostics.EventLog that can be used to manage event logs. Можно создать новый экземпляр класса .NET Framework с помощью командлета New-Object с параметром TypeName . 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:

Хотя команда и создала экземпляр класса EventLog, этот экземпляр не содержит данных. 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?

Использование конструкторов с командлетом New-Object Using Constructors with New-Object

Чтобы сослаться на определенный журнал событий, нужно указать его имя. To refer to a specific event log, you need to specify the name of the log. Командлет New-Object имеет параметр ArgumentList . 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. Например, чтобы получить ссылку на журнал приложений, нужно указать строку «Application» в качестве аргумента: For example, to get a reference to the Application log, you specify the string ‘Application’ as an argument:

Поскольку основные классы платформы .NET Framework содержатся в пространстве имен System, Windows PowerShell автоматически пытается найти в нем указанные классы, если не может найти совпадения для указанного имени типа. 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. Это значит, что можно указать класс Diagnostics.EventLog вместо класса System.Diagnostics.EventLog. 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. Хотя Windows PowerShell позволяет выполнять больше задач с помощью конвейеров, что снижает потребность в переменных, иногда сохранение ссылок на объекты в переменных помогает сделать работу с объектами более удобной. 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 позволяет создавать переменные, которые, по сути, являются именованными объектами. Windows PowerShell lets you create variables that are essentially named objects. Выходные данные любой допустимой команды Windows PowerShell можно сохранить в переменной. The output from any valid Windows PowerShell command can be stored in a variable. Имена переменных всегда начинаются со знака «$». Variable names always begin with $. Если нужно сохранить ссылку на журнал приложений в переменной с именем $AppLog, введите имя переменной, знак равенства и команду, используемую для создания объекта журнала приложений: 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:

Если после этого набрать $AppLog, будет выведено содержимое журнала приложения: If you then type $AppLog, you can see that it contains the Application log:

Доступ к удаленному журналу событий с помощью New-Object Accessing a Remote Event Log with New-Object

Команды, рассмотренные в предыдущем разделе, обращаются к локальному компьютеру. Для этого подходит и командлет Get-EventLog . The commands used in the preceding section target the local computer; the Get-EventLog cmdlet can do that. Чтобы получить доступ к журналу приложений на удаленном компьютере, необходимо в качестве аргументов ввести имя журнала и имя (или IP-адрес) компьютера. 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.

Какие действия могут быть выполнены с переменной $RemoteAppLog после сохранения в ней ссылки на журнал событий? 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. Командлет Get-Member позволяет вывести методы, связанные с объектом. You can use Get-Member to display the methods associated with an object. Следующая команда и выделенный фрагмент выходных данных показывают некоторые методы класса EventLog: The following command and selected output show some the methods of the EventLog class:

Метод Clear() позволяет очистить журнал событий. 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. Таким образом оболочка Windows PowerShell отличает метод от возможного свойства с таким же именем. This lets Windows PowerShell distinguish between the method and a potential property with the same name. Чтобы вызвать метод Clear , нужно ввести следующую команду: Type the following to call the Clear method:

Введите следующую строку, чтобы отобразить журнал: Type the following to display the log. Видно, что журнал событий очищен, и вместо 262 записей не содержит ни одной. You will see that the event log was cleared, and now has 0 entries instead of 262:

Создание COM-объектов с помощью New-Object Creating COM Objects with New-Object

Командлет New-Object может использоваться для работы с СОМ-компонентами. You can use New-Object to work with Component Object Model (COM) components. Спектр этих компонентов довольно обширен — от различных библиотек, поставляемых с сервером сценариев Windows (WSH), до приложений ActiveX, например Internet Explorer, установленных на большинстве систем. 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 создает СОМ-объекты с помощью вызываемых оболочек времени выполнения .NET Framework, поэтому для него действуют те же ограничения, что и для платформы .NET Framework во время вызова СОМ-объектов. 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. Чтобы создать СОМ-объект, необходимо задать параметр ComObject для программного идентификатора ProgId нужного класса СОМ-объекта. 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. Подробное обсуждение ограничений использования СОМ-объектов и определение доступных в системе программных идентификаторов выходит за рамки данного руководства пользователя, но с оболочкой Windows PowerShell может использоваться большинство хорошо известных объектов таких сред, как сервер сценариев Windows. 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.

Объекты сервера сценариев Windows можно создать, задав следующие программные идентификаторы: WScript.Shell , WScript.Network , Scripting.Dictionary и Scripting.FileSystemObject . 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:

Хотя функциональность этих классов в большой степени может быть реализована другими способами в Windows PowerShell, некоторые действия (например создание ярлыков) проще выполнить с помощью классов сервера сценариев Windows. 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.

Создание ярлыков на рабочем столе с помощью WScript.Shell Creating a Desktop Shortcut with WScript.Shell

Одной из функций, быстро выполняемых с помощью СОМ-объектов, является создание ярлыков. One task that can be performed quickly with a COM object is creating a shortcut. Допустим, на рабочем столе требуется создать ярлык для корневой папки Windows PowerShell. Suppose you want to create a shortcut on your desktop that links to the home folder for Windows PowerShell. Сначала необходимо создать ссылку на объект WScript.Shell , которая сохраняется в переменной $WshShell : You first need to create a reference to WScript.Shell , which we will store in a variable named $WshShell :

Командлет Get-Member работает и с СОМ-объектами, поэтому элементы объекта можно изучить, введя следующее: Get-Member works with COM objects, so you can explore the members of the object by typing:

У командлета Get-Member есть необязательный параметр InputObject , который можно использовать вместо передачи по конвейеру, чтобы предоставить входные данные для Get-Member . Get-Member has an optional InputObject parameter you can use instead of piping to provide input to Get-Member . При использовании команды Get-Member -InputObject $WshShell в примере выше выходные данные были бы такими же. You would get the same output as shown above if you instead used the command Get-Member -InputObject $WshShell . При указании параметра InputObject командлет обрабатывает свои аргументы как одно целое. If you use InputObject , it treats its argument as a single item. Это означает, что если в переменной содержится несколько объектов, командлет Get-Member обрабатывает их как массив объектов. This means that if you have several objects in a variable, Get-Member treats them as an array of objects. Пример: For example:

Метод WScript.Shell CreateShortcut допускает использование одного аргумента — пути к создаваемому файлу ярлыка. 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. Рабочий стол обычно представлен папкой с именем Desktop внутри домашней папки текущего пользователя. The desktop is normally represented by a folder named Desktop inside the home folder of the current user. В Windows PowerShell имеется переменная $Home , в которой содержится путь к этой домашней папке. Windows PowerShell has a variable $Home that contains the path to this folder. Таким образом, путь к домашней папке может быть задан указанием этой переменной, после чего нужно ввести только имя папки Desktop и имя создаваемого ярлыка: 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:

Если похожая на переменную строка заключена в двойные кавычки, Windows PowerShell пытается заменить ее подходящим значением. 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:

В переменной $lnk теперь хранится новая ссылка на ярлык. We now have a variable named $lnk that contains a new shortcut reference. Чтобы просмотреть элементы переменной, ее можно передать по конвейеру в Get-Member . 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:

Осталось определить свойство TargetPath , указывающее путь к папке Windows PowerShell, и вызвать метод Save , чтобы сохранить $lnk ярлыка. 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. Путь к папке Windows PowerShell хранится в переменной $PSHome , поэтому это можно сделать, введя следующее: The Windows PowerShell application folder path is stored in the variable $PSHome , so we can do this by typing:

Использование Internet Explorer из Windows PowerShell Using Internet Explorer from Windows PowerShell

С помощью СОМ-объектов можно автоматизировать многие приложения (включая семейство приложений Microsoft Office и Internet Explorer). Many applications (including the Microsoft Office family of applications and Internet Explorer) can be automated by using COM. На примере Internet Explorer можно рассмотреть некоторые типичные приемы и тонкости, связанные с работой приложений, основанных на СОМ-технологии. Internet Explorer illustrates some of the typical techniques and issues involved in working with COM-based applications.

Экземпляр Internet Explorer создается указанием программного идентификатора этого приложения InternetExplorer.Application : You create an Internet Explorer instance by specifying the Internet Explorer ProgId, InternetExplorer.Application :

Эта команда запускает Internet Explorer, но не отображает его. This command starts Internet Explorer, but does not make it visible. Если запустить командлет Get-Process, то можно увидеть выполняющийся процесс iexplore. If you type Get-Process, you can see that a process named iexplore is running. Причем после выхода из Windows PowerShell выполнение этого процесса будет продолжаться. In fact, if you exit Windows PowerShell, the process will continue to run. Чтобы завершить процесс iexplore, необходимо перезагрузить компьютер или воспользоваться средством наподобие диспетчера задач. You must reboot the computer or use a tool like Task Manager to end the iexplore process.

СОМ-объекты, запускаемые в виде отдельных процессов, обычно называются исполняемыми файлами ActiveX . При их запуске окно пользовательского интерфейса отображается не всегда. COM objects that start as separate processes, commonly called ActiveX executables , may or may not display a user interface window when they start up. Если окно создается, но не отображается, как в случае с приложением Internet Explorer, фокус обычно перемещается на рабочий стол Windows, и для взаимодействия с окном его необходимо сделать видимым. 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.

Введя $ie | Get-Member , можно получить список свойств и методов для Internet Explorer. By typing $ie | Get-Member , you can view properties and methods for Internet Explorer. Чтобы отобразить окно Internet Explorer, свойству Visible нужно присвоить значение $true, введя следующее: To see the Internet Explorer window, set the Visible property to $true by typing:

После этого можно перейти по какому-либо веб-адресу, используя метод Navigate: You can then navigate to a specific Web address by using the Navigate method:

Другие элементы объектной модели Internet Explorer позволяют получить текстовое содержание веб-страниц. Using other members of the Internet Explorer object model, it is possible to retrieve text content from the Web page. Следующая команда отображает HTML-текст в теле текущей веб-страницы: The following command will display the HTML text in the body of the current Web page:

Чтобы закрыть Internet Explorer из PowerShell, необходимо вызвать метод Quit(): To close Internet Explorer from within PowerShell, call its Quit() method:

Это приведет к принудительному закрытию приложения. This will force it to close. Переменная $ie больше не содержит действительную ссылку, хотя все еще отображается как СОМ-объект. 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:

В этой ситуации можно либо удалить оставшуюся ссылку с помощью команды $ie = $null, либо полностью удалить переменную: You can either remove the remaining reference with a command like $ie = $null, or completely remove the variable by typing:

Для исполняемых файлов ActiveX нет общего стандарта, по которому выполнение их процессов завершается или продолжается после удаления ссылки на них. There is no common standard for whether ActiveX executables exit or continue to run when you remove a reference to one. Выход из приложения зависит от обстоятельств (видимо ли приложение, открыт ли в нем какой-либо отредактированный документ, а также продолжается ли выполнение Windows PowerShell). 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. Поэтому требуется проверка поведения при завершении работы каждого исполняемого файла ActiveX, используемого в Windows PowerShell. For this reason, you should test termination behavior for each ActiveX executable you want to use in Windows PowerShell.

Получение предупреждений о вызываемых COM-объектах .NET Framework Getting Warnings About .NET Framework-Wrapped COM Objects

В некоторых случаях у СОМ-объекта есть соответствующая вызываемая оболочка времени выполнения (RCW) .NET Framework, и именно она используется командлетом New-Object . 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 . Поведение оболочки RCW может отличаться от поведения обычного СОМ-объекта, поэтому у командлета New-Object есть параметр Strict , используемый для предупреждения о доступе к RCW. 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. Если указать параметр Strict и создать СОМ-объект, использующий оболочку RCW, выводится предупреждение: 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.

Читайте также:  Windows hosts file cmd windows
Оцените статью
Property Description