Invoke-sqlcmd -ServerInstance “MyServer\MyInstance” -Query “select value_data from sys.dm_server_registry WHERE value_name = ‘TcpPort’” | GM
What do you get back? I ask because I’m not sure what Invoke-SqlCmd actually spits out. I’m GUESSING based on what you showed me that this would do it:
$tcpport = Invoke-sqlcmd -ServerInstance “MyServer\MyInstance” -Query “select value_data from sys.dm_server_registry WHERE value_name = ‘TcpPort’” | select -expand value_data
Your query is also going to return multiple rows based on the number of ipv4 and ipv6 addresses that are bound to the sqlserver so add the DISTINCT to your query as it is unlikely you are running on separate ports for each address. Then you wont return multiple objects in your variable.
select distinct value_data from sys.dm_server_registry
where value_name = ‘TcpPort’