locked
Write-Output variable inclusion RRS feed

  • Question

  • Hi,

    I need to output $Query” to a .ps1 file via Write-Output/Out-File in the below script. However, it doesn’t populate in either .ps1 or .txt extensions.

    Write-Output "$Query = SELECT

    (SELECT TOP (1) [SoftwareRevision]

    FROM [Database1]

    ) As 'Software Version'” | Out-file -filepath c:\scripts\attempt.ps1

    Is there a way to bypass this so I can include the variable?

    Thanks

    Thursday, July 6, 2017 6:49 PM

Answers


  • @'
    $Query = SELECT
    (SELECT TOP (1) [SoftwareRevision]
    FROM [Database1]
    ) As 'Software Version'
    '@ | Out-File C:\Scripts\attempt.ps1
    

    Run the command help about_Quoting_Rules for more information about here-strings.

    -- Bill Stewart [Bill_Stewart]


    • Edited by Bill_Stewart Thursday, July 6, 2017 7:33 PM
    • Marked as answer by RackHat Thursday, July 6, 2017 8:14 PM
    Thursday, July 6, 2017 7:33 PM

All replies


  • @'
    $Query = SELECT
    (SELECT TOP (1) [SoftwareRevision]
    FROM [Database1]
    ) As 'Software Version'
    '@ | Out-File C:\Scripts\attempt.ps1
    

    Run the command help about_Quoting_Rules for more information about here-strings.

    -- Bill Stewart [Bill_Stewart]


    • Edited by Bill_Stewart Thursday, July 6, 2017 7:33 PM
    • Marked as answer by RackHat Thursday, July 6, 2017 8:14 PM
    Thursday, July 6, 2017 7:33 PM
  • You lost the required quotes.  I also suspect that the SQL is wrong:

    $qryText = '$Query = "SELECT TOP 1 SoftwareRevision As [Software Version] FROM Database1"'
    $qryText | Out-File C:\Scripts\attempt.ps1
    We only need to us [] when there are spaces in object names.   Single quotes are used when values are of type *char.


    \_(ツ)_/

    Thursday, July 6, 2017 10:41 PM