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) & "}"
Related
What i have so far is a Query that opens the Microsoft Access Application but i would like to open and run a sql query itself and close the application. the query like
SELECT S2iOSGISAcquisitionCSV.Agencia,
S2iOSGISAcquisitionCSV.Mercado,
S2iOSGISAcquisitionCSV.[Nome Produtor],
S2iOSGISAcquisitionCSV.Dispositivo
FROM S2iOSGISAcquisitionCSV;
where can i put that statement ? thank you
Dim sAcc
Dim sFrontEnd
Dim sSec
Dim sUser
Dim objShellDb
Dim sComTxt
Dim rs
sAcc = "C:\Program Files\Microsoft Office 15\root\office15\msaccess.exe"
'"C:\Program Files\Microsoft Office\OFFICE11\msaccess.exe"
sFrontEnd = "C:\Users\User\Desktop\TABELA_DE_DADOS.accdb"
Set objShellDb = CreateObject("WScript.Shell")
'Set rs = createObject("SELECT* FROM S2iOSGISAcquisitionCSV");
sComTxt = chr(34) & sAcc & chr(34) &_
" " & chr(34) & sFrontEnd & chr(34)
if isNull(sSec)=False AND sSec<>"" Then
sComTxt = sComTxt & " /wrkgrp " & chr(34) & sSec & chr(34)
End if
if isNull(sUser)=False AND sUser<>"" Then
sComTxt = sComTxt & " /user " & sUser
End if
objShellDb.Run sComTxt
' rs.Run sComTxt
I wish to use thing string useing Shell() function to automate an upload of an excel file to an ftp server whenever a save occurs:
strShell = "C:\Program Files\WinSCP\WinSCP.exe /console /command " & Chr(34) & "option batch on" & Chr(34) & " " & Chr(34) & "open user:pass#localhost" & Chr(34) & " " & Chr(34) "put " ThisWorkbook.Path & "/" & ThisWorkbook.Name & "/home/User/Directory" & Chr(34) & " " & Chr(34) "exit" & Chr(34)
For some reason I get syntax error for this string. My knowledge in VBA isn't wide but I going over MSDNfor the last couple of hours didn't seem to help at all.
I suspect that you need more quotes for file paths containing spaces. Something like
strShell = "'C:\Program Files\WinSCP\WinSCP.exe' /console /command " & Chr(34) &....
you also forgot some "&" like on the 3dr line:
Chr(34) & "put " & ThisWorkbook.Path &
Again on that line, you might need to surround filenames with quotes !
Your best help would be to include a Debug.Print strShell and watch the result in the VBE Immediate Window (^G)
According to the documentation for WinSCP, you need to add the double quotes around your commands. For Example:
WinSCP.exe /command "option batch abort"
So in VBA that would be: "WinSCP.exe /command ""option batch abort"""
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
Hi Is there any easier way to write multiple lines in a file which has things like quotes in and other things like that or is the only way to do it like this
Dim objwriter As New System.IO.StreamWriter(AppsDir & "EthIPChanger.bat")
objwriter.WriteLine("#echo off")
objwriter.WriteLine("netsh interface ip set address name=""" & "Local Area Connection""" & " static " & TB_EthIPAddress.Text & " " & TB_EthSubnetMask.Text & " " & TB_EthDefaultGateway.Text & " 1")
objwriter.WriteLine("netsh interface ip set dns """ & "Local Area Connection""" & " static " & TB_EthDNS1.Text)
objwriter.WriteLine("ipconfig /all > """ & AppsDir & "NetworkInfo.txt""")
objwriter.WriteLine("echo hi > """ & AppsDir & "CheckLen.txt""")
objwriter.Close()
I know if you are using python you can do """ and then do anything inside that and end it with """
Does anything like that exist in vb.net?
thanks
If you use objwriter.Write - then you can supply the vbcrlf yourself - and then you can put multiple 'lines' in one write statement.
For example:
Dim str2write As string
str2write = "firstline" and Chr(34) & Chr(34) & vbcrlf
str2write &= Chr(34) & "second line" and Chr(34) & vbcrlf & vbcrlf
objwriter.write(str2write)
objwriter.close()
You can try with StringBuilder:
Dim objwriter As New System.IO.StreamWriter(AppsDir & "EthIPChanger.bat")
Dim textToWrite As New System.Text.StringBuilder
With textToWrite
.Append("#echo off")
.AppendFormat("netsh interface ip set address name={0}Local Area Connection{0} static {1} {2} {3} 1", Chr(34), TB_EthIPAddress.Text, TB_EthSubnetMask.Text, TB_EthDefaultGateway.Text)
.AppendFormat("netsh interface ip set dns {0}Local Area Connection{0} static {1}", Chr(34), TB_EthDNS1.Text)
.AppendFormat("ipconfig /all > {0}{1}{2}{0}", Chr(34), AppsDir, TB_EthDNS1.Text)
.AppendFormat("echo hi > {0}{1}{2}{0}", Chr(34), AppsDir, CheckLen.Text)
End With
objwriter.WriteLine(textToWrite.ToString)
objwriter.Close()
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.