- New-Object
- Syntax
- Description
- Examples
- Example 1: Create a System.Version object
- Example 2: Create an Internet Explorer COM object
- Example 3: Use the Strict parameter to generate a non-terminating error
- Example 4: Create a COM object to manage Windows desktop
- Example 5: Pass multiple arguments to a constructor
- Example 6: Calling a constructor that takes an array as a single parameter
- Parameters
- Inputs
- Outputs
- Клёвый код
- Решаем задачи Абрамян на C. Matrix78
- Решаем задачи Абрамян на C. Matrix77
- Решаем задачи Абрамян на C. Matrix76
- Решаем задачи Абрамян на C. Matrix75
- Решаем задачи Абрамян на C. Matrix74
- Решаем задачи Абрамян на C. Matrix73
- Решаем задачи Абрамян на C. Matrix72
- Решаем задачи Абрамян на C. Matrix71
- Решаем задачи Абрамян на C. Matrix70
- Решаем задачи Абрамян на C. Matrix69
- Создание объектов .NET и COM (New-Object) Creating .NET and COM Objects (New-Object)
- Использование командлета New-Object для доступа к журналу событий Using New-Object for Event Log Access
- Использование конструкторов с командлетом New-Object Using Constructors with New-Object
- Сохранение объектов в переменных Storing Objects in Variables
- Доступ к удаленному журналу событий с помощью New-Object Accessing a Remote Event Log with New-Object
- Очистка журнала событий методами объектов Clearing an Event Log with Object Methods
- Создание COM-объектов с помощью New-Object Creating COM Objects with New-Object
- Создание ярлыков на рабочем столе с помощью WScript.Shell Creating a Desktop Shortcut with WScript.Shell
- Использование Internet Explorer из Windows PowerShell Using Internet Explorer from Windows PowerShell
- Получение предупреждений о вызываемых COM-объектах .NET Framework Getting Warnings About .NET Framework-Wrapped COM Objects
New-Object
Creates an instance of a Microsoft .NET Framework or COM object.
Syntax
Description
The New-Object cmdlet creates an instance of a .NET Framework or COM object.
You can specify either the type of a .NET Framework class or a ProgID of a COM object. By default, you type the fully qualified name of a .NET Framework class and the cmdlet returns a reference to an instance of that class. To create an instance of a COM object, use the ComObject parameter and specify the ProgID of the object as its value.
Examples
Example 1: Create a System.Version object
This example creates a System.Version object using the «1.2.3.4» string as the constructor.
Example 2: Create an Internet Explorer COM object
This example creates two instances of the COM object that represents the Internet Explorer application. The first instance uses the Property parameter hash table to call the Navigate2 method and set the Visible property of the object to $True to make the application visible. The second instance gets the same results with individual commands.
Example 3: Use the Strict parameter to generate a non-terminating error
This example demonstrates that adding the Strict parameter causes the New-Object cmdlet to generate a non-terminating error when the COM object uses an interop assembly.
Example 4: Create a COM object to manage Windows desktop
This example shows how to create and use a COM object to manage your Windows desktop.
The first command uses the ComObject parameter of the New-Object cmdlet to create a COM object with the Shell.Application ProgID. It stores the resulting object in the $ObjShell variable. The second command pipes the $ObjShell variable to the Get-Member cmdlet, which displays the properties and methods of the COM object. Among the methods is the ToggleDesktop method. The third command calls the ToggleDesktop method of the object to minimize the open windows on your desktop.
Example 5: Pass multiple arguments to a constructor
This example shows how to create an object with a constructor that takes multiple parameters. The parameters must be put in an array when using ArgumentList parameter.
PowerShell binds each member of the array to a parameter of the constructor.
This example uses parameter splatting for readability. For more information, see about_Splatting.
Example 6: Calling a constructor that takes an array as a single parameter
This example shows how to create an object with a constructor that takes a parameter that is an array or collection. The array parameter must be put in wrapped inside another array.
The first attempt to create the object in this example fails. PowerShell attempted to bind the three members of $array to parameters of the constructor but the constructor does not take three parameter. Wrapping $array in another array prevents PowerShell from attempting to bind the three members of $array to parameters of the constructor.
Parameters
Specifies an array of arguments to pass to the constructor of the .NET Framework class. If the constructor takes a single parameter that is an array, you must wrap that parameter inside another array. For example:
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate -ArgumentList (,$bytes)
For more information about the behavior of ArgumentList, see about_Splatting.
The alias for ArgumentList is Args.
Type: | Object [ ] |
Aliases: | Args |
Position: | 1 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the programmatic identifier (ProgID) of the COM object.
Type: | String |
Position: | 0 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Sets property values and invokes methods of the new object.
Enter a hash table in which the keys are the names of properties or methods and the values are property values or method arguments. New-Object creates the object and sets each property value and invokes each method in the order that they appear in the hash table.
If the new object is derived from the PSObject class, and you specify a property that does not exist on the object, New-Object adds the specified property to the object as a NoteProperty. If the object is not a PSObject, the command generates a non-terminating error.
Type: | IDictionary |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates that the cmdlet generates a non-terminating error when a COM object that you attempt to create uses an interop assembly. This feature distinguishes actual COM objects from .NET Framework objects with COM-callable wrappers.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the fully qualified name of the .NET Framework class. You cannot specify both the TypeName parameter and the ComObject parameter.
Type: | String |
Position: | 0 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
None
You cannot pipe input to this cmdlet.
Outputs
Object
New-Object returns the object that is created.
Клёвый код
Скриптописание и кодинг
Решаем задачи Абрамян на C. Matrix78
Matrix78. Дана матрица размера $$M \times N$$. Упорядочить ее строки так, чтобы их минимальные элементы образовывали убывающую последовательность.
Решаем задачи Абрамян на C. Matrix77
Matrix77. Дана матрица размера $$M \times N$$. Упорядочить ее столбцы так, чтобы их последние элементы образовывали убывающую последовательность.
Решаем задачи Абрамян на C. Matrix76
Matrix76. Дана матрица размера $$M \times N$$. Упорядочить ее строки так, чтобы их первые элементы образовывали возрастающую последовательность.
Решаем задачи Абрамян на C. Matrix75
Matrix75. Дана матрица размера $$M \times N$$. Элемент матрицы называется ее локальным максимумом, если он больше всех окружающих его элементов. Поменять знак всех локальных максимумов данной матрицы на противоположный. При решении допускается использовать вспомогательную матрицу.
Решаем задачи Абрамян на C. Matrix74
Matrix74. Дана матрица размера $$M \times N$$. Элемент матрицы называется ее локальным минимумом, если он меньше всех окружающих его элементов. Заменить все локальные минимумы данной матрицы на нули. При решении допускается использовать вспомогательную матрицу.
Решаем задачи Абрамян на C. Matrix73
Matrix73. Дана матрица размера $$M \times N$$. После последнего столбца, содержащего только отрицательные элементы, вставить столбец из нулей. Если требуемых столбцов нет, то вывести матрицу без изменений.
Решаем задачи Абрамян на C. Matrix72
Matrix72. Дана матрица размера $$M \times N$$. Перед первым столбцом, содержащим только положительные элементы, вставить столбец из единиц. Если требуемых столбцов нет, то вывести матрицу без изменений.
Решаем задачи Абрамян на C. Matrix71
Matrix71. Дана матрица размера $$M \times N$$. Продублировать столбец матрицы, содержащий ее минимальный элемент.
Решаем задачи Абрамян на C. Matrix70
Matrix70. Дана матрица размера $$M \times N$$. Продублировать строку матрицы, содержащую ее максимальный элемент.
Решаем задачи Абрамян на C. Matrix69
Matrix69. Дана матрица размера $$M \times N$$ и целое число $$K$$ $$(1 \le K \le $$N$$)$$. После столбца матрицы с номером $$K$$ вставить столбец из единиц.
Создание объектов .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.