2

Running the following sqlcmd in PowerShell:

$unassignedCnt = sqlcmd -W -k 1 -S MSSQLSERVER -E -Q "SET NoCount ON; SELECT   Count(DISTINCT SP.SubnetKey) AS 'UnassignedCount' FROM [Control].[dbo].[Subnet] AS SP Left OUTER JOIN [Control].[rw_current].[QIP_Subnet] AS Q ON SP.KeyHash = Q.__key_Hash; SET NoCount OFF; "
Write-Host $unassignedCnt

This returns the following formatted result:

UnassignedCount --------------- 1

I would like to have only:

1

Can I achieve this through the SQL command or do I need to post process the result? If so what's the simplest approach?

7
  • 1
    Write-Host $unassignedCnt -> Write-Host $unassignedCnt.UnassignedCount Commented Aug 3, 2017 at 9:25
  • @AnsgarWiechers - That returns null Commented Aug 3, 2017 at 9:28
  • Unlikely. What is the output of $unassignedCnt.GetType().FullName? Commented Aug 3, 2017 at 9:34
  • @AnsgarWiechers - System.Object[] Commented Aug 3, 2017 at 9:35
  • $unassignedCnt -> $unassignedCnt[0].UnassignedCount. Adjust the index if the first item is not the one you want. Commented Aug 3, 2017 at 9:36

1 Answer 1

2

You can do this using by changing your SQL query to use PRINT instead of SELECT

SELECT will create a table which has header and data associated with it. PRINT simply outputs the results.

$unassignedCnt = sqlcmd -W -k 1 -S MSSQLSERVER -E -Q "SET NoCount ON; DECLARE @result varchar(max); SELECT  @result= Count(DISTINCT SP.SubnetKey) FROM [Control].[dbo].[Subnet] AS SP Left OUTER JOIN [Control].[rw_current].[QIP_Subnet] AS Q ON SP.KeyHash = Q.__key_Hash; PRINT @result ;SET NoCount OFF; "
Write-Host $unassignedCnt
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.