Skip to content

Commit c16f7f3

Browse files
Export-DbaCredential - Add IF NOT EXISTS guard to exported SQL scripts (#10295)
1 parent aaa8f9e commit c16f7f3

2 files changed

Lines changed: 6 additions & 1 deletion

File tree

public/Export-DbaCredential.ps1

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,14 +165,15 @@ function Export-DbaCredential {
165165

166166
foreach ($cred in $credentials) {
167167
$quotename = $cred.Quotename
168+
$credName = $cred.Name.Replace("'", "''")
168169
$identity = $cred.Identity.Replace("'", "''")
169170
$password = $cred.Password.Replace("'", "''")
170171
$cryptoSql = ""
171172
if ($cred.MappedClassType -like 'Cryptographic*') {
172173
$providerName = $cred.ProviderName
173174
$cryptoSql = " FOR CRYPTOGRAPHIC PROVIDER $providerName"
174175
}
175-
$sql += "CREATE CREDENTIAL $quotename WITH IDENTITY = N'$identity', SECRET = N'$password'" + $cryptoSql
176+
$sql += "IF NOT EXISTS (SELECT 1 FROM sys.credentials WHERE name = N'$credName') CREATE CREDENTIAL $quotename WITH IDENTITY = N'$identity', SECRET = N'$password'" + $cryptoSql
176177
}
177178

178179
if ($Passthru) {

tests/Export-DbaCredential.Tests.ps1

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,10 @@ Describe $CommandName -Tag IntegrationTests {
108108
It "Should have the password" {
109109
$exportResults | Should -Match "ReallyT3rrible!"
110110
}
111+
112+
It "Should include IF NOT EXISTS guard" {
113+
$exportResults | Should -Match "IF NOT EXISTS"
114+
}
111115
}
112116

113117
Context "Should export a specific credential" {

0 commit comments

Comments
 (0)