Search code examples
sql-serverxp-cmdshelltasklist

Tasklist using xp_cmdshell


I want to know how i will use the tasklist cmd that will output the imagename plus the hostname

i have thus syntax but could not combine the result into one.

EXEC xp_cmdshell 'tasklist /fi "imagename eq notepad.exe"';  

plus hostname


Solution

  • This will give you what you want:

    DECLARE @T TABLE (capture VARCHAR(5000))
    
    INSERT @T
    EXEC xp_cmdshell 'tasklist /fi "imagename eq notepad.exe"'; 
    
    INSERT INTO dbo.[N4FO_OpenGUIOutput] (Output,system) 
    SELECT capture, @@SERVERNAME as host FROM @T WHERE capture IS NOT NULL
    

    But you have to actually connect to the SQL Server to run it so you'll already need to know the host name to connect to.