I've searched SO, and I can find plenty of examples of running a PowerShell script from VBA, but I can't find any examples of just running a simple command.
For example, this works:
Dim retval As Variant
retval = Shell("PowerShell ""C:\MyScript.ps1""", vbNormalFocus)
But this does not:
Dim retval As Variant
Dim pscmd As String
pscmd = "PowerShell " & _
Chr(34) & "Get-ScheduledTask" & _
" -TaskName " & Chr(34) & "My Task" & Chr(34) & _
" -CimSession MYLAPTOP" & Chr(34)
retval = Shell(pscmd, vbNormalFocus)
Debug.Print pscmd
'pscmd = PowerShell "Get-ScheduledTask -TaskName "My Task" -CimSession MYLAPTOP"
I know I could write the PS command to a file, execute it as a script, and then delete the file, but that does not seem to be very elegant.
To run an inline Powershell command, you'll probably need to use the -Command param and surround your statement with quotes. It'll also be easier if you use single quotes within the command.
Try this out:
pscmd = "PowerShell -Command ""{Get-ScheduledTask -TaskName 'My Task' -CimSession MYLAPTOP}"""
Haven't tested but this but the execution policy may be a factor.
pscmd = "PowerShell -NoProfile -NoLogo -ExecutionPolicy Bypass -Command {" & _
Chr(34) & "Get-ScheduledTask" & _
" -TaskName " & Chr(34) & "My Task" & Chr(34) & _
" -CimSession MYLAPTOP" & Chr(34) & "}"
I have an Excel macro that has an Oracle database connection. When I call the macro, it fills out user name and password but not service name. User has to enter service name manually every time.
How can I specify it in the connection string?
Connection string:
CN.ODBCConnection.Connection = _
"ODBC;DRIVER={Oracle in OraClient11g_home2};" & _
"UID=" & inputUser & ";PWD=" & inputPassword & ";" & _
"HOST=" & inputHost & ";PORT=1521;DB=" & inputHost & ";" & _
"DefaultIsolationLevel=READUNCOMMITTED"
Excel prompt:
Found it. It's DBQ
New connection string:
CN.ODBCConnection.Connection = _
"ODBC;DRIVER={Oracle in OraClient11g_home2};" & _
"DBQ=" & inputHost & ";UID=" & inputUser & ";PWD=" & inputPassword & ";" & _
"HOST=" & inputHost & ";PORT=1521;DB=" & inputHost & ";" & _
"DefaultIsolationLevel=READUNCOMMITTED"
It depends on your driver, check this out
But without a config file, you have to specify the options in the connection string.
Give this a try,
CN.ODBCConnection.Connection = _
"ODBC;DRIVER={Oracle in OraClient11g_home2};" & _
"SERVICE_NAME=" & inputHost & ";UID=" & inputUser & ";PWD=" & inputPassword & ";" & _
"HOST=" & inputHost & ";PORT=1521;" & _
"DefaultIsolationLevel=READUNCOMMITTED"
Also, make sure inputHost should be used in both cases where it is currently. One should be an instance of a server with the other being the database within it.
I have written a vbscript based .hta installer to install PhoneGap/Cordova automatically with all the pre-requisites(ant/jdk/bada sdk etc). Its almost done but I am stuck at the part where I need to download JDK directly.
If you copy paste this (long) line in commandprompt and it works
wget --header "Cookie: gpw_e24=http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html;" ""http://download.oracle.com/otn-pub/java/jdk/7u17-b02/jdk-7u17-windows-i586.exe -O jdk.exe
It will download JDK directly , absolutely fine .
When you paste the code snippet in notepad e.g and save as .vbs and run it then it doesnt work
Set objShell = CreateObject("WScript.Shell")
objShell.CurrentDirectory = "c:\"
'inQuotes function just puts quotes around the command parameters
objShell.Run inQuotes(WorkingDir & "\wget.exe") & " " & " --header " & inQuotes("Cookie: gpw_e24=http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html; ") & "http://download.oracle.com/otn-pub/java/jdk/7u17-b02/jdk-7u17-windows-i586.exe" & " -O" & " " & inQuotes("jdk.exe"),1,True
Function inQuotes(toQuote)
'return with quotes around the toQuote parameter
inQuotes = chr(34) & toQuote & chr(34)
End Function
Somewhere in teh objShell.Run line there is a problem and wget isn't downloading the jdk ...
Will really appreciate any help
thank you :)
Is your variable WorkingDir is defined? If I put one echo:
strCmd = inQuotes(WorkingDir & "\wget.exe") & " " & " --header " _
& inQuotes("Cookie: gpw_e24=http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html; ") _
& "http://download.oracle.com/otn-pub/java/jdk/7u17-b02/jdk-7u17-windows-i586.exe" & " -O" & " " & inQuotes("jdk.exe")
WScript.Echo strCmd
I get this:
"\wget.exe" --header "Cookie: gpw_e24=http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html; "http://download.oracle.com/otn-pub/java/jdk/7u17-b02/jdk-7u17-windows-i586.exe -O "jdk.exe"
And this not pass to the original command. Maybe it s'd be like this?
strCmd = "wget.exe --header " _
& inQuotes("Cookie: gpw_e24=http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html;") _
& " " & chr(34) &chr(34) & "http://download.oracle.com/otn-pub/java/jdk/7u17-b02/jdk-7u17-windows-i586.exe" _
& " -O jdk.exe"
WScript.Echo strCmd
i have this huge csv file, it's 4GB, don't know how many rows but 320 columns.
since it can't be open in any program (except using 3rd party programs to split the file into multiple pieces) i'm trying to fins a way to extract the data i need. i only need about 10-15 columns from it.
i saw many solutions on the net (most in vbs) but i couldn't get any of them to work. i'd get errors and i don't know vbs to be able to troubleshoot them.
can anyone help please?
thank you
PS here's one example of the vbs code i found and tried using that i had no luck with.
the original error was "800a01f4 variable is undefined", on the net it was suggested to take out OPTION EXPLICIT. once i do that the next error is "800a01fa class not defined".
in both cases the line giving the error is "Set adoJetCommand = New ADODB.Command"
Option Explicit
Dim adoCSVConnection, adoCSVRecordSet, strPathToTextfile
Dim strCSVFile, adoJetConnection,adoJetCommand, strDBPath
Const adCmdText = &H0001
' Specify path to CSV file.
strPathToTextFile = "C:\Users\natalie.rynda\Documents\Temp\RemailMatch\"
' Specify CSV file name.
strCSVFile = "NPIOld.csv"
' Specify Access database file.
strDBPath = "C:\Users\natalie.rynda\Documents\Temp\RemailMatch\NPIs.mdb"
' Open connection to the CSV file.
Set adoCSVConnection = CreateObject("ADODB.Connection")
Set adoCSVRecordSet = CreateObject("ADODB.Recordset")
' Open CSV file with header line.
adoCSVConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strPathtoTextFile & ";" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited"""
adoCSVRecordset.Open "SELECT * FROM " & strCSVFile, adoCSVConnection
' Open connection to MS Access database.
Set adoJetConnection = CreateObject("ADODB.Connection")
adoJetConnection.ConnectionString = "DRIVER=Microsoft Access Driver (*.mdb);" _
& "FIL=MS Access;DriverId=25;DBQ=" & strDBPath & ";"
adoJetConnection.Open
' ADO command object to insert rows into Access database.
Set adoJetCommand = New ADODB.Command
Set adoJetCommand.ActiveConnection = adoJetConnection
adoJetCommand.CommandType = adCmdText
' Read the CSV file.
Do Until adoCSVRecordset.EOF
' Insert a row into the Access database.
adoJetCommand.CommandText = "INSERT INTO NPIs " _
& "(NPI, EntityTypeCode, ReplacementNPI, EIN, MAddress1, MAddress2, MCity, MState, MZIP, SAddress1, SAddress2, SCity, SState, SZIP, ProviderEnumerationDate, LastUpdateDate, NPIDeactivationReasonCode, NPIDeactivationDate, NPIReactivationDate) " _
& "VALUES (" _
& "'" & adoCSVRecordset.Fields("NPI").Value & "', " _
& "'" & adoCSVRecordset.Fields("Entity Type Code").Value & "', " _
& "'" & adoCSVRecordset.Fields("Replacement NPI").Value & "', " _
& "'" & adoCSVRecordset.Fields("Employer Identification Number (EIN)").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider First Line Business Mailing Address").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Second Line Business Mailing Address").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Business Mailing Address City Name").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Business Mailing Address State Name").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Business Mailing Address Postal Code").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider First Line Business Practice Location Address").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Second Line Business Practice Location Address").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Business Practice Location Address City Name").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Business Practice Location Address State Name").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Business Practice Location Address Postal Code").Value & "', " _
& "'" & adoCSVRecordset.Fields("Provider Enumeration Date").Value & "', " _
& "'" & adoCSVRecordset.Fields("Last Update Date").Value & "', " _
& "'" & adoCSVRecordset.Fields("NPI Deactivation Reason Code").Value & "', " _
& "'" & adoCSVRecordset.Fields("NPI Deactivation Date").Value & "', " _
& "'" & adoCSVRecordset.Fields("NPI Reactivation Date").Value & "')"
adoJetCommand.Execute
adoCSVRecordset.MoveNext
Loop
' Clean up.
adoCSVRecordset.Close
adoCSVConnection.Close
adoJetConnection.Close
If your CSV file is straightforward, without newlines or commas in unexpected places, then the standard *nix tool awk would be useful. It would allow you to easily extract the 15 columns you are looking for to a new CSV file. This blog post gives an explanation how to use it on CSV files.
Suppose that you want to extract columns 1, 3 and 7 from file.csv, then you could do this with the command
awk -F, '{print $1","$3","$7;}' file.csv
Your Windows machine probably does not have awk installed. There are a few options:
You can find it in
MSYS, which basically
provides you with a Unix-like shell environment in Windows. To me, this seems to be the easies way to go.
Another option seems to be Gawk for
Windows, but I
have no experience with that, so no guarantees.
You could try to achieve the same result using the Windows
PowerShell, as explained in this blog
post
-- if you have that available. Again, I have no experience trying that.
Last but not least, you could switch to Linux, for example in a
virtual machine. awk is usually available in *nix environments.
If you are parsing a more awkward CSV file, then check out parse csv file using gawk for a bunch of suggestions.
In the VBE editor
Then find in the List the Microsoft Activex Data Objects Library.
Not sure which version might be appropriate, but probably 6
It seems like your code doesn't know what the ADODB.COMMAND is and this should resolve that.
I only know I was able to copy your code, and was able to step through it successfully, when the reference was set.
Hope this helps explain
i need a code to type and perform commands in cygwin terminal in hidden mode(background) using visual basic, i was using cmd but now i want to use a Linux source code so i must use linux.
i ran cmd in hidden mode successfully but it isn't working with cygwin, here is the cmd code:
Shell("cmd.exe /k tracert -h " & _h & " " & domain.Text & " > temp" & i + 1 & ".txt & exit", AppWinStyle.Hide, True)
so i have tried
Shell(""C:\cygwin\Cygwin.bat -k tracert -h " & _h & " " & domain.Text & " > temp" & i + 1 & ".txt & exit", AppWinStyle.Hide, True)
and
Shell("C:\cygwin\Cygwin.bat")
'SendKeys.Send("tracert -h " & _h & " " & domain.Text & " > temp" & i + 1 & ".txt"))
but this still didn't work where in the second code i still have to press enter in cygwin to process the traceroute and which should be automaticcaly processed, so i hope that i'll find help in here.
Shell("C:\cygwin\Cygwin.bat")
SendKeys.Send("tracert -h " & _h & " " & domain.Text & " > temp" & i + 1 & ".txt"))
SendKeys.Send("{ENTER}")
this is the answer, icase anyone needed this.