Returning an object from invoke-sqlcmd RRS feed

  • Question

  • Hi All.

    I would like to know if this is the correct way to return a result as an object.

    $server = "xxxxxxxxxxxxx"
    $username = "xxxxxxxxxxxxxxl"
    $pass= Get-Content "yyyyyyyyyyyyyyyyyyy"
    $password = ConvertTo-SecureString -String $pass -AsPlainText -Force
    $credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$password
    $session = new-pssession -ComputerName $server -credential $credential -authentication credssp -Name 'DB'
    $sb = {  $x = invoke-sqlcmd -Server DBServer -Database master -Query "select newid() as buildguid"
                       buildguid = $x | select buildguid
    invoke-command  -Session $session  -Scriptblock $sb
    Remove-PSSession $session 

    Sunday, June 9, 2019 9:40 AM

All replies

  • You are overcomplicating this:

    $sb = {invoke-sqlcmd -Query 'select newid()' -ServerInstance DBServer}
    $result = invoke-command -Scriptblock $sb -ComputerName $server

    You shouldn't need to use remoting. SQS does its  own remoting:

    $results = invoke-sqlcmd -Query 'select newid()' -ServerInstance DBServer

    Just use this query directly to the server.  The server function knows what to do.

    If you just want a guid then just do this:


    New guids are system independent.  Any fresh guid is like any other fresh guid.


    Sunday, June 9, 2019 10:30 AM
  • Hi,

    Was your issue resolved?

    If you resolved it using our solution, please "mark it as answer" to help other community members find the helpful reply quickly.

    If you resolve it using your own solution, please share your experience and solution here. It will be very beneficial for other community members who have similar questions.

    If no, please reply and tell us the current situation in order to provide further help.

    Best Regards,


    Just do it.

    Friday, July 5, 2019 2:24 AM