The term 'connect-nacontroller' is not recognized as the name of a cmdlet, function, script file, or operable program - vb.net

Doesn't it figure. Moments after I post this, I finally get it to work. I'll post what I did just in case anyone else has this issue in the futures. It's a big oversight for me!
Right before the username line, I added this line:
"Import-Module DataOnTap" & Environment.NewLine & _**
I'm trying to run a PowerShell script from within VB.Net 2010 code. When I run the code in PowerShell, it runs fine. When I run it from within VS2010, I get the error:
"The term 'connect-nacontroller' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."
The error occurs when it gets to the "Dim results As Collection(Of PSObject) = MyPipeline.Invoke()" line.
Here is my code (I changed the username and password and will be changing how it comes into the code once I get it to work. I also changed the name of the volume):
Protected Sub ExecuteCode_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
resultBox.Text = RunScript(powerShellCodeBox.Text)
End Sub
Private Function RunScript(ByVal scriptText As String) As String
Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
MyRunSpace.Open()
Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline()
Dim userName As String = "abc"
Dim password As String = "123"
Dim myscript As String = "$username = " & Chr(34) & userName & Chr(34) & Environment.NewLine & _
"$password = ConvertTo-SecureString " & Chr(34) & password & Chr(34) & " -AsPlainText -Force" & Environment.NewLine & _
"$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName,$password" & Environment.NewLine & _
"connect-nacontroller mydrive -credential $cred" & Environment.NewLine
MyPipeline.Commands.AddScript(myscript)
MyPipeline.Commands.Add("Out-String")
Dim results As Collection(Of PSObject) = MyPipeline.Invoke()
MyRunSpace.Close()
Dim MyStringBuilder As New StringBuilder()
For Each obj As PSObject In results
MyStringBuilder.AppendLine(obj.ToString())
Next
Return MyStringBuilder.ToString()
End Function

Right before the username line, I added this line:
"Import-Module DataOnTap" & Environment.NewLine & _**

Related

SQL Result to Global Variable

Within my MDIParent Me_Load I have an SQL query that returns user information based upon Windows ID. This works well, however I'd really like to move this logic out into perhaps a module and assign each value in the db to a global variable to be used elsewhere. I'd like to be able to access the contact_id in any child form of the parent MDI. I'm used to PHP where I'd just assign it to a session variable that I could reference anywhere.
This is my current SQL Code
Dim sql_query As String
Dim errorMessages As New StringBuilder()
Dim cnn = ConfigurationManager.ConnectionStrings("sql_connection_string").ConnectionString
Dim adapter As SqlDataAdapter
Dim ds As New DataTable()
Dim User_ID As String
Dim User_First_Name As String
Dim User_Last_Name As String
Dim User_Contact_CD As String
Dim User_Login As String
sql_query = "SELECT Contact_ID, First_Name_CH, Last_Name_CH, Contact_CD, Login_VC FROM [Worktool].[dbo].[vwEmployees_T] WHERE Login_VC = '" & username & "'"
Using connection As New SqlConnection(cnn)
Try
If connection.State = ConnectionState.Closed Then connection.Open()
adapter = New SqlDataAdapter(sql_query, connection)
adapter.Fill(ds)
User_ID = ds.Rows(0)("Contact_ID").ToString()
User_First_Name = ds.Rows(0)("First_Name_CH").ToString()
User_Last_Name = ds.Rows(0)("Last_Name_CH").ToString()
User_Contact_CD = ds.Rows(0)("Contact_CD").ToString()
User_Login = ds.Rows(0)("Login_VC").ToString()
connection.Close()
Catch ex As SqlException
MsgBox("Sorry, there was an issue with the connection. Please try again ! ")
Dim i As Integer
For i = 0 To ex.Errors.Count - 1
errorMessages.Append("Index #" & i.ToString() & ControlChars.NewLine _
& "Message: " & ex.Errors(i).Message & ControlChars.NewLine _
& "LineNumber: " & ex.Errors(i).LineNumber & ControlChars.NewLine _
& "Source: " & ex.Errors(i).Source & ControlChars.NewLine _
& "Procedure: " & ex.Errors(i).Procedure & ControlChars.NewLine)
Next i
MsgBox(errorMessages.ToString())
End Try
End Using
'Assign messages
main_window_welcome.Text = "Welcome back, " & Replace(User_First_Name, " ", "") & " " & Replace(User_Last_Name, " ", "")
variable username is
Public username = Environ$("Username")
You've declared the 4 variables in the class and they are private to that class. At this point your code works. Hilight those 4 variable declarations and Cut them. Your code shows errors because you just removed the declarations.
Add a module to your solution (name it what you want)
paste the declarations into the module body.
change the Dim to Public.
Your errors disappear.
Your variables are now public and available throughout your solution.

Shell command excel vba

