Encrypt or decrypt a column with PowerShell
Encrypt a column
-
Log in to the client using the <domain>\dbuser account.
-
Launch PowerShell and run the
Encrypt_Column_Named_Password.ps1script (below).# Import the SqlServer module. Import-Module SqlServer -MinimumVersion 22.0.59 # Set up connection and database SMO objects $sqlConnectionString = "Data Source=MSSQL-AE2025SRV;Initial Catalog=TestDatabase;Integrated Security=True;Multiple Active Result Sets=False;Connect Timeout=30;Encrypt=True;Trust Server Certificate=True;Packet Size=4096;Application Name=`"Microsoft SQL Server Management Studio`"" $smoDatabase = Get-SqlDatabase -ConnectionString $sqlConnectionString # Change encryption schema $encryptionChanges = @() # Add changes for table [dbo].[TestTable] $encryptionChanges += New-SqlColumnEncryptionSettings -ColumnName dbo.TestTable.Password -EncryptionType Randomized -EncryptionKey "MyCEK" Set-SqlColumnEncryption -ColumnEncryptionSettings $encryptionChanges -InputObject $smoDatabaseThe command line is:
> PowerShell -ExecutionPolicy Bypass -File Encrypt_Column_Named_Password.ps1 -
Present the OCS, select the HSM, and enter the passphrase.
-
Launch Microsoft SQL Server Management Studio. Do as indicated in encrypt-decrypt-column-with-ssms.adoc#view-encrypted-column-ssms to verify the column has been encrypted.
Remove column encryption
-
Log in to the client using the <domain>\dbuser account.
-
Launch PowerShell and run the
Decrypt_Column_Named_Password.ps1script (below).# Import the SqlServer module. Import-Module SqlServer -MinimumVersion 22.0.59 # Set up connection and database SMO objects $sqlConnectionString = "Data Source=MSSQL-AE2025SRV;Initial Catalog=TestDatabase;Integrated Security=True;Multiple Active Result Sets=False;Connect Timeout=30;Encrypt=True;Trust Server Certificate=True;Packet Size=4096;Application Name=`"Microsoft SQL Server Management Studio`"" $smoDatabase = Get-SqlDatabase -ConnectionString $sqlConnectionString # Change encryption schema $encryptionChanges = @() # Add changes for table [dbo].[TestTable] $encryptionChanges += New-SqlColumnEncryptionSettings -ColumnName dbo.TestTable.Password -EncryptionType Plaintext Set-SqlColumnEncryption -ColumnEncryptionSettings $encryptionChanges -InputObject $smoDatabaseThe command line is:
> PowerShell -ExecutionPolicy Bypass -File Decrypt_Column_Named_Password.ps1 -
Present the OCS, select the HSM, and enter the passphrase.
-
Launch Microsoft SQL Server Management Studio. Do as indicated in encrypt-decrypt-column-with-ssms.adoc#view-encrypted-column-ssms to verify the column has been decrypted.