End win32 process vbscript - winapi

I've got the following code to end a process, but I still receive an error code 2 (Access Denied).
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'MSSEARCH.exe'")
For each objProcess in colProcessList
wscript.echo objProcess.processid
intrc = objProcess.Terminate()
if intrc = 0 then wscript.echo "succesfully killed process" else wscript.echo "Could not kill process. Error code: " & intrc End if

It's quite legitimate to get "access denied" for ending a program. If it's a service (which I'm guessing mssearch.exe is), then it is probably running as the "SYSTEM" user, which has higher privileges than even the Administrator account.
You can't log on as the SYSTEM account, but you could probably write a service to manage other services...

As a non-privileged user, you can only end processes you own. In a multiuser environment this can bite you in the ankle, because WMI would return equally named processes from other users as well, unless you write a more specific WQL query.
If your process is a service, and your script runs under a privileged account, you may still need to take "the regular route" to stop it, for example using WScript.Shell to call net stop or sc.exe, or, more elegantly, using the Win32_Service class:
Set Services = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service WHERE Name = '" & ServiceName & "'")
For Each Service In Services
Service.StopService()
WSCript.Sleep 2000 ' wait for the service to terminate '
Next

If you look on this page: http://msdn.microsoft.com/en-us/library/aa393907(VS.85).aspx you would see that error code 2 is access denied instead of file not found

Related

Modify NTEventlogFile OverwritePolicy/Retention Cycle by WMI

I‘m trying to set via VBS the Win32_NTEventlogFile to keep entries for 10 days. I know I need an elevated shell to modify the security log. I’ve used the samples from Microsoft with this code
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Security)}!\\" & _
strComputer & "\root\cimv2")
Set colLogFiles = objWMIService.ExecQuery _
("Select * from Win32_NTEventLogFile " _
& "Where LogFileName='Security'")
For Each objLogFile in colLogFiles
objLogfile.MaxFileSize = (50*1024)
objLogFile.OverwriteOutDated=10
objLogFile.OverwritePolicy=OutDated
objLogFile.Put_(&H20000)
Next
This works for changing the maximum file size, but it does not work for setting the retention cycle.
When I query OverwriteOutDated again after changing it it says ‚0‘ in WMI. When I access it with powershell PS Get-Eventlog -List
It reports
Retain: -1
OverflowAction: DoNotOverwrite
But when I change it via powershell with
Limit-EventLog -LogName Security -RetentionDays 10 -OverflowAction OverwriteOlder
It works
Retain: 10
OverflowAction: OverwriteOlder
There is no error in the WMI call reported. I just seems to mess up the entry. Am I forgetting something when trying to change the retention cycle via WMI?

SetInfo to a user in active directory error handling

I cant get the error handling to work in my VBScript to set details for a user.
I know why I cant set it because they have more access then me :) but i'm doing a 'bulk' update of user accounts and a few support accounts get flagged in my list.
but I want my script to continue if a usr account is found that has more access then me.
Call GetusersDN(getDN) ' connecting to my domain and gets user details.
Set myUser = GetObject ("LDAP://" & getDN)
WScript.Echo "working on: " myUser.displayname
NewDate = "06/30/2014"
myUser.AccountExpirationDate = NewDate
myUser.SetInfo
in the CMD window i get this error: "Active Directory: General access denied error"
So started Googling found this site http://www.selfadsi.org/errorcodes.htm
so tried adding the below code but still 'konks out' and stops.
If (Err.number <> 0) Then
WScript.Echo Err.Description
WScript.Echo Err.Number
WScript.Echo "Error: Attribute could not be written"
Wscript.Quit
End If
that didnt work so I tried this
If Err.Description = "Active Directory: General access denied error" Then
WScript.Echo Err.Number
End If

Getting errors when checking framentation status

I am trying to execute the following script on Win7 (x64) to check if any volumes need to be defragmented.
Set VolumeList = GetObject("winmgmts:").ExecQuery("Select * from Win32_Volume")
For Each objVolume in VolumeList
errResult = objVolume.DefragAnalysis(blnRecommended, objReport)
If errResult = 0 then
Wscript.Echo "Used space: " & objReport.UsedSpace
Wscript.Echo "Volume name: " & objReport.VolumeName
Wscript.Echo "Volume size: " & objReport.VolumeSize
If blnRecommended = True Then
Wscript.Echo "This volume should be defragged."
Else
Wscript.Echo "This volume does not need to be defragged."
End If
Wscript.Echo
Else
MsgBox errResult
End If
Next
I have tried to run this script on two different Win7 systems.
On the first, I get an OUT OF MEMORY error on GetObject("winmgmts:").ExecQuery("Select * from Win32_Volume").
On the second, I get no OUT OF MEMORY error on GetObject, but I get error 11 (Unknown Error) in errResult (output of DefragAnalysis-method).
Both Win7 systems have been installed and configured in the same way.
Perhaps this is not important, but when I check the WMI properties, it says "Connected to <Local Computer>" and not (as in Win XP) "SUCCESSFULLY connected to <Local Computer>".
Code works just fine for me, but perhaps it'll help when you explicitly connect to the right namespace:
Set wmi = GetObject("winmgmts://./root/cimv2")
Set VolumeList = wmi.ExecQuery("SELECT * FROM Win32_Volume")
Also I'd recommend restricting the query to just local disks that have a drive letter assigned to them:
SELECT * FROM Win32_Volume WHERE DriveType = 3 AND DriveLetter IS NOT NULL
Use WBEMTest or WMIDiag to check if your WMI connection is working at all. Check the Application and System eventlogs for errors and warnings, too.
The reason for the error 11 was that the script was not run with elevated privileges. Once it was run as administrator, it worked fine. Thanks

Running a vbs file via a scheduled task on Server 2003

I've been working on modifying an existing vbscript. The wierd part is that when I run the script manually, it works fine. But as soon as I try to run it as a scheduled task, it reports as complete, but doesn't actually do anything. After much troubleshooting, I think I tracked it down to the original CreateObject. Here's the code:
On Error Resume Next
'create an instance of IE
Dim oIE, objFSO, linenum
linenum = 0
Set oIE = CreateObject("InternetExplorer.Application")
'If err.number <> 0 Then linenum = 6
Set objFSO = CreateObject("Scripting.FileSystemObject")
Const ForAppending = 8
Set objTextFile = objFSO.OpenTextFile ("C:\test.txt", ForAppending, True)
'objTextFile.WriteLine(now() & " Internet object created.")
'Execute our URL
'oIE.navigate("<intranet site>")
'objTextFile.WriteLine(now() & " Starting import")
'wait for the window to be closed (exit IE)
'Do Until Err : oIE.visible = True : wsh.sleep 1000 : Loop
'objTextFile.WriteLine(now() & " Import complete.")
if Err.Number <> 0 then
' An exception occurred
objTextFile.WriteLine("Exception:" & vbCrLf & " linenum: " & linenum & vbCrLf & " Error number: " & Err.Number & vbCrLf & " Error source: " & Err.source & vbCrLf & " Error description: " & Err.Description & vbCrLf)
End If
'clean up
'oIE.Quit
'oIE.Visible = False
'Set oIE = Nothing
I've commented most of it out, to narrow it down, and from the logging I added, it spits out the current error:
Exception:
linenum: 0
Error number: -2147467259
Error source:
Error description:
Yes, the source and description lines are blank.
Googling the error doesn't seem to bring up anything useful. So I'm not sure what's going on. Permissions have been checked multiple times, and it's always run as Administrator, the same user as I'm logged in as. The funny part is, this script works fine with Windows 2000. About the only thing I can think of is perhaps the Remote Desktop connection I'm using is somehow interfering with it.
Anyone have any ideas or things I might be able to try to resolve this?
For reference, when you've got problems googling a decimal error number, try converting it to hexadecimal. -2147467259 is the same as 80004005 and if you search for that you'll find that it's quite a common error and usually means that you're denied access to something so even if you're sure that it's not permissions for the things you've checked, it might be worth doing the following checks:
Does the scheduled task run under the same account as you used when you executed the script manually? Otherwise, try doing a RunAs on the script to run as the same user account as the task, if that works, try scheduling the task as your account.
That way you'll know if it's (task vs manual) or if it's (user1 vs user2). Which might make it a little easier to track down the issue.

Is there an easy way to verify that a server exists on a network with VBScript?

I have the eventual goal of determining that a particular database on a particular server with particular credentials is running, but I would settle, at this point, for the ability to check and see if a server is actually up on the network. Does anyone have a way of doing this? I seem to be drawing a blank.
Michael
try this
Dim target
Dim result
target= "172.19.130.96"
Set shell = WScript.CreateObject("WScript.Shell")
Set shellexec = shell.Exec("ping " & target)
result = LCase(shellexec.StdOut.ReadAll)
If InStr(result , "reply from") Then
WScript.Echo "Server alive"
Else
WScript.Echo "Not Alive"
End If
There maybe better ways especialy given you end goal but this should work and at least point you in the correct direction.
Here's an alternative solution that uses the Win32_PingStatus WMI class (note: this class is only available on Windows XP and later):
strServer = "stackoverflow.com"
Set oWMI = GetObject("winmgmts:\\.\root\cimv2")
Set oPing = oWMI.Get("Win32_PingStatus.Address='"& strServer & "'")
If oPing.StatusCode = 0 Then
WScript.Echo "Server is available."
Else
WScript.Echo "Server is not available."
End If
More ping script samples here: Why Doesn't My Ping Script Run on Windows 2000 Computers?
If you update the ping command so it only sends one echo request the script executes faster, if you've got an unreliable network this might not be best but for local LAN it's useful.
Dim target
Dim result
target= "172.19.130.96"
Set shell = WScript.CreateObject("WScript.Shell")
Set shellexec = shell.Exec("ping -n 1 " & target)
result = LCase(shellexec.StdOut.ReadAll)
If InStr(result , "reply from") Then
WScript.Echo "Server alive"
Else
WScript.Echo "Not Alive"
End If
For checking whether your database server is up, you can use tools like nmap. Then you can call it in your vbscript using exec() as per normal.

Resources