0

I have the below SQL query to get the logical filename of my database backup file.

$sqlcmd = "RESTORE FILELISTONLY FROM DISK = N'E:\backup\OnePDM\DBEmpty.bak'"
& sqlcmd -Q $sqlcmd 

Now I'm trying to filter only the LogicalName column from the above result using below command. But I'm getting blank value for all rows.

& sqlcmd -Q $sqlcmd   | Select-Object -Property LogicalName

Is there any way to get this from Powershell command?

2
  • 1
    I have had trouble with sqlcmd as the data it returns, I have found it to be hard to work with. I switched to Invoke-sqlcmd from sqlserver powershell module. learn.microsoft.com/en-us/sql/powershell/… Commented Jul 29, 2019 at 19:17
  • It is generally a bad practice to mix DOS commands with PowerShell. You may consider Invoke-SqlCmd from sqlserver or Invoke-DbaQuery from dbatools (I personally recommend dbatools) Commented Jul 29, 2019 at 19:32

1 Answer 1

4

Your command will not work because since sqlcmd is not a Cmdlet. This means sqlcmd will only return text, instead of a PowerShell object.

To solve this, you should instead use a Cmdlet from a module like the Microsoft official sqlserver or the community made dbatools.

sqlserver:

# Run this once to get the module if you don't already have it (requires PowerShell Get)
Install-Module sqlserver

# Invoke this every time you begin a new instance (new terminal window or new script)
Import-Module sqlserver

Invoke-SqlCmd -ServerInstance 'yourserver\instance' -Query 'SELECT * FROM whatever' |
    Select-Object -Property ColumnNameHere

dbatools:

Disclaimer: I have made non-code contributions to dbatools in the past but I am not officially affiliated with them

# Run this once to get the module if you don't already have it (requires PowerShell Get)
Install-Module dbatools

# Invoke this every time you begin a new instance (new terminal window or new script)
Import-Module dbatools

Invoke-DbaQuery -SqlInstance 'yourserver\instance' -Query 'SELECT * FROM whatever' |
    Select-Object -Property ColumnNameHere
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.