I am trying to add a IIS website via command-lets. What I currently have:
' User input
Dim domainname As String = "niels_test"
' System vars
Dim basePath As String = "C:\Projecten\Websites\"
Dim finalDirname As String = basePath & domainname
Dim shell As PowerShell = PowerShell.Create
'shell.Commands.AddScript("mkdir """ & finalDirname & """")
shell.Commands.AddScript("New-Website -name """ & domainname & """ -PhysicalPath '" & finalDirname & "' -port 80")
Dim results = shell.Invoke()
If results.Count > 0 Then
Dim b As New StringBuilder
For Each PSObject In results
b.AppendLine(PSObject.BaseObject.ToString)
Next
Else
Throw New Exception("NORESULT")
End If
If I comment out hte line for mkdir it works. But I cannot create a new website in IIS this way. If I execute that command via the powershell on the server itself. It does work.
This code is inside a .aspx.vb file.
Any idea on how to get this working?
Sounds like a permissions issue, the user under which you are running the website/appPool does not have the rights for "C:\Projecten\Websites\".
You can fix that by assigning a user with correct privileges to the Application Pool:
iis manager -> application pools -> yourPool -> advanced settings -> Process Model -> Identity
or give your app pool rights to the folder:
folder's security tab -> edit/add -> (in locations select your server) -> IIS AppPool\yourPool
Related
i write a code for remote access for exchange powershell from asp.net application to enable remote mail using vb.net and exchange 2016
the command run successfully from my visual studio debug
but when i put in iis web server it's giving me
Connecting to remote server "" failed with the following error
message : Access is denied
this is is the code
Function enableRemoteEmail(ByVal samaccount As String, ByVal email As String) As String
Dim ServerUri As String = "http://{mailserver}/powershell"
Dim SchemaUri As String = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"
Dim userName As String = AccountOperatorLogon
Dim password As New System.Security.SecureString
For Each x As Char In AccountOperatorPassword
password.AppendChar(x)
Next
Dim PSCredential As New PSCredential(userName, password)
Dim ConnectionInfo As WSManConnectionInfo = New WSManConnectionInfo(New Uri(ServerUri), SchemaUri, PSCredential)
ConnectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic
Dim RemoteRunspace As Runspace = RunspaceFactory.CreateRunspace(ConnectionInfo)
Dim RemotePowerShell As PowerShell = PowerShell.Create
RemotePowerShell.AddCommand("Enable-RemoteMailbox")
RemotePowerShell.AddParameter("Identity", samaccount)
RemotePowerShell.AddParameter("RemoteRoutingAddress",email )
RemotePowerShell.AddParameter("Credential", PSCredential)
' Open the remote runspace on the server.
RemoteRunspace.Open()
' Associate the runspace with the Exchange Management Shell.
RemotePowerShell.Runspace = RemoteRunspace
Dim TheResult As Collection(Of PSObject)
Dim TheResultString As String = ""
TheResult = RemotePowerShell.Invoke
For Each RSLT As PSObject In TheResult
TheResultString += RSLT.ToString() + "<br/>"
Next
RemoteRunspace.Close()
' Invoke the Exchange Management Shell to run the command.
Return TheResultString
End Function
i found the solution for anyone have the same problem
create user as a member of (Recipient Management group)
IIS change (for exchange server) navigate to IIS Manager | Default Website | PowerShell Change the physical path from: C:\Program Files\Microsoft\Exchange Server\V15\FrontEnd\HttpProxy\PowerShell to: C:\Program Files\Microsoft\Exchange Server\V15\ClientAccess\PowerShell
3.After the change: IISRESET
and it will work fine
I have created a windows service that requires executing an EXE file with the CMD process. I have used the following code:
Str = "C:\PCounter\Staff\account.exe CHARGE " & Name & " " & Amount & " TO" & Id
Dim procStartInfo As New System.Diagnostics.ProcessStartInfo(Str)
procStartInfo.RedirectStandardOutput = True
procStartInfo.UseShellExecute = False
procStartInfo.CreateNoWindow = True
Dim proc As New System.Diagnostics.Process
proc.StartInfo = procStartInfo
proc.Start()
proc.Dispose()
However the above code will return
system cannot find the file specified
I have tried same code on the Windows form, and its works fine. To make sure the path is correct I have added a text file in the same location as EXE file, and load the content of the text file in the service. It works fine.
I can't think of anything else; I really would appreciate it if you can help me on this.
ProcessStartInfo has two properties. One for the executable to run, and the other for the arguments to pass to the executable. The symantics for the Arguments property are the exact same as the command line.
You can not include the arguments in the same property as the executable. They must be separated.
Create service:
sc create Vm-Symantec04 binPath= "\"C:\App32\VMware\VMware Workstation\vmrun.exe\" -T ws start \"D:\VM\Sym04\Sym04.vmx\" nogui" depend= "VMAuthdService/VMnetDHCP/VMUSBArbService/VMware NAT Service" start= auto
Delete service:
sc delete Vm-Symantec04
I'm building out a decommissioning application that will allow an individual to provide an computer name and the utility will go out and purge the computer record from various locations. I'm running into a problem when attempting to delete a computer account from Active Directory. I'm impersonating a service account that only has rights to "Delete All Child Objects" within a particular OU structure. The code below works if I run it with my domain admin account; however fails with an "Access Denied" when I run it with the impersonated service account. I have verified that the permissions are correct within AD as I can launch Active Directory Users and Computers using a "runas" and providing the service account credentials and I can delete computer objects perfectly fine.
Wondering if anyone has run into this before or has a different way to code this while still utilizing my current OU permissions. My gut tells me the "DeleteTree" method is doing more then just deleting the object.
Any assistance would be appreciated.
Sub Main()
Dim strAsset As String = "computer9002"
Dim strADUsername As String = "serviceaccount#domain.com"
Dim strADPassword As String = "password"
Dim strADDomainController As String = "domaincontroller.domain.com"
Dim objDirectoryEntry As New System.DirectoryServices.DirectoryEntry
Dim objDirectorySearcher As New System.DirectoryServices.DirectorySearcher(objDirectoryEntry)
Dim Result As System.DirectoryServices.SearchResult
Dim strLDAPPath As String = ""
Try
objDirectoryEntry.Path = "LDAP://" & strADDomainController
objDirectoryEntry.Username = strADUsername
objDirectoryEntry.Password = strADPassword
objDirectorySearcher.SearchScope = DirectoryServices.SearchScope.Subtree
objDirectorySearcher.Filter = "(&(ObjectClass=Computer)(CN=" & strAsset & "))"
Dim intRecords As Integer = 0
For Each Result In objDirectorySearcher.FindAll
Console.WriteLine(Result.Path)
Diagnostics.Debug.WriteLine("DN: " & Result.Path)
Dim objComputer As System.DirectoryServices.DirectoryEntry = Result.GetDirectoryEntry()
objComputer.DeleteTree()
objComputer.CommitChanges()
intRecords += 1
Next
If intRecords = 0 Then
Console.WriteLine("No Hosts Found")
End If
Catch e As System.Exception
Console.WriteLine("RESULT: " & e.Message)
End Try
End Sub
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
' set up domain context
Dim ctx As New PrincipalContext(ContextType.Domain, "DOMAIN", strADUsername, strADPassword)
' find a computer
Dim computerToDelete As ComputerPrincipal = ComputerPrincipal.FindByIdentity(ctx, strAsset)
If computerToDelete IsNot Nothing Then
' delete the computer, if found
computerToDelete.Delete()
End If
The new S.DS.AM makes it really easy to play around with users and groups in AD!
Delete Tree is different from delete. You're going to need the Delete Subtree permission on the child computer objects for this to work.
I'm needing to run scripts from within a vb.net windows app.
I've got the scripts running in the background fine;
Using MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
MyRunSpace.Open()
Using MyPipeline As Pipeline = MyRunSpace.CreatePipeline()
MyPipeline.Commands.AddScript("import-module -name " & moduleName &
vbCrLf &
"(get-module -name " & moduleName & ").version")
Dim results = MyPipeline.Invoke()
'Do something with the results
End Using
MyRunSpace.Close()
End Using
However, i now need to be able to have the powershell run (not in the background) eg. When prompts occur;
Set-ExecutionPolicy unrestricted
I'm currently looking into the Microsoft.PowerShell.ConsoleHost namespace to see if i can use something like;
Dim config = RunspaceConfiguration.Create
ConsoleShell.Start(config, "Windows PowerShell", "", New String() {""})
Can anyone advise me please???
EDIT: I've fudged it a bit with this;
Public Function RunPowershellViaShell(ByVal scriptText As String) As Integer
Dim execProcess As New System.Diagnostics.Process
Dim psScriptTextArg = "-NoExit -Command ""& get-module -list"""
'Dim psScriptTextArg = "-NoExit -Command ""& set-executionPolicy unrestricted"""
'Dim psScriptTextArg = ""-NoExit -Command """ & scriptText & """"
execProcess.StartInfo.WorkingDirectory = Environment.SystemDirectory & "\WindowsPowershell\v1.0\"
execProcess.StartInfo.FileName = "powershell.exe"
execProcess.StartInfo.Arguments = psScriptTextArg
execProcess.StartInfo.UseShellExecute = True
Return execProcess.Start
End Function
But there's gotta be a better way??
There is a distinction between the PowerShell engine and its host. What you're wanting is to run the engine within your application but then fire up a separate host (which also is hosting the PowerShell engine) to handle prompts. You might want to look into modifying your application to act as a host itself. You could then react to prompts (read-host) and pop dialog boxes or whatever. Take a look at this relevant PowerShell namespace. Also check out this blog post on creating a simple PSHost.
I have a very simple VB.net Windows Service written using VS.net 2008. The program after doing several other functions writes a log in one of the network folders. The code is as shown below: If I change the path from "Y:\Activity_Log" to "C:\Activity_Log" it is working like a charm.
What is the problem if I use Y drive which is a valid one and I am able to access it from other VB.net desktop apps. Please help.
Dim strFile As String = "Y:\Activity_Log\" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim fs As FileStream = Nothing
Dim activityfolder As String = "Y:\Activity_Log"
Dim di As System.IO.DirectoryInfo
di = New System.IO.DirectoryInfo(activityfolder)
If (Not di.Exists) Then
di.Create()
End If
If (Not File.Exists(strFile)) Then
Try
Dim sw1 As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
sw1.WriteLine("******************************Activity Log for " & Now.Date & "*******************")
sw1.WriteLine("-----------------------------------------------------------------------------------------------------------------")
sw1.WriteLine(Remarks & " ---" & DateTime.Now)
sw1.Close()
Catch ex As Exception
End Try
Else
Dim sw As StreamWriter
sw = AppendText(strFile)
sw.WriteLine(Remarks & " ---" & DateTime.Now)
sw.Close()
End If
Start->Control Panel->Administrative Tools->Services
Find Your service in the list, right click on the name, Properties
Click the Log On tab
Change from Local System account to 'This Account'
Use a user that has access to that share, start with your username/password to convince yourself that it works ;)
Click Ok, then restart the service.
maybe you need to run the service under a user that has access to that drive?
maybe the generic service user doesn't have access.