简体   繁体   中英

PowerShell: `New-Object` `-ArgumentList` vs calling constructor vs type casting

I'm just starting to learn some basics of PowerShell and can't get my head around New-Object and type casting. For example this:

# all of these yield the same
New-Object System.Net.Sockets.TcpListener -ArgumentList 5000
New-Object System.Net.Sockets.TcpListener(5000)
[System.Net.Sockets.TcpListener]500  # this works

# all of these yield the same
New-Object -TypeName System.Net.Sockets.TCPClient -ArgumentList "8.8.8.8", 53
New-Object System.Net.Sockets.TCPClient("8.8.8.8", 53)
[System.Net.Sockets.TCPClient]::New("8.8.8.8", 53)
# but this doesn't work
# [System.Net.Sockets.TCPClient]("8.8.8.8", 53) # does not work
  • What is the difference between using -ArgumentList and using (arg1,...) ? Is it that the name of the type and the (arg1,...) are interpreted as two different arguments to New-Object even when there is no space between them, and so the (arg1,...) is assigned as the value of -ArgumentList ?
  • Why doesn't casting work for the second example of System.Net.Sockets.TCPClient ? The only difference I see is that it takes multiple arguments, whereas System.Net.Sockets.TcpListener takes a single argument. But why can PowerShell cast an integer to a System.Net.Sockets.TcpListener but not an array to a System.Net.Sockets.TCPClient by calling its constructor? Ie why aren't these two equivalent:
    • [System.Net.Sockets.TCPClient]::New("8.8.8.8", 53) # works
    • [System.Net.Sockets.TCPClient]("8.8.8.8", 53) # does not work

What is the difference between using -ArgumentList and using (arg1, ...) ?

  • Do not use (arg1,...) it is pseudo method syntax that only happens to work - see the bottom section of this answer .

  • Instead, use arg1, ... - no parentheses, whitespace before the list; that is the positionally implied equivalent of -ArgumentList arg1, ... (or -Args arg1, ... )

Why doesn't casting work for the second example of System.Net.Sockets.TCPClient ?

Casting only works in two variants:

  • With a scalar that matches a single-argument constructor or, in the case of a string , if the target type has a static .Parse() method.

  • With a hash table ( @{ ... } ) whose entries' keys match properties of the target type and assuming that the target type has a parameterless public constructor.

Therefore you cannot cast from an array of values.

See this answer for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM