How to call a vb method from command line? - vb.net

Im trying to call a simple VB sub from windows task scheduler, the vb script is found inside a very large project so I have created a new item inside the project just to test the execution of the script. For now im just trying to return a simple string so that the process will go like this and this is also how I am going to be debugging and testing this:
Windows Task Scheduler > cmd line > .vb > sub/method
This is the test class I am working with for now.
Public Class clsSchedule
Public Sub RunTasksFromCommandLine(ByVal lstrArgs() As String)
Try
For i As Integer = 1 To lstrArgs.Length - 1 Step 1
lstrProcessKey = lstrArgs(i).Trim("-"c).Trim("/"c).ToUpper
Next i
End Try
End Sub
End Class

If you want to execute VBScript code from command line you can use mshta like in this example:
mshta vbscript:Execute("Msgbox(""Are you sure?"",vbYesNo+vbInformation,"""")(window.close)")
you can also check this - Is it possible to embed and execute VBScript within a batch file without using a temporary file?
If you want to execute VB.NET from command line... then may be you try with powershell codeblocks. If you want to embed VB.NET code into batch file you can use msbuild inline tasks or to use the .net compiler to create self-compiling script.

Related

Is there a way to write a command directly by code in the immediate window?

I'm trying to save all lines from the output window into a log-file. That works fine when I enter the command directly into the immediate window. However, I need a way to enter the command line by code.
I searched for a way to enter a command into the immediate window so the log-file I want will be created and filled with data. That's not happening and I don't know if this is even possible. Searching Google didn't help so far.
My command line is:
> Tools.LogCommandWindowOutput C:\Users\user\AppData\test.log
And I try to get it into the immediate window by
Debug.Print("> Tools.LogCommandWindowOutput C:\Users\user\AppData\test.log")
The command line works fine when put directly into the immediate window (either by typing it in or pasting it in). When I try to do that by code, nothing happens. Is there a way to do that or do I have to try another option and if so, what option is it?
EDIT:
I've tried the solution provided by RobertBaron with the following changes:
'Dim dummy = $"C:\\log\\outputfileAddOn_{Date.Now:yyyy_MM_dd_HH_mm_ss}.log"
'cmdWindow.SendInput($"Tools.LogCommandWindowOutput {dummy}", True)
cmdWindow.SendInput("Tools.LogCommandWindowOutput C:\log\outputfile_AddOn.log", True)
(I want a new file to be written every time, so I tried to add the date at the end to have unique file names)
It creates the file but doesn't log anything in it. What do I do wrong?
Another solution I have found was to add a command parameter in project-properties-debug-command parameter:
> C:\log\outputfile.log
This creates the file and inserts all of the data from the output window. The only problem that I have now is that this file will be overwritten every time the program is started. Is there a way I can set the logging from the second, third, … start at the end of the file? (adding /on at the end of the command Parameter didn't help) Or can I provide something like "outputfile_yyyy_MM_dd_HH_mm_ss.log" (for example: outputfile_2019_07_23_15_47_45.log)?
Thank you for your help!
You need to create a Visual Studio Extension project.
Add a new Custom Command item to the VSIX project.
This will create the Command1.vb. This is where you implement the code that you want to execute inside Visual Studio. The code executes whenever you select the entry Invoke Command1 from the Tools menu.
At the bottom of the Command1.vb file, there is the Execute() Sub. It displays a message just to show that the command is working. You can remove this eventually. But for now, just run the project. Another instance of Visual Studio will start. This is where you can test and debug your code. Once the second instance of Visual Studio has started, go to its Tools menu, and select the Invoke Command1 entry. A message box will display. Stop execution.
Now we want to modify the Execute() Sub so that our code gets executed when Invoke Command1 is selected. Here is the Sub that will execute the command that you want. Add it to the Command1 class.
Public Sub ExecCommandWindow()
Dim dte As EnvDTE.DTE = CType(Microsoft.VisualStudio.Shell.Package.GetGlobalService(GetType(Microsoft.VisualStudio.Shell.Interop.SDTE)), EnvDTE.DTE)
Dim cmdWindow As CommandWindow = CType(dte.Windows.Item(EnvDTE.Constants.vsWindowKindCommandWindow).Object, CommandWindow)
'Display some text in the command window
cmdWindow.OutputString("Executing command from the automation OM...")
'Send some command strings to the command window and execute them...
'This command will start logging all input/output in the command window to the specified file
cmdWindow.SendInput("Tools.LogCommandWindowOutput cmdwindow.log", True)
''Open a file in a code editor:
'' 1. We use an alias, 'of', for the File.OpenFile command
'' 2. This command takes quote-delimited parameters (in this case,
'' the name of the editor to load the file in)
'Dim cmd As String = "of "
'cmd = (cmd + """""C:\Contoso\ContosoCommonFramework\Integration.cs""""")
'cmd = (cmd + "/e:""""CSharp Editor""""")
'cmdWindow.SendInput(cmd, True)
'cmdWindow.SendInput("Edit.Find MessageTrxId", True)
'Turn off logging
cmdWindow.SendInput("Tools.LogCommandWindowOutput /off", True)
End Sub
Change the Execute() Sub to call ExecCommandWindow().
You can change the name of the command by changing its title in the Command1 class.
The Visual Studio extension needs to be installed by each user. Just distribute the .vsix file. To install, double-click it.
It's not the best solution, but it works (for now):
adding
>> C:\log\outputfile.log
(with two '>' before the path for the log file) attaches every log at the end of the file. So I get all Information and nothing is being overwritten.
As I want to know if there is a better solution, I will keep this thread open if that is permitted.

Using VB.net - pull a file from GitLab

As the title implies, I'm looking for a way to pull specific file(s) from a private GitLab repo using VB.net (2017).
I have an application that I'm writing which will call certain PowerShell scripts. I have a few other users working with me writing the scripts, so we are using GitLab as the repository for these.
We want the application to pull the latest version of the scripts from GitLab when the application opens, then from within the app, call the scripts.
I have everything done, with the exception of downloading the scripts from GitLab.
So I'm posting an answer here just in case anyone else has the same question. I was actually able to get this done pretty easily.
First, you have to generate a private token. Plenty of walk-throughs for that, so I won't go into that here.
Next, you have to get the address of raw file that you want to download. You can get this by opening the file in GitLab, then there's a button on the top right of the window to "Open Raw", which opens the raw page.
See Image Here
Grab the url from the address bar. Once you have that, you have all the pieces you need to curl the file down using VB.net.
You have to take the address of the raw file, let's say that was "https://gitlab.com/CompanyName/raw/master/folder/filename.ps1", you then append ?, with your private token so it looks like this: "https://gitlab.com/CompanyName/raw/master/folder/filename.ps1?private_token=MyPrivateToken" and use a curl (through powershell) to get it.
I already had a function in my code to run powershell scripts (with code I believe I got off this site...forgot the exact location), which was like this:
Private Function RunScript(ByVal scriptText As String) As String
' Takes script text as input and runs it, then converts
' the results to a string to return to the user
' create Powershell runspace
Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
' open it
MyRunSpace.Open()
' create a pipeline and feed it the script text
Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline()
MyPipeline.Commands.AddScript(scriptText)
' add an extra command to transform the script output objects into nicely formatted strings
' remove this line to get the actual objects that the script returns. For example, the script
' "Get-Process" returns a collection of System.Diagnostics.Process instances.
MyPipeline.Commands.Add("Out-String")
' execute the script
Dim results As Collection(Of PSObject) = MyPipeline.Invoke()
' close the runspace
MyRunSpace.Close()
' convert the script result into a single string
Dim MyStringBuilder As New StringBuilder()
For Each obj As PSObject In results
MyStringBuilder.AppendLine(obj.ToString())
Next
' return the results of the script that has
' now been converted to text
Return MyStringBuilder.ToString()
End Function
Now, I can call a curl command with that function like this:
RunScript("curl https://gitlab.com/CompanyName/raw/master/folder/filename.ps1?private_token=MyPrivateToken -outfile C:\DownloadFolder\FileName.ps1")
That's it! Anytime you need to get a file, you can simply get the location of the raw file and modify the function call to reflect the new address and grab it.

Call .reg File from Excel-VBA script

I want to call a .reg File out of my VBA script. I'm using Office/Excel 2013.
I know Excel can't run these files by itself, so i need to call the file via shell. The code i wrote doesn't work:
Sub deactivateHyperlinkWarnings()
Dim x
x = Shell("cmd /C C:\TEMP\DisableHyperlinkWarnings.reg")
End Sub
I found this piece of code somewhere on the web, but its not working. I don't even get an error message. The .reg File is located in C:\TEMP
What do i need to write to make it work?
Plus: Is it possible to suppress the MessageBoxes that are displayed when i run the .reg-File? When i start the file manually, i need to Hit "OK" like 3 Times. The people who are working with the Excelsheet later on shouldn't be seeing these things.
Instead of running cmd try to run reg. So in your case it should be x = Shell("reg import C:\TEMP\DisableHyperlinkWarnings.reg")
More info here

How to use "ReSharper.ReSharper_SilentCleanupCode" in a vs2010 macro?

I am trying to build a macro that formats all modified files before saving them.
Public Module ReformatAndSave
Sub SingleFile()
DTE.ExecuteCommand("ReSharper.ReSharper_SilentCleanupCode")
DTE.ActiveDocument.Save()
End Sub
Sub AllFiles()
For Each doc As Document In DTE.Documents
If Not doc.Saved Then
doc.Activate()
DTE.ExecuteCommand("ReSharper.ReSharper_SilentCleanupCode")
DTE.ActiveDocument.Save()
End If
Next
End Sub
End Module
This results in an error
Error HRESULT E_FAIL has been returned from a call to a COM component.
It works when I use this instead:
DTE.ExecuteCommand("ReSharper.ReSharper_CleanupCode")
I could live with this solution for a single file but choosing the profile when saving all files is annoying.
I use ReSharper 6.1.1000.82. This bug seems to be rather old: http://youtrack.jetbrains.com/issue/RSRP-179846
Is it possible to work around this bug by collecting all modified files and the execute the working CleanUpCode command once for all the files.
I can manually select many files and execute CleanUp on these files, manually. I would like to do this automatically on all modified files when saving them.
The solution is so simple.
All I had to do is replacing this
DTE.ExecuteCommand("ReSharper.ReSharper_CleanupCode")
with this
DTE.ExecuteCommand("ReSharper_SilentCleanupCode")
This doesn't work!
DTE.ExecuteCommand("ReSharper.ReSharper_SilentCleanupCode")

Trying to create a batch file from VB 2010 Express

Why does a batch file run when I create it in Notepad, but not when I create it in my VB code?
Dim strStartFile As String = "C:\Documents and Settings\All Users\StartMenu\Programs\Startup\Starter.bat"
If Not File.Exists(strStartFile) Then
Dim strBatLine1 As String = "cd C:\Progra~1\Applic~1 && start Application.exe"
My.Computer.FileSystem.WriteAllText(strStartFile, strBatLine1, False)
SetAttr(strStartFile, FileAttribute.Normal)
End If
It creates the file just fine. It looks exactly the same as the handmade version, it just won't launch the exe when double clicked. I've tried appending CR+LF, vbCrLf, but no go.
There is an inherent problem when trying to launch the exe directly from Startup, it runs it from that directory and can't find the related files (in the Application directory) so the cd is necessary.
Using VB 2010 Express. Thanks in advance for your help!
You probably need to pass in the Systems ANSI CodePage, because you are executing the file from cmd.exe
My.Computer.FileSystem.WriteAllText(strStartFile, strBatLine1, False, System.Text.Encoding.Default);