VBS script to parse a csv, get data and move AD object - parsing

I am quite new in vbs and I would like some of your help on this script.
Basically I need a script that will get my current computername, look into a csv file to get the new related computername and then use that new name to move the corresponding account in the AD to a new OU.
I already know how to get my current computername and how to move an object to a new OU, these are things I have already done, but I am really not confident about parsing the csv looking for the new computername based on my current one.
The new name is the value just after the current name in the csv file. Only separted by a coma.
Edit 1
I tried your solution but as stated in the comments I think there are some things that I don't get. I might misuse the recordset or do not know how to retrieve the information from it. Here is my full script so you can see what I am doing:
'Get the old/current computername
Set wshShell = WScript.CreateObject( "WScript.Shell" )
OldComputerName = wshShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )
'Parse the xml file to get the related new computername
Dim CONNECTION : Set CONNECTION = CreateObject("ADODB.CONNECTION")
Dim RECORDSET : Set RECORDSET = CreateObject("ADODB.RECORDSET")
CONNECTION.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test\;Extended Properties=""text;HDR=YES;FMT=Delimited"""
RECORDSET.Open "SELECT NewComputerName FROM ComputerList.csv WHERE ComputerName = '& OldComputerName'", CONNECTION, 3, 3
'Move the new computername in the target AD to a new OU
Dim NewComputerName
Dim OldLocation
NewComputerName = RECORDSET
OldLocation = "LDAP://CN=" & NewComputerName & ",OU=Staging,OU=Workstations,DC=contoso,DC=lab"
Set objNewOU = GetObject("LDAP://OU=Migration,OU=Workstations,DC=contoso,DC=lab")
Set objMoveComputer = objNewOU.MoveHere(OldLocation, vbNullString)
' It does not work as it said Error: Wrong number of arguments or invalid property assignment pour la ligne:
' OldLocation = "LDAP://CN=" & NewComputerName & ",OU=Staging,OU=Workstations,DC=contoso,DC=lab"
Thanks a lot for your help ! :)

You can use ADO to read CSV (and other delimited) files. The gory details are discussed in this article. Sample code for reading a simple CSV file using VBScript is as follows:
Note: the CSV file needs a header line in order for ADO to use column names:
ComputerName,NewComputerName
Computer #1,Other Computer #1
Computer #2,Other Computer #2
Computer #3,Other Computer #3
VBScript Code:
option explicit
dim CONNECTION : set CONNECTION = CreateObject("ADODB.CONNECTION")
dim RECORDSET : set RECORDSET = CreateObject("ADODB.RECORDSET")
CONNECTION.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Folder\Containing\CSV\File\;Extended Properties=""text;HDR=YES;FMT=Delimited"""
RECORDSET.Open "SELECT * FROM data.csv WHERE ComputerName = '" & OldComputerName & "'", CONNECTION, 3, 3
' //// For testing \\\\
WScript.Echo RECORDSET.Source
' \\\\ For testing ////
if RECORDSET.EOF then
WScript.Echo "Record not found"
WScript.Quit
else
dim NewComputerName : NewComputerName = RECORDSET("NewComputerName") & ""
WScript.Echo NewComputerName
end if
Note that this code might not work on 64-bit OS -- not directly. You must run 32-bit version of CScript/WScript like so:
%windir%\SysWoW64\cscript c:\Path\To\test.vbs

Ok the script works perfectly now thanks to your modifications ! :)
But I've got one more trouble, it seems that I cannot open the csv file in the FROM clause when this file have - in the name.
Like : CONTOSO-US-ComputerList.csv I get the error Syntax error in FROM clause
But when I use a file name without dashes there is no problem.
I know it is a detail but I have no choice than having a file with dashes in the name :/
Thanks again for your help :) Very much appreciated !!
EDIT:
Nevermind I found the solution thanks to the scriptingguys !
The request now looks like this:
strFile = "[CONTOSO-ComputerList.csv]"
RECORDSET.Open "SELECT * FROM " & strFile & " WHERE ComputerName = '" & OldComputerName & "'", CONNECTION, 3, 3

