Registry - HKEY_USERS Recursively Delete Key (VBS) - recursion

I would like to delete the following value recursively through the User Profiles/HKEY_USERS location. This is what I got so far. However I cannot get the script to delete the value under "strKeyPath" variable. I have removed what I did before as it was very wrong.
Const HKEY_CURRENT_USER = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002
Const HKEY_USERS = &H80000003
'Set the local computer as the target
strComputer = "."
'set the objRegistry Object
Set objRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
'Enumerate All subkeys in HKEY_USERS
objRegistry.EnumKey HKEY_USERS, "", arrSubkeys
'Define variables
strKeyPath = "\Software\Microsoft\Windows\CurrentVersion\Uninstall\50cc940dd0f54608"
strSID = "S-1-5-21-\d*-\d*-\d*-\d*\\"

What you're trying to achieve isn't really 'recursion', you're just deleting a registry key from a number of different places. This is how I'd do it:
Option Explicit
Const HKU = &H80000003
Dim wmi, reg
Dim prof, profs
Dim key
Set wmi = GetObject("winmgmts:\\.\root\cimv2")
Set reg = GetObject("winmgmts:\\.\root\default:StdRegProv")
Set profs = wmi.ExecQuery("Select SID from Win32_UserProfile where SID like 'S-1-5-21%'")
For Each prof In profs
key = prof.SID & "\Software\Microsoft\Windows\CurrentVersion\Uninstall\50cc940dd0f54608"
WScript.Echo key
'Call reg.DeleteKey(HKU, key) 'commented out for safety
Next
The WMI query matches all user profiles on the system, the same as your regular expression, and the result of it is used to build a registry path.
Please be careful when deleting from the registry

Related

How to get the total number of records count from a sql ado dB connection in classic asp [duplicate]

I am newbie in VBScript and I've come across with the following problem. I want get data from sql server db and to allow RecordCount properties. Next code get data but RecordCount is disabled. How can I enable this properties
Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=BUG\SQLSERVER2005;Initial Catalog=test;user id ='sa';password='111111'"
Set myConn = CreateObject("ADODB.Connection")
Set myCommand = CreateObject("ADODB.Command" )
myConn.Open DB_CONNECT_STRING
Set myCommand.ActiveConnection = myConn
myCommand.CommandText = ("select * from klienci k where k.indeks = " & oferty(16))
Set klienci = myCommand.Execute
AFAIK you can't change the cursor type when using the Execute method of the Command object, and you can't change the cursor type after you retrieved the recordset. Something like this might work, though:
Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=BUG\SQLSERVER2005;Initial Catalog=test;user id ='sa';password='111111'"
Set myConn = CreateObject("ADODB.Connection")
myConn.Open DB_CONNECT_STRING
query = "select * from klienci k where k.indeks = " & oferty(16)
Set klienci = CreateObject("ADODB.Recordset")
klienci.CursorLocation = 3 'adUseClient
klienci.CursorType = 3 'adOpenStatic
klienci.LockType = 1 'adLockReadOnly
klienci.Open query, myConn
I don't think this is a VBScript issue- I think it is an ADO issue.
I think you are using a default forward-only cursor which won't work with recordcount.
I think you should stick a cursortype=adOpenStatic in there but I'm having a little trouble determining if you are specifying a recordset object - klienci?
If so try
klienci.cursortype=adOpenStatic

ms_access Run time error 3078 in VBA although query runs as saved query [duplicate]

