I am new to powershell and trying to built a script which can accept username and fetch corresponding userID from table(SUser), based on which i should delete that particular user from that table. Below is the code, kindly correct in case of any syntax errors cause i am not able to find any error and
I am not able to fetch values properly. Some times the query doesnt fetch values and some times the results on first run are displayed on the second run.
clear
$servername = "Someserver"
$databasename = "someDB"
$c = Get-Credential
$cmd1 = "select UserID from SUser where UserName='$Name'"
$cmd2 = "delete from SUser where UserID = '$a'"
$connectionString = [string]::Format( "server={0};database={1};uid={2};pwd= {3};Integrated Security=True;", "$servername", "$databasename",$c.username,$c.GetNetworkCredential ().password)
$conn = New-Object system.Data.SqlClient.SqlConnection
$conn.connectionstring = $connectionString
$conn.open()
switch ($conn.State)
{
"Open"
{
$SqlCmd1 = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd1.CommandText = $cmd1
$SqlCmd1.Connection = $Conn
$Name = Read-host "Enter UserName (One user name at a time):"
write-host "UserName Entered:" $Name
$usrname = $SqlCmd1.ExecuteScalar()
$a = $usrname
write-host "User Id for Username $Name :"$a
$SqlCmd2 = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd2.CommandText = $cmd2
$SqlCmd2.Connection = $Conn
$usrid = $SqlCmd2.ExecuteScalar()
}
Default
{ Write-Host "The connection is $($conn.State)";
}
}
$conn.close()
Thanks, Hari
write-host $SqlCmd1.CommandTextandwrite-host $SqlCmd2.CommandTextbefore you execute them?$cmd2 = "select UserName from SUser where UserID='$a'"I am getting the below lines in the ouput pane:select UserID from SUser where UserName=''select UserName from SUser where UserID=''