Sql-Server

而不是 C:SQLDBAServerNameInstance 而不是 C:SQLDBAServerName_Instance

  • August 19, 2018

我正在嘗試根據要備份的 servername\instance 創建一個文件夾,我希望該文件夾創建為 servername_instance。您能否指出我哪裡出錯了,因為它創建為 servername\instance

IF OBJECT_ID('TempPSCreateFolder') IS NULL
BEGIN
CREATE TABLE [TempPSCreateFolder]
(QueryText nvarchar(max))
END

INSERT INTO [TempPSCreateFolder]

SELECT '$fso = new-object -ComObject scripting.filesystemobject

$fso.CreateFolder("C:\'+ STUFF((SELECT ',' + SUBSTRING(@@SERVERNAME, 1, CASE 
WHEN CHARINDEX(',', @@SERVERNAME) > 0 THEN 
CHARINDEX(',', @@ServerName)-1
                      ELSE LEN(@@ServerName)
                   END)

FOR XML PATH('')), 1, 1, '')+'")'

EXEC sp_configure 'xp_cmdshell', 1;  
RECONFIGURE

EXEC xp_cmdshell 'bcp master.dbo.TempPSCreateFolder out 
"C:\SQLDBA\CreateFolder.ps1" -c -T -SServer\Instance'

EXEC sp_configure 'xp_cmdshell', 0;  
RECONFIGURE

DROP TABLE TempPSCreateFolder

您的腳本似乎過於復雜。根據問題標題格式化文件夾名稱所需要做的就是@@SERVERNAME用下劃線替換反斜杠。不需要表、腳本文件和XML PATH此任務。PowerShell 還包括一個New-Item命令,以避免對舊版 COM 的需要FileSystemObject

DECLARE @PowershellCommand varchar(8000) = 'powershell -Command "New-Item -Path \"C:\SQLDBA\'
   + REPLACE(@@SERVERNAME, '\', '_')
   + '\" -ItemType \"directory\""';
EXEC sp_configure 'xp_cmdshell', 1;  --assumes 'show advanced' config option is already enabled 
RECONFIGURE;
EXEC xp_cmdshell @PowershellCommand;
EXEC sp_configure 'xp_cmdshell', 0;  
RECONFIGURE;

你也可以xp_cmdshell完全避免,只在伺服器上執行一個獨立的 PowerShell 腳本:

New-Item -Path "C:\SQLDBA\ServerName_InstanceName" -ItemType "directory"

引用自:https://dba.stackexchange.com/questions/215297