I have the following script in 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.
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?
SecureString. Just"$Password"will return stringSystem.Security.SecureString.