I'm having some problems executing the following in Excel VBA. The goal is to run an .sql file - the issue is with the Execute Shell sub I think.
I run:
Sub RunFile()
Call ExecuteShell("C:\","LAPBTN1749","filename.sql")
End Sub
Sub ExecuteShell(path As String, hostname As String, file As String)
Dim retval
retval = Shell("SQLCMD -E -S " & hostname & "\SQLEXPRESS -i " & path & file, vbMinimizedFocus)
End Sub
It doesn't run, probably due to the quotes. If it is the quote, can someone explain how they work or tell me where I can find out because I've never properly understood this.
I agree with #TimWilliams. I prefer to append Chr$(34) to a string because it means I don't have to count the number of quotes that I'm using. The code looks like:
Sub RunFile()
Call ExecuteShell("C:\", "LAPBTN1749", "filename.sql")
End Sub
Sub ExecuteShell(path As String, hostname As String, file As String)
Dim retval
retval = Shell("SQLCMD -E -S " & Chr$(34) & hostname & "\SQLEXPRESS" & Chr$(34) & " -i " _
& Chr$(34) & path & file & Chr$(34), vbMinimizedFocus)
End Sub
If any of the passed parameters contain spaces then likely they need to be quoted in the call to Shell. Quotes in VBA are escaped by doubling them up:
Sub RunFile()
Call ExecuteShell("C:\","LAPBTN1749","filename.sql")
End Sub
Sub ExecuteShell(path As String, hostname As String, file As String)
Dim retval
retval = Shell("SQLCMD -E -S """ & hostname & "\SQLEXPRESS"" -i """ & _
path & file & """", vbMinimizedFocus)
End Sub
If you're still having problems then try Debug.Printing the first Shell argument and running it "manually" at the command prompt.

ExecuteNonQuery() won't work for INSERT function

First of all, I'm not a professional programmer. So there are some big faults possible in my program!
The problem is:
I linked my WPF file in visual express with a MS Access database (format 2003). Whenever I try to run the following (sorry for the dutch code):
Public Sub ToevoegenPersoon(voornaam As String, achternaam As String, mailadres As String, geboortedatum As Date, klantennummer As Integer, specialeCategorie As String)
Dim opdracht As OleDbCommand
Dim sqlOpdracht As String
sqlOpdracht = "INSERT INTO Klant (Voornaam, achternaam, mailadres, geboortedatum, klantennummer, specialeCategorie)" & _
"VALUES (" & Chr(34) & "" & voornaam & "" & Chr(34) & "," & Chr(34) & "" & achternaam & "" & Chr(34) & "," & Chr(34) & "" & _
mailadres & "" & Chr(34) & "," & Convert.ToString(geboortedatum) & "," & Convert.ToString(klantennummer) & "," & Chr(34) & "" & specialeCategorie & "" & Chr(34) & ")"
opdracht = New OleDbCommand(sqlOpdracht, connectie)
Debug.WriteLine(sqlOpdracht)
MsgBox(sqlOpdracht)
opdracht.Connection.Open()
opdracht.ExecuteNonQuery()
opdracht.Connection.Close()
End Sub
my program always has an error for the ExecuteNonQuery() function. This function is used for the following event:
Private Sub btnKlantToevoegen_Click(sender As Object, e As RoutedEventArgs) Handles btnKlantToevoegen.Click
Dim achternaam As String = boxVoornaam.Text
Dim voornaam As String = boxAchternaam.Text
Dim emailadres As String = boxEmailadres.Text
Dim geboortedatum As Date = GeboortedatumSelectie.SelectedDate
Dim klantennummer As Integer = 5
Dim specialeCategorie As String = "Jeugd"
Try
database.ToevoegenPersoon(voornaam, achternaam, emailadres, geboortedatum, klantennummer, specialeCategorie)
Catch ex As Exception
End Try
boxAchternaam.Clear()
boxVoornaam.Clear()
boxEmailadres.Clear()
End Sub
At the top, I stated the following to connect MS Access database with Visual express:
Private connectiestring As String = My.Settings.Database_Drijkoningen_Konings1ConnectionString
Private connectie As OleDbConnection
connectie = New OleDbConnection(connectiestring)
When running this program, the executenonquery() gives an error. And I have no clue whatsoever what it can be. Anybody who does?
Thanks in advance
Jeroen
Not sure if this could resolve your problem. I don't know the error message. However I will show a simple parameterized query that probably could help a lot
Public Sub ToevoegenPersoon(voornaam As String, achternaam As String, mailadres As String, geboortedatum As Date, klantennummer As Integer, specialeCategorie As String)
Dim opdracht As OleDbCommand
Dim sqlOpdracht As String
sqlOpdracht = "INSERT INTO Klant (Voornaam, achternaam, mailadres, " & _
"geboortedatum, klantennummer, specialeCategorie) " & _
"VALUES (?,?,?,?,?,?)"
opdracht = New OleDbCommand(sqlOpdracht, connectie)
opdracht.Parameters.AddWithValue("#p1", voornaam)
opdracht.Parameters.AddWithValue("#p2", achternaam)
opdracht.Parameters.AddWithValue("#p3", mailadres)
opdracht.Parameters.AddWithValue("#p4", Convert.ToString(geboortedatum))
opdracht.Parameters.AddWithValue("#p5", Convert.ToString(klantennummer))
opdracht.Parameters.AddWithValue("#p6", specialeCategorie)
opdracht.Connection.Open()
opdracht.ExecuteNonQuery()
opdracht.Connection.Close()
End Sub
Now, with a parameterized query there is no more concatenations on the command text and this alone will remove any possibility to forget some quote or comma between value. (Of course this removes also the Sql Injection problem and the parsing of strings that contain special characters)
There is still a problem to be resolved. The 4th and 5th parameter receive a string value. This requires the underlying field on the datatable to be a string field and not a DateTime. If this is not the case then you need to pass (as parameter value) just the date value

run 2 seperate cmd commands from vb forms appliaction

i want my program to open cmd , change directory and then do the command : "copy /B file1 file2 output"
this is what i have at the moment. but all that happens is a cmd window flashes for a second but no file gets created
Dim cmd1 As String
Dim cmd2 As String
cmd1 = "cd " & FolderFromFileName(imagename)
cmd2 = "copy /B " & NameOnlyFromFullPath(imagename) & "+" & "TEMP.txt" & " " & TextBox1.Text
Shell("cmd /c" & " " & cmd1 & " " & cmd2, AppWinStyle.NormalFocus)
please help, thanks :)
Do you really need to have a command prompt appear? You could do all this without a separate process by using the system.io library. If you really need the cmd prompt you can create a process.
Dim NewProcess = New Process
' a new process is created
NewProcess.StartInfo.UseShellExecute = False
' redirect IO
' PVWCmd.StartInfo.RedirectStandardOutput = True
' PVWCmd.StartInfo.RedirectStandardError = True
' PVWCmd.StartInfo.RedirectStandardInput = True
' don't even bring up the console window
NewProcess.StartInfo.CreateNoWindow = False
' executable command line info
NewProcess.StartInfo.FileName = "cmd"
NewProcess.StartInfo.WorkingDirectory = "C:\"
' NewProcess.StartInfo.Arguments = +" > """ + "LogFile.log" + """ 2>&1"
NewProcess.Start()

Write a visual basic script in a vb.net application.

In my application I have created I need it to write a visual basic script to change the ip address
The script is as follows...
Dim strIPAddress
Dim strSubnetMask
Dim strGateway
Dim intGatewayMetric
Dim strDns1
Dim strDns2
strIPAddress = "192.168.1.211"
strSubnetMask = "255.255.255.0"
strGateway = "192.168.0.11"
intGatewayMetric = 1
strDns1 = "8.8.8.8"
strDns2 = "4.4.4.4"
Set objShell = WScript.CreateObject("Wscript.Shell")
objShell.Run "netsh interface ip set address name=""Local Area Connection"" static " & strIPAddress & " " & strSubnetMask & " " & strGateway & " " & intGatewayMetric, 0, True
objShell.Run "netsh interface ip set dns name=""Local Area Connection"" static "& strDns1, 0, True
objShell.Run "netsh interface ip add dns name=""Local Area Connection"" addr="& strDns2, 0, True
Set objShell = Nothing
WScript.Quit
The way I am trying to write this is like the following..
Directory.CreateDirectory("C:\SpecMee\IPChanger\")
Dim objwriter As New System.IO.StreamWriter("C:\SpecMee\IPChanger\IpChanger.vbs")
objwriter.WriteLine("Dim strIPAddress" & Environment.NewLine & "Dim strSubnetMask" & Environment.NewLine & "Dim strGateWay" & Environment.NewLine & "Dim intGatewayMetric" & Environment.NewLine & "Dim strDns1" & Environment.NewLine & "Dim strDns2" & Environment.NewLine & "strIPAddress = """ & Environment.NewLine & TB_IPAddress & Environment.NewLine &)
objwriter.Close()
MessageBox.Show("Created")
The problem I am having is one, it is taking ages and two, how would i include the "" in the script.
I dont mind spending time on this, I just dont know if im going about this the right way.
any help would be appreciated.
Thanks
Chris
Add the script as a text file resource to your project. Replace all instances of the IP Address in the script with some known value, then use string.replace:
Const ipPlaceHolder As String = "##IP##"
Dim scriptContent As String = My.Resources.script.Replace(ipPlaceHolder, myTextBox.Text)
IO.File.WriteAllText("C:\SpecMee\IPChanger\IpChanger.vbs", scriptContent)
Where myTextBox contains user input and the text file resource is named "Script"
Two quotation marks in a row makes one in the output.
"And he said ""Thar she blows!"""
( You have two questions in one. That is not considered good customs on Stackoverflow. )