Sql-Server
將 SQL Server 結果轉換為 PowerShell 可以訪問和使用的文本文件
下面的查詢用於創建帶有伺服器名稱列表的文本文件。
我遇到的問題是文本文件的創建就像
Server, Server, Server etc.
但我需要它如下
Server Server Server
查詢:
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
PowerShell 腳本:
$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 }
此答案假定多個逗號位於列的單行中
ServerName
,並且需要刪除這些逗號並添加換行符+輸入符而不是每個逗號。可能有更好的方法來獲得最終結果,但是要寫入沒有逗號的文本文件,您可以使用該
REPLACE()
函式。
CHARINDEX()
只會給你找到第一個值的位置。CREATE TABLE [TempPSWmiObjectQuery](QueryText nvarchar(max)); INSERT INTO [TempPSWmiObjectQuery] SELECT REPLACE(ServerName,',',+ ' '+char(13)+char(10) ) -- Replace comma with space, line feed and carriage return. FROM MasterList; 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;
測試
INSERT INTO MasterList(ServerName) VALUES('Server1,Server2,Server3')
如果您不想要新行,請更改
SELECT REPLACE(ServerName,',',+ ' '+char(13)+char(10) )
為 。SELECT REPLACE(ServerName,',',+ ' ' )