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
-ArgumentListand using(arg1,...)? Is it that the name of the type and the(arg1,...)are interpreted as two different arguments toNew-Objecteven 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, whereasSystem.Net.Sockets.TcpListenertakes a single argument. But why can PowerShell cast an integer to aSystem.Net.Sockets.TcpListenerbut not an array to aSystem.Net.Sockets.TCPClientby calling its constructor? I.e. 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