I have a query called qryAlloc_Source that has two paramaters under one criteria:
>=[forms]![frmReportingMain]![txtAllocStart] And <=[forms]![frmReportingMain]![txtAllocEnd])
A have a separate query that ultimately references qryAlloc_Source (there are a couple queries in between), and that query runs fine when I double click it in the UI, but if I try to open it in VBA, I get an error. My code is:
Dim rst As Recordset
Set rst = CurrentDb.OpenRecordset("qryAlloc_Debits")
I am getting run-time error 3061, Too few parameters. Expected 2. I've read that I may need to build out the SQL in VBA using the form parameters, but it would be pretty complex SQL given that there are a few queries in the chain.
Any suggestions as to a workaround? I considered using VBA to create a table from the query and then just referencing that table--I hate to make extra steps though.
The reason you get the error when you just try to open the recordset is that your form is not open and when you try to access [forms]![frmReportingMain] it's null then you try to get a property on that null reference and things blow up. The OpenRecordset function has no way of poping up a dialog box to prompt for user inputs like the UI does if it gets this error.
You can change your query to use parameters that are not bound to a form
yourTableAllocStart >= pAllocStart
and yourTableAllocEnd <= pAllocEnd
Then you can use this function to get the recordset of that query.
Function GetQryAllocDebits(pAllocStart As String, pAllocEnd As String) As DAO.Recordset
Dim db As DAO.Database
Dim qdef As DAO.QueryDef
Set db = CurrentDb
Set qdef = db.QueryDefs("qryAlloc_Debits")
qdef.Parameters.Refresh
qdef.Parameters("pAllocStart").Value = pAllocStart
qdef.Parameters("pAllocEnd").Value = pAllocEnd
Set GetQryAllocDebits = qdef.OpenRecordset
End Function
The disadvantage to this is that when you call this now on a form that is bound to it it doesn't dynamically 'fill in the blanks' for you.
In that case you can bind forms qryAlloc_debts and have no where clause on the saved query, then use the forms Filter to make your where clause. In that instance you can use your where clause exactly how you have it written.
Then if you want to still open a recordset you can do it like this
Function GetQryAllocDebits(pAllocStart As String, pAllocEnd As String) As DAO.Recordset
Dim qdef As DAO.QueryDef
Set qdef = New DAO.QueryDef
qdef.SQL = "Select * from qryAlloc_Debits where AllocStart >= pAllocStart and pAllocEnd <= pAllocEnd"
qdef.Parameters.Refresh
qdef.Parameters("pAllocStart").Value = pAllocStart
qdef.Parameters("pAllocEnd").Value = pAllocEnd
Set GetQryAllocDebits = qdef.OpenRecordset
End Function
While a [Forms]!... reference does default to a form reference when a QueryDef is run from the GUI, it is actually just another Parameter in the query in VBA. The upshot is you don't have to recode your query/create a new one at all. Also, as #Brad mentioned, whether a parameter is in the final query of a chain of queries or not, you are able to refer to the parameter as if it is in the collection of the final query. That being the case, you should be able to use code similar to this:
Sub GetQryAllocDebits(dteAllocStart As Date, dteAllocEnd as Date)
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
Set db = CurrentDb()
Set qdf = db.QueryDefs("qryAlloc_Debit")
If CurrentProject.AllForms("frmReportingMain").IsLoaded Then
qdf.Parameters("[forms]![frmReportingMain]![txtAllocStart]") = [forms]![frmReportingMain]![txtAllocStart]
qdf.Parameters("[forms]![frmReportingMain]![txtAllocEnd]") = [forms]![frmReportingMain]![txtAllocEnd]
Else
qdf.Parameters("[forms]![frmReportingMain]![txtAllocStart]") = CStr(dteAllocStart)
qdf.Parameters("[forms]![frmReportingMain]![txtAllocEnd]") = CStr(dteAllocEnd)
End If
Set rst = qdf.OpenRecordset
Do Until rst.EOF
'...do stuff here.
Loop
Set rst = Nothing
Set qdf = Nothing
Set db = Nothing
End Function
If the referenced form is open, the code is smart enough to use the referenced controls on the form. If not, it will use the dates supplied to the subroutine as parameters. A gotcha here is that the parameters did not like when I set them as date types (#xx/xx/xx#), even if the field were dates. It only seemed to work properly if I set the params as strings. It didn't seem to be an issue when pulling the values straight out of the controls on the forms, though.
I know it's been a while since this was posted, but I'd like to throw in my tuppence worth as I'm always searching this problem:
A stored query can be resolved:
Set db = CurrentDb
Set qdf = db.QueryDefs(sQueryName)
For Each prm In qdf.Parameters
prm.Value = Eval(prm.Name)
Next prm
Set rst = qdf.OpenRecordset
For SQL:
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", "SELECT * FROM MyTable " & _
"WHERE ID = " & Me.lstID & _
" AND dWeekCommencing = " & CDbl(Me.frm_SomeForm.Controls("txtWkCommencing")) & _
" AND DB_Status = 'Used'")
For Each prm In qdf.Parameters
prm.Value = Eval(prm.Name)
Next prm
Set rst = qdf.OpenRecordset
This assumes that all parameter values are accessible - i.e. forms are open and controls have values.
'I have two parameters in my recordset and I was getting the "Too few parameters. Expected 2" 'error when using an OpenRecordset in MS Access vba, and this is how I got around it and IT WORKS! see the below sub routine:
'Private Sub DisplayID_Click()
'1. I created variables for my two parameter fields xEventID and xExID as seen below:
Dim db As Database
Dim rst As Recordset
Dim xEventID As Integer
Dim xExId As Integer
'2. Sets the variables to the parameter fields as seen below:
Set db = CurrentDb
xEventID = Forms!frmExhibitorEntry!txtEventID
xExId = Forms!frmExhibitorEntry!subExhibitors!ExID
'3. Set the rst to OpenRecordSet and assign the Set the variables to the WHERE clause. Be sure to include all quotations, ampersand, and spaces exactly the way it is displayed. Otherwise the code will break!exactly as it is seen below:
Set rst = db.OpenRecordset("SELECT tblInfo_Exhibitor.EventID,tblInfo_Display.ExID, tblMstr_DisplayItems.Display " _
& "FROM tblInfo_Exhibitor INNER JOIN (tblMstr_DisplayItems INNER JOIN tblInfo_Display ON tblMstr_DisplayItems.DisplayID = tblInfo_Display.DisplayID) ON tblInfo_Exhibitor.ExID = tblInfo_Display.ExID " _
& "WHERE (((tblInfo_Exhibitor.EventID) =" & xEventID & " ) and ((tblInfo_Exhibitor.ExID) =" & xExId & " ));")
rst.Close
Set rst = Nothing
db.Close
'End Sub

