Database Reference
In-Depth Information
The
Get-ConfigConnectionString
function uses
gc
(an alias for
Get-Content
)
to read the ile's XML text and then creates an
XmlDocument
from the result with
[xml]
. It then looks for and returns the speciied connection string, or throws an
exception if the speciied connection was not found.
2.
Some connection strings may be stored in
machine.config
under
%WINDIR%\
Microsoft.NET\Framework\[Version]\Config\
where
[Version]
is the .NET
Framework version (i.e. v2.0.50727 or v4.0.30319). These can be accessed with
Get-
ConfigConnectionString
or via using the
ConfigurationManager
class:
$config = [System.Configuration.ConfigurationManager]::OpenMachine
Configuration()
$connectString = $config.ConnectionStrings.
ConnectionStrings["AppConnect"]
If securing connection strings is a concern, you might use
Secure-String
if the account encrypting and decrypting is the
same, or use
Library-StringCrypto.ps1
by Steven Hystad.
Prompting for connection credentials
If a user-interactive script is acceptable there may be times where you want to prompt for
credentials to use in building a connection string:
function Get-Password
{
$securePass = Read-Host "Enter Password" -AsSecureString
$bstr = [System.Runtime.InteropServices.Marshal]::SecureString
ToBSTR($securePass)
$pass = [System.Runtime.InteropServices.Marshal]::PtrToStringA
uto($bstr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
return $pass
}
$user = read-host "Enter username"
$pass = Get-Password
$connectString = "Data Source=LOCALDEV;User
Id={0};Password={1};Connection Timeout=10" -f $user, $pass
This script deines a
Get-Password
function that uses the
-AsSecureString
switch
of
Read-Host
to get a secure password string. It then does a couple of conversions and
cleanup using methods in
System.Runtime.InteropServices.Marshal
class to return
a plain text version of the secure password.
Search WWH ::
Custom Search