ConvertTo-SecureString converts an existing string into a System.Security.SecureString. Using -AsPlainText requires -Force because the source value already exists in memory and may appear in scripts, event logs, or PowerShell history. section 4.2.1
SecureString values are encrypted and pinned in memory on Windows, reducing exposure through memory dumps and ensuring cleanup when the variable is deleted or the process ends. On Linux and macOS, the in-memory value is not encrypted. section 4.2.1
Choose the conversion approach according to how the secret enters the automation:
- Prefer Read-Host -AsSecureString when a user can enter the value interactively; this avoids placing plaintext directly in the script. section 4.2.1
- Use ConvertTo-SecureString with -AsPlainText -Force when an existing string must be converted, while recognizing the weaker plaintext handling. section 4.2.1
- Supply a custom encryption key when a SecureString must move between computers; protect that key because it can decrypt the stored values. section 4.2.1
Recreating Jenkins credentials
Jenkins exposes bound secrets to a PowerShell build as ordinary environment-variable strings. Convert each password back into a SecureString before constructing a PSCredential: $secure = @{ String = $ENV:sqlpassword; AsPlainText = $true; Force = $true }; $Password = ConvertTo-SecureString @secure; $SqlCredential = New-Object System.Management.Automation.PSCredential ($ENV:sqlusername, $Password). section 4.4.2
$String = "password01" $SecureString = ConvertTo-SecureString $String -AsPlainText -Force $SecureString System.Security.SecureString
Inspect the minimal plaintext conversion that produces a System.Security.SecureString object. section 4.2.1