Creating dynamic ADODB connections in Classic ASP

I have a list of Database connection strings, Database Name. These databases have the same table structure. What I am trying to do is dynamically create a connection to each one, add/delete/modify a table, however, if an error pops up anywhere, then RollbackTrans, else, CommitTrans.
My basic question to get my on the correct path is this:
Is this code possible in Classic ASP to make Dynamically named connections?
'create the dynamic object
execute("Set Con" & index & " = Server.CreateObject(""ADODB.connection"")")
'connect to the dynamic object
execute("Con" & index & ".Open " & DBString(index))
The error I get is 'Expected end of statement' on the .open line (the last one)
This might do the trick: Just use an array of connection strings. From this you create an array of connections. Then you can iterate over this array and send your commands to the separate databases.
dim connectionStrings(1)
dim connections(1)
dim curConn
connectionStrings(0) = "Provider=sqloledb;Server=.\EXPRESS2012;Database=master;uid=youruser;pwd=yourpwd"
connectionStrings(1) = "Provider=sqloledb;Server=.\EXPRESS2012;Database=model;uid=youruser;pwd=yourpwd"
for curConn = 0 to ubound( connectionStrings)
set connections(curConn) = Server.CreateObject("ADODB.Connection")
connections(curConn).Open connectionStrings(curConn)
next
dim cmd : cmd = "select ##servername, db_name()"
for curConn = 0 to ubound( connectionStrings)
dim rs
set rs = connections(curConn).Execute( cmd)
Response.write( rs( 0) & ":" & rs(1) & "<br />")
rs.close
set rs = nothing
next
for curConn = 0 to ubound( connectionStrings)
call connections(curConn).Close
set connections(curConn) = nothing
next
Mysql Dynamic Connection String , sample for t=1 to 4 , four different database connection conns(t)
dim conns(4)
Set Conns(1)=Server.Createobject("ADODB.Connection")
Conns(1).Open "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost;port=3306;DATABASE=dbname;UID=root;PASSWORD=pass;OPTION=3"
Conns(1).Execute "SET NAMES 'latin5'"
Conns(1).Execute "SET CHARACTER SET latin5"
Conns(1).Execute "SET COLLATION_CONNECTION = 'latin5_turkish_ci'"

Why 'The local device name is already in use' in asp.net when mapping drive but OK with command line

In command line it works fine:
net USE T: \123.45.67.89\TEST mytestuser /user:MYTESTUSER
But using asp.net, with the following code, the Exception with the following error is always thrown: 'The local device name is already in use' when mapping drive
I have tried disconnecting from all drives first, mapping to a different Drive letter. I have done this from different servers, and to different servers
Is the problem definitely with drive letter?
temp = MapDrive("T", "\\123.45.67.89\TEST", "MYTESTUSER", "mytestuser")
Public Shared Function MapDrive(ByVal DriveLetter As String, ByVal Path As String, ByVal Username As String, ByVal Password As String) As Boolean
Dim ReturnValue As Boolean = False
Dim p As New System.Diagnostics.Process()
p.StartInfo.UseShellExecute = False
p.StartInfo.CreateNoWindow = True
p.StartInfo.RedirectStandardError = True
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.FileName = "net.exe"
p.StartInfo.Arguments = " use " & DriveLetter & ": " & Path & " /user:" & Username & " " & Password & " /persistent:yes"
p.Start()
p.WaitForExit()
Dim ErrorMessage As String = p.StandardError.ReadToEnd()
Dim OuputMessage As String = p.StandardOutput.ReadToEnd()
Dim StoreFile As System.IO.Directory
Dim Files As String()
Dim File As String
If ErrorMessage.Length > 0 Then
Throw New Exception("Error:" & ErrorMessage)
Else
ReturnValue = True
End If
Files = StoreFile.GetFiles("T:\FINDTHIS\", "*")
For Each File In Files
HttpContext.Current.Trace.Warn(File)
Next
Return ReturnValue
End Function
Aren't mapped drives particular to the user that is running the net command?
Your asp.net page usually runs under a different identity to the current user's. This means that your code might possibly map the network path successfully the first time you run it. Then when you run it the second time you will get that error.
But then you are looking in vain to delete the mapping for that letter in your cmd window since the drive was not mapped via your user identity (under which your cmd window is running after all)
Then there's also the permissions needed to run the net command, although that might have thrown a different error.

ASP 3.0 Declare ADO Constants w/out Including ADOVBS.inc

I've written a simple form handler script using ASP3.0/VBScript and would like to add the inputted data (via the web) to an Access database located on my server. I'm using the OLEDB method to connect like so:
Cst = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" & _
"DATA SOURCE=" & Server.MapPath("DataBase.mdb")
Dim Conn
Set Conn = CreateObject("ADODB.Connection")
Conn.Mode = 3
Conn.Open Cst
Blah Blah Blah...
I currently have a file named ADOVBS.inc included at the top but would like to ditch it because I feel it's inefficient and wasteful. I'd like to define the constants as I need them- but I don't know how. What ADO constants would I need to define and where? The book that I'm using basically says "forget about that- pound include those 400 or so boogers in there and don't ask stupid questions!"
Any specific examples/help would be greatly appreciated.
Thanks,
you have a couple of options to choose from. You can reference the metadata library in your page ( or in your global.asa file ) with
<!--
METADATA
TYPE="TypeLib"
NAME="Microsoft ActiveX Data Objects 2.5 Library"
UUID="{00000205-0000-0010-8000-00AA006D2EA4}"
VERSION="2.5"
-->
or
you can simply copy a few constants from the adovbs file into your page to cover your needs. For example
Const adCmdText = 1 'Evaluate as a textual definition
Const adCmdStoredProc = 4 'Evaluate as a stored procedure
Of course that the answer is "Forget about that- pound include those 400 or so boogers in there and don't ask stupid questions!" :)
But since you insist:
The best way is to encapsulate all data access function in one .ASP
Let's call it dbHelper.asp
Then put all the DB functions in there, like:
''// run a query and returns a disconnected recordset
Function RunSQLReturnRS(sqlstmt, params())
On Error Resume next
''//Create the ADO objects
Dim rs , cmd
Set rs = server.createobject("ADODB.Recordset")
Set cmd = server.createobject("ADODB.Command")
''// Init the ADO objects & the stored proc parameters
cmd.ActiveConnection = GetConnectionString()
cmd.CommandText = sqlstmt
cmd.CommandType = adCmdText
collectParams cmd, params
''//Execute the query for readonly
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
If err.number > 0 then
BuildErrorMessage()
exit function
end if
''//Disconnect the recordset
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Set rs.ActiveConnection = Nothing
''//Return the resultant recordset
Set RunSQLReturnRS = rs
End Function
At that point, you know that all you ado constants are in this file and you can start replacing them as wished.
Relevant list of constants can be found here: https://web.archive.org/web/20190225142339/http://www.4guysfromrolla.com:80/ASPScripts/PrintPage.asp?REF=/webtech/faq/beginner/faq7.shtml
I'll copy it here as well:
'---- CursorTypeEnum Values ----
Const adOpenForwardOnly = 0
Const adOpenKeyset = 1
Const adOpenDynamic = 2
Const adOpenStatic = 3
'---- CursorOptionEnum Values ----
Const adHoldRecords = &H00000100
Const adMovePrevious = &H00000200
Const adAddNew = &H01000400
Const adDelete = &H01000800
Const adUpdate = &H01008000
Const adBookmark = &H00002000
Const adApproxPosition = &H00004000
Const adUpdateBatch = &H00010000
Const adResync = &H00020000
Should be enough for inserting/selecting/updating records in database.

Resources