如何将SQL凭据作为命令行参数传递给PowerShell脚本

时间:2021-01-07 00:37:29

I have the following script in PowerShell:

我在PowerShell中有以下脚本:

Clear-Host 
$Machine=Read-Host "Enter the machine name"

$SQLServerTEST = "servername\instance1"  
$SQLTableTEST = "Computer"
$SqlConnectionLANDESK = New-Object System.Data.SqlClient.SqlConnection
$global:dt = new-object System.Data.DataTable

$LONA = ""
$o = 0

function doit() {
$SqlConnectionTEST.ConnectionString =     "Server=$SQLServerTEST;Database=$SQLDBNameTEST;uid=userid;pwd=password"
$SqlConnectionTEST.Open()

$QueryLANDesk = @"

SELECT 
    [Type]
  ,[DeviceName]
  ,[LoginName]
  ,[PrimaryOwner]
FROM $SQLTableTEST
WHERE ([Type] NOT LIKE 'Server' AND [DeviceName] LIKE '%$Machine%' AND     [LoginName] IS NOT NULL )

"@ 

$CommandTEST = new-object System.Data.SqlClient.SqlDataAdapter ($QueryTEST, $SqlConnectionTEST) 
$CommandLANDesk.fill($dt) | out-null

            $dtrc = $dt.Rows.Count
 Write-Host "($i) Searching all cores ($dtrc machines)..."

$SqlConnectionTEST.Close() 
}

foreach ($i in  1..10)
{if ($i -eq 6) {continue}
  $SQLDBNameTEST = "cuc$i"
  $SQLServerTEST = "servername\instance1"
  doit
    }

Write-Host 

$dt.select("DeviceName like '%$Machine%'") | foreach  {  $o++  } 

$dt | Format-Table -AutoSize | select -first 10

"$o machines found."`

I want to be able to pass the $Machine, the dbusename and the password as command line arguments for safety reasons.

我希望能够出于安全原因将$ Machine,dbusename和密码作为命令行参数传递。

I have tried already

我已经尝试过了

Clear-Host 



Param (
[Parameter(Mandatory=$True)]
[string]$dbusername,

[Parameter(Mandatory=$True)]
[Security.SecureString]$Password,

[Parameter(Mandatory=$True)]
[string]$Machine
)

$SQLServerTEST = "servername\instance1"  
$SQLTableTEST = "Computer"

$SqlConnectionTEST = New-Object System.Data.SqlClient.SqlConnection
$global:dt = new-object System.Data.DataTable

$LONA = ""
$o = 0

function doit() {
    $SqlConnectionTEST.ConnectionString =         "Server=$SQLServerTEST;Database=$SQLDBNameTEST;uid=$dbusername;pwd=$Password"
$SqlConnectionTEST.Open()

…….

But this gives me errors:

但这给了我错误:

Exception calling "Open" with "0" argument(s): "Login failed for user     'userid'."
At C:\Users\me\Desktop\cucu\PRIMARYOWNER\Primaryowner.ps1:15 char:5
+     $SqlConnectionTEST.Open()
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException

Exception calling "Fill" with "1" argument(s): "Login failed for user     'userid'."
At C:\Users\me\Desktop\cucu\PRIMARYOWNER\Primaryowner.ps1:31 char:5
+     $CommandLANDesk.fill($dt) | out-null
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException

Can you help me figure this?

你能帮我解决这个问题吗?

1 个解决方案

#1


1  

Try following to get plain text password inside a variable from a secure string which then you will be able to pass to your connectionString. Editing my answer based upon the comment related to memory leak.

尝试按照从安全字符串中获取变量中的纯文本密码,然后您就可以将其传递给connectionString。根据与内存泄漏相关的注释编辑我的答案。

$creds = get-credential
$Marshal=[Runtime.InteropServices.Marshal];
$Handle=[IntPtr]::Zero;
$Result= try {
  [Runtime.InteropServices.Marshal]::PtrToStringBSTR(($Handle=$Marshal::SecureStringToBSTR($creds.Password))) 
}catch {}
finally{
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($Handle)
}
$Result

Another alternate approach and much easier approach is here

另一种替代方法和更简单的方法就在这里

PS> $creds = Get-Credential
PS> $plainTextPassword = $creds.GetNetworkCredential().Password

#1


1  

Try following to get plain text password inside a variable from a secure string which then you will be able to pass to your connectionString. Editing my answer based upon the comment related to memory leak.

尝试按照从安全字符串中获取变量中的纯文本密码,然后您就可以将其传递给connectionString。根据与内存泄漏相关的注释编辑我的答案。

$creds = get-credential
$Marshal=[Runtime.InteropServices.Marshal];
$Handle=[IntPtr]::Zero;
$Result= try {
  [Runtime.InteropServices.Marshal]::PtrToStringBSTR(($Handle=$Marshal::SecureStringToBSTR($creds.Password))) 
}catch {}
finally{
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($Handle)
}
$Result

Another alternate approach and much easier approach is here

另一种替代方法和更简单的方法就在这里

PS> $creds = Get-Credential
PS> $plainTextPassword = $creds.GetNetworkCredential().Password