Related

How fetch image from database using Stream Classic?

I successful Adding image in SQL database using Stream class in that code
Public CN As New ADODB.Connection
Public Emp As New ADODB.Recordset
Public ST As New ADODB.Stream
Emp.Open("Employees", CN, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic)
Emp.AddNew()
ST.Open()
ST.Type = ADODB.StreamTypeEnum.adTypeBinary
ST.LoadFromFile(OpenFileDialog1.FileName)
Emp(19).Value = ST.Read
Emp.Update()
ST.Close()
Emp.Close()
this operation is successful but when I retrieve the database using this Code:
Emp.Open("Select * From Employees Where UserName = '" + TXTSearch.Text + "'", CN)
ST.Open()
ST.Type = ADODB.StreamTypeEnum.adTypeBinary
ST.Write(Emp.Fields(19).Value)
ST.SaveToFile("\temp", ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
PICEmployee.Image = Image.FromFile("\temp")
ST.Close()
Emp.Close()
I have a button to show the database grid and it confirm the picture is loaded
but when I tried to fetch the data it stopped in that line
ST.SaveToFile("\temp", ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
says Failed to Write I changed the Path got same error, I open the VB as Administrator got same error.
Tip: I didn't send All my Codes in case if something missing but everything about Stream is here
I like to have simple solution I'm still beginner and Need all Help you can give to me, Thanks

Excel VBA code doesn't work in Open Office (Code copy files from list)

I had some excel VBA code, and it doesn't work in Open Office Calc.
Code in excel copy files from list from different catalog to another.
I don't know macro programming in open office. I read about diffrent declaration, but it really hard for me. What should I change for open office?
I will really grateful for any help.
Sub copyfiles()
Dim xRg As Range, xCell As Range
Dim xSFileDlg As FileDialog, xDFileDlg As FileDialog
Dim xSPathStr As Variant, xDPathStr As Variant
Dim xVal As String
On Error Resume Next
Set xRg = Application.InputBox("Wybierz pliki do skopiowania:", "KuTools For Excel", ActiveWindow.RangeSelection.Address, , , , , 8)
If xRg Is Nothing Then Exit Sub
Set xSFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
xSFileDlg.Title = "Wybierz folder z którego kopiuję:"
If xSFileDlg.Show <> -1 Then Exit Sub
xSPathStr = xSFileDlg.SelectedItems.Item(1) & "\"
Set xDFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
xDFileDlg.Title = "Wybierz folder do którego kopiuję:"
If xDFileDlg.Show <> -1 Then Exit Sub
xDPathStr = xDFileDlg.SelectedItems.Item(1) & "\"
For Each xCell In xRg
xVal = xCell.Value
If TypeName(xVal) = "String" And xVal <> "" Then
FileCopy xSPathStr & xVal, xDPathStr & xVal
End If
Next
End Sub
The code needs to be entirely rewritten. OpenOffice Basic is a completely different programming platform from MS Office VBA.
One good place to start learning OpenOffice Basic is http://www.pitonyak.org/oo.php.

ADODB.recordset AddNew/Update Method Error -2147467259 (80004005)

I've been getting the following error when trying to write data from my HMI to a MSSQL db using ADODB.recordset with the AddNew/Update Methods. I'm using SQL Server Native Client 11.0 for the connection and Microsoft ActiveX Data Objects 6.0 Library.
Generic VBA Error -2147467259[Microsoft][SQL Server Native Client 11.0][SQL Server]FNGCO,ABCDEFGHI,1000003,2017-04-14,17:00:36:187,FOAML1,A1,,1
If it works this code should write each value to each column in the MSSQL database. I've got very similar code working in another part of the application, but I can't seem to get this working.
What I Have Tried So Far:
Checked against code running in another HMI, everything between the two appears to be identical.
Tried the same connection string with another ADODB.recordset and added data to the db with AddNew/Update.
Checked the database table to make sure all of the data I'm trying to enter fits the column (its not null, max characters not exceeded, etc...)
Here is my code:
On debug, the code halts at sqlrs1.Update.
Option Explicit
Const strSQLNCLI11_1 = "Driver={SQL Server Native Client 11.0};Server=TESTDEMO\SQLEXPRESS;Database=RABPI;Uid=sa;Pwd=testdemo;QueryTimeout=0"'
Private Sub Button1_Released()
On Error GoTo ErrHandler
Dim sqlcn2 As ADODB.Connection
Dim sqlrs1 As ADODB.Recordset
Set sqlcn2 = New ADODB.Connection
Set sqlrs1 = New ADODB.Recordset
sqlcn2.Open strSQLNCLI11_1
sqlrs1.Open "Select * from AT_BW_PRDN ;", _
sqlcn2, adOpenDynamic, adLockPessimistic
sqlrs1.AddNew
sqlrs1("AT_BW_BUS_UNIT") = "FNGCO"
sqlrs1("AT_BW_PID") = "ABCDEFGHI"
sqlrs1("AT_BW_PRDN_AREA") = "FOAML1"
sqlrs1("AT_BW_SHIFT") = "A1"
sqlrs1("AT_BW_ITEM_ID") = "1000007"
sqlrs1("AT_BW_REL") = 0
sqlrs1.Update
Exit Sub
ErrHandler:
LogDiagnosticsMessage "Generic VBA Error" & Err.Number & " " & Err.Description, ftDiagSeverityError, ftDiagAudienceOperator
Set sqlcn2 = Nothing
Set sqlrs1 = Nothing
Exit Sub
End Sub
UPDATE:
I made a test database and re-created the tables I'm trying to write to without any constraints or triggers and the code functioned properly.

Calling Oracle 11g Stored Procedure Using VB6

I have a simple Oracle procedure as below. I am trying to call the procedure using VB6 and extract the output from the procedure.
CREATE OR REPLACE PROCEDURE EXTRACTTXN (reportdate IN DATE, p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR
SELECT
TXN_ID,
TXN_ACTION,
TXN_STATUS,
TXN_DATE,
TXN_AMOUNT
FROM TRANSACTIONS
WHERE
TRUNC(TXN_DATE) = TRUNC(reportdate)
END EXTRACTTXN;
The VB Code goes like this;
Sub FetchTransactions(ByVal ReportDate As Date, cnnMine as ADODB.Connection)
On Error GoTo TrapErr
Dim cmdMine As ADODB.Command, rsMine As ADODB.Recordset
cmdMine.ActiveConnection = cnnMine
cmdMine.CommandTimeout = 300
cmdMine.CommandType = adCmdStoredProc
cmdMine.CommandText = "EXTRACTTXN"
cmdMine.Parameters.Append cmdMine.CreateParameter("reportdate", adDate, adParamInput, , Format(ReportDate, "DD-MMM-YYYY"))
cmdMine.Parameters.Append cmdMine.CreateParameter("p_recordset", adVariant, adParamOutput)
Set rsMine = cmdMine.Execute
Do While rsMine.EOF
Debug.Print rsMine!TXN_ID, rsMine!TXN_ACTION, rsMine!TXN_STATUS, rsMine!TXN_DATE, rsMine!TXN_AMOUNT
rsMine.MoveNext
Loop
rsMine.Close
Exit Sub
TrapErr:
MsgBox Err.Number & " - " & Err.Description, vbExclamation, App.ProductName
End Sub
While running the code, I get the following Error:
ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'EXTRACTTXN'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
Anything wrong in my code? Appreciate help.
Niz
The problem is that the types of your arguments as specified in your VB code don't match the types of the arguments as specified in your PL/SQL code. The most likely reason for your problem is that the Format function in VB6 returns a Variant type, not a Date type, and that Variant type is set to be a String type. See this for more information on the Format function.
In case you don't know, the way that Variant variables are set up is that they reserve 8 bytes to tell the world what the actual variable type is. So, if you pass your ReportDate in after applying the Format function to it, it will be a Variant that's telling the world it's a string. It's possible that the ADO Parameter object is happy with that (SQL Server is happy to parse properly-formatted strings into Date fields, after all) and Oracle isn't. In my limited experience with Oracle, I've found that it's fussier about that sort of thing than SQL Server.
Try losing the Format function and see if you at least get a different error.
I have managed to get this sorted. It's mainly due to me being new to Oracle and its complexity.
Here are the changes I made;
Stored Procedure Changes. Note that I have changed TRUNC(reportdate, 'DD') on the Where clause.
CREATE OR REPLACE PROCEDURE EXTRACTTXN (reportdate IN DATE, p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR
SELECT
TXN_ID,
TXN_ACTION,
TXN_STATUS,
TXN_DATE,
TXN_AMOUNT
FROM TRANSACTIONS
WHERE
TRUNC(TXN_DATE) = TRUNC(reportdate, 'DD')
END EXTRACTTXN;
VB Code Changes (Note that I have change the CommandText within parenthesis with a Call, removed the parameter name, changed the date format to DD/MMM/YYYY and removed the output parameter)
Sub FetchTransactions(ByVal ReportDate As Date, cnnMine as ADODB.Connection)
On Error GoTo TrapErr
Dim cmdMine As ADODB.Command, rsMine As ADODB.Recordset
cmdMine.ActiveConnection = cnnMine
cmdMine.CommandTimeout = 300
cmdMine.CommandType = adCmdStoredProc
cmdMine.CommandText = "{ call EXTRACTTXN}"
cmdMine.Parameters.Append cmdMine.CreateParameter(, adDate, adParamInput, , Format(ReportDate, "DD/MMM/YYYY"))
Set rsMine = cmdMine.Execute
Do While rsMine.EOF
Debug.Print rsMine!TXN_ID, rsMine!TXN_ACTION, rsMine!TXN_STATUS, rsMine!TXN_DATE, rsMine!TXN_AMOUNT
rsMine.MoveNext
Loop
rsMine.Close
Exit Sub
TrapErr:
MsgBox Err.Number & " - " & Err.Description, vbExclamation, App.ProductName
End Sub
The above worked perfectly.
Regards, Niz

Visual Basic 2010 connecting to my database

Private Sub OK_Click(sender As System.Object, e As System.EventArgs) Handles OK.Click
If TextBox1.Text = "1234" Then
' This is the connection. You have to have this exact string, except "E:\Documents\notekeeper.mdb" will be the path to your thing instead
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=N:\Visual Studio 2010\Projects\Maths System Aid\Maths System Aid\Database7.mdb;User=;Password=;")
Try
conn.Open()
Catch ex As Exception
MsgBox("Cannot open database")
End Try
' The SQL statement / command
Dim cmd = New OleDbCommand("Insert INTO Student ([First Name], [Surname], [Username], [Password]) VALUES "("" & TextBox5.Text & "," & TextBox4.Text & "," & TextBox3.Text & "," & TextBox2.Text & "" & ")"), conn)
cmd.ExecuteNonQuery() ' Use ExecuteReader() to execute SELECT statements, but ExecuteNonQuery() for others
' Basically, the reader is like an array of all of the records that have been returned by the database
Me.Close()
StudentLogin.Show()
Else
MsgBox("Enter The Correct Confirmation code")
End If
End Sub
my problem is that it will not find my database file. I have followed the path and it is correct. Any ideas of what is the problem?
I haven't done this in quite some time but at the top of your form you should be running some imports firstly
imports system.data
Then you should define rather like this:
dim conn as new oledb.oledbconnection
Another issue I noticed in your code is that you're using the Jet provider which if memory serves correctly only works with the new databases using the .accdb extension. Try to change it to an accdb in access.. I'll go over it quick and see what I can conjure up. Hopefully that helps at least. The alternative provider if you run into issues :
("Provider=Microsoft.ACE.OLEDB.12.0.......
Is this path a local disk or a network disk? is it on another computer or a mapped network drive?
The way I connect is
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = C:\data\database.mdb;Jet OLEDB:Database Password=******;"
con.ConnectionString = dbProvider & dbSource
con.open()
con.close()
This should work perfect but use your path and password if you have one

Resources