The query below is used to create a text file with a list of server names.
The problem I have is that the text file gets created like
Server, Server, Server etc.
but I need it as follows
Server
Server
Server
The query:
BEGIN
CREATE TABLE [TempPSWmiObjectQuery]
(QueryText nvarchar(max))
END
INSERT INTO [TempPSWmiObjectQuery]
SELECT STUFF((SELECT char(13)+char(10),
SUBSTRING(ServerName, 1,
CASE WHEN CHARINDEX(',', ServerName) > 0
THEN CHARINDEX(',', ServerName)-1
ELSE LEN(ServerName)
END)
FROM MasterList
FOR XML PATH('')), 1, 1, '')
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE
EXEC xp_cmdshell 'bcp SQLEnv.dbo.TempPSWmiObjectQuery out "\\ServerName\Data\temp\testlist.txt" -c -T -S "ServerName\Instance"'
EXEC sp_configure 'xp_cmdshell', 0;
RECONFIGURE
DROP TABLE TempPSWmiObjectQuery
The PowerShell Script:
$StagingServer = "ServerName\InstanceName"
$StagingServerDatabase = "SQLEnv"
foreach($line in
[System.IO.File]::ReadLines("\\ServerName\Data\temp\testlist.txt"))
{
$line
Get-WmiObject win32_Service -Computer $line | where {$_.DisplayName
-match "SQL Server"} | select SystemName, DisplayName, Name, State,
Status, StartMode, StartName | ConvertTo-DbaDataTable | Write-
DbaDataTable -SqlInstance $StagingServer -Database
$StagingServerDatabase -Table _SQLServicesInfo -AutoCreateTable -Confirm
}
Best Answer
This answer assumes multiple comma's are in a single row of the
ServerName
column, and these need to be removed & Line feed + Carriage returns added instead of each comma.There could be better ways to get your endresult, but to write to a text file without the comma's, you could use the
REPLACE()
function.CHARINDEX()
will only give you the location of the first value found.Test
Result
Change
SELECT REPLACE(ServerName,',',+ ' '+char(13)+char(10) )
toSELECT REPLACE(ServerName,',',+ ' ' )
if you don't want new lines.