New-Object
Crea un'istanza di un oggetto Microsoft .NET Framework o COM.
Sintassi
New-Object
[-TypeName] <String>
[[-ArgumentList] <Object[]>]
[-Property <IDictionary>]
[<CommonParameters>]
New-Object
[-ComObject] <String>
[-Strict]
[-Property <IDictionary>]
[<CommonParameters>]
Descrizione
Il cmdlet crea un'istanza New-Object
di un oggetto .NET Framework o COM.
È possibile specificare il tipo di una classe .NET Framework o un ProgID di un oggetto COM. Per impostazione predefinita, si digita il nome completo di una classe .NET Framework e il cmdlet restituisce un riferimento a un'istanza di tale classe. Per creare un'istanza di un oggetto COM, usare il parametro ComObject e specificare progID dell'oggetto come valore.
Esempio
Esempio 1: Create un oggetto System.Version
In questo esempio viene creato un oggetto System.Version usando la stringa "1.2.3.4" come costruttore.
New-Object -TypeName System.Version -ArgumentList "1.2.3.4"
Major Minor Build Revision
----- ----- ----- --------
1 2 3 4
Esempio 2: Create un oggetto COM di Internet Explorer
In questo esempio vengono create due istanze dell'oggetto COM che rappresenta l'applicazione Internet Explorer. La prima istanza usa la tabella hash del parametro Property per chiamare il metodo Navigate2 e impostare la proprietà Visible dell'oggetto per $True
rendere visibile l'applicazione.
La seconda istanza ottiene gli stessi risultati con i singoli comandi.
$IE1 = New-Object -COMObject InternetExplorer.Application -Property @{Navigate2="www.microsoft.com"; Visible = $True}
# The following command gets the same results as the example above.
$IE2 = New-Object -COMObject InternetExplorer.Application`
$IE2.Navigate2("www.microsoft.com")`
$IE2.Visible = $True`
Esempio 3: Usare il parametro Strict per generare un errore non terminante
In questo esempio viene illustrato che l'aggiunta del parametro Strict causa la generazione di un errore non terminante quando l'oggetto New-Object
COM usa un assembly di interoperabilità.
$A = New-Object -COMObject Word.Application -Strict -Property @{Visible = $True}
New-Object : The object written to the pipeline is an instance of the type
"Microsoft.Office.Interop.Word.ApplicationClass" from the component's primary interop assembly. If
this type exposes different members than the IDispatch members, scripts written to work with this
object might not work if the primary interop assembly is not installed.
At line:1 char:14
+ $A = New-Object <<<< -COM Word.Application -Strict; $a.visible=$true
Esempio 4: Create un oggetto COM per gestire desktop Windows
Questo esempio illustra come creare e usare un oggetto COM per gestire il desktop di Windows.
Il primo comando usa il parametro ComObject del New-Object
cmdlet per creare un oggetto COM con Shell.Application ProgID. Archivia l'oggetto risultante nella $ObjShell
variabile. Il secondo comando pipe la $ObjShell
variabile al Get-Member
cmdlet, che visualizza le proprietà e i metodi dell'oggetto COM. Tra i metodi è il metodo ToggleDesktop . Il terzo comando chiama il metodo ToggleDesktop dell'oggetto per ridurre a icona e aprire le finestre sul desktop.
$Objshell = New-Object -COMObject "Shell.Application"
$objshell | Get-Member
$objshell.ToggleDesktop()
TypeName: System.__ComObject#{866738b9-6cf2-4de8-8767-f794ebe74f4e}
Name MemberType Definition
---- ---------- ----------
AddToRecent Method void AddToRecent (Variant, string)
BrowseForFolder Method Folder BrowseForFolder (int, string, int, Variant)
CanStartStopService Method Variant CanStartStopService (string)
CascadeWindows Method void CascadeWindows ()
ControlPanelItem Method void ControlPanelItem (string)
EjectPC Method void EjectPC ()
Explore Method void Explore (Variant)
ExplorerPolicy Method Variant ExplorerPolicy (string)
FileRun Method void FileRun ()
FindComputer Method void FindComputer ()
FindFiles Method void FindFiles ()
FindPrinter Method void FindPrinter (string, string, string)
GetSetting Method bool GetSetting (int)
GetSystemInformation Method Variant GetSystemInformation (string)
Help Method void Help ()
IsRestricted Method int IsRestricted (string, string)
IsServiceRunning Method Variant IsServiceRunning (string)
MinimizeAll Method void MinimizeAll ()
NameSpace Method Folder NameSpace (Variant)
Open Method void Open (Variant)
RefreshMenu Method void RefreshMenu ()
ServiceStart Method Variant ServiceStart (string, Variant)
ServiceStop Method Variant ServiceStop (string, Variant)
SetTime Method void SetTime ()
ShellExecute Method void ShellExecute (string, Variant, Variant, Variant, Variant)
ShowBrowserBar Method Variant ShowBrowserBar (string, Variant)
ShutdownWindows Method void ShutdownWindows ()
Suspend Method void Suspend ()
TileHorizontally Method void TileHorizontally ()
TileVertically Method void TileVertically ()
ToggleDesktop Method void ToggleDesktop ()
TrayProperties Method void TrayProperties ()
UndoMinimizeALL Method void UndoMinimizeALL ()
Windows Method IDispatch Windows ()
WindowsSecurity Method void WindowsSecurity ()
WindowSwitcher Method void WindowSwitcher ()
Application Property IDispatch Application () {get}
Parent Property IDispatch Parent () {get}
Esempio 5: Passare più argomenti a un costruttore
In questo esempio viene illustrato come creare un oggetto con un costruttore che accetta più parametri. I parametri devono essere inseriti in una matrice quando si usa il parametro ArgumentList .
$array = @('One', 'Two', 'Three')
$parameters = @{
TypeName = 'System.Collections.Generic.HashSet[string]'
ArgumentList = ([string[]]$array, [System.StringComparer]::OrdinalIgnoreCase)
}
$set = New-Object @parameters
PowerShell associa ogni membro della matrice a un parametro del costruttore.
Nota
In questo esempio viene usato lo splatting dei parametri per la leggibilità. Per altre informazioni, vedere about_Splatting.
Esempio 6: Chiamata di un costruttore che accetta una matrice come singolo parametro
In questo esempio viene illustrato come creare un oggetto con un costruttore che accetta un parametro che è una matrice o un insieme. Il parametro della matrice deve essere inserito in wrapped all'interno di un'altra matrice.
$array = @('One', 'Two', 'Three')
# This command throws an exception.
$set = New-Object -TypeName 'System.Collections.Generic.HashSet[string]' -ArgumentList $array
# This command succeeds.
$set = New-Object -TypeName 'System.Collections.Generic.HashSet[string]' -ArgumentList (,[string[]]$array)
$set
New-Object : Cannot find an overload for "HashSet`1" and the argument count: "3".
At line:1 char:8
+ $set = New-Object -TypeName 'System.Collections.Generic.HashSet[strin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
One
Two
Three
Il primo tentativo di creare l'oggetto in questo esempio ha esito negativo. PowerShell ha tentato di associare i tre membri di $array
ai parametri del costruttore, ma il costruttore non accetta tre parametri. Il wrapping $array
in un'altra matrice impedisce a PowerShell di tentare di associare i tre membri di $array
ai parametri del costruttore.
Parametri
-ArgumentList
Specifica una matrice di argomenti da passare al costruttore della classe .NET Framework. Se il costruttore accetta un singolo parametro che è una matrice, è necessario eseguire il wrapping del parametro all'interno di un'altra matrice. Ad esempio:
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate -ArgumentList (,$bytes)
Per altre informazioni sul comportamento di ArgumentList, vedere about_Splatting.
L'alias per ArgumentList è Args.
Type: | Object[] |
Aliases: | Args |
Position: | 1 |
Default value: | None |
Required: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-ComObject
Specifica il ProgID dell'oggetto COM.
Type: | String |
Position: | 0 |
Default value: | None |
Required: | True |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-Property
Imposta i valori delle proprietà e richiama i metodi del nuovo oggetto.
Immettere una tabella hash in cui le chiavi corrispondono ai nomi delle proprietà o dei metodi e i valori corrispondono ai valori delle proprietà o agli argomenti dei metodi. New-Object
crea l'oggetto e imposta ogni valore della proprietà e richiama ogni metodo nell'ordine in cui vengono visualizzati nella tabella hash.
Se il nuovo oggetto è derivato dalla classe PSObject e si specifica una proprietà che non esiste nell'oggetto, New-Object
aggiunge la proprietà specificata all'oggetto come NotaProperty. Se l'oggetto non è un PSObject, il comando genera un errore non terminante.
Type: | IDictionary |
Position: | Named |
Default value: | None |
Required: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-Strict
Indica che il cmdlet genera un errore non terminante quando un oggetto COM che si tenta di creare usa un assembly di interoperabilità. Questa funzionalità distingue gli oggetti COM effettivi dagli oggetti .NET Framework con COM Callable Wrapper.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Required: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-TypeName
Specifica il nome completo della classe .NET Framework. Non è possibile specificare sia il parametro TypeName che il parametro ComObject .
Type: | String |
Position: | 0 |
Default value: | None |
Required: | True |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Input
None
Non è possibile eseguire la pipe degli oggetti a questo cmdlet.
Output
Questo cmdlet restituisce l'oggetto creato.
Note
New-Object
fornisce la funzionalità più comunemente usata della funzione CREATEObject VBScript. Un'istruzione comeSet objShell = CreateObject("Shell.Application")
in VBScript può essere tradotta$objShell = New-Object -COMObject "Shell.Application"
in PowerShell.New-Object
espande le funzionalità disponibili nell'ambiente Host script di Windows semplificando l'uso di oggetti .NET Framework dalla riga di comando e all'interno di script.