I am trying to get all the group users in a computer. If I do this manually, my way is to go to Computer Management to get the list of Local Users and Group, and from there, I can get the list of Users and Group.
This is my code and I use AutoIt:
Func User()
Local $objWMIService, $colSettings, $objComputer, $strComputer = "."
;# Initiate the object
$objWMIService = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\" & $strComputer & "\root\cimv2")
;# Check if it's an object
If IsObj($objWMIService) Then
;# Search for PC Infomration
$colSettings = $objWMIService.ExecQuery("Select * from Win32_GroupUser")
If IsObj($colSettings) Then
For $objComputer In $colSettings
If $objComputer.AccountType <> '' Then
Return MsgBox(0, "RETURN", "AccountType: " & $objComputer.AccountType & #CRLF & "Full Name: " & $objComputer.FullName & #CRLF & "Caption: " & $objComputer.Caption & #CRLF & "Name: " & $objComputer.Name)
EndIf
Next
Else
MsgBox(0, "RETURN", $colSettings & " IS NOT AN OBJ")
EndIf
Else
MsgBox(0, "RETURN", $objWMIService & " IS NOT AN OBJ")
EndIf
EndFunc ;==>User
However, no output is being returned. Is my query correct at all?
Try this : "Computer Info UDF"
Also, I found this old snippet. (Not tested!)
Dim $InGroup
$oMyError = ObjEvent("AutoIt.Error", "ComError")
If UserInGroup(#LogonDomain, #UserName, "Administrator") Then
MsgBox(0, "Validate", #LogonDomain & "/" & #UserName & " : User in your groupname " & $InGroup)
Else
MsgBox(0, "Validate", #LogonDomain & "/" & #UserName & " : User NOT in your groupname")
EndIf
Exit
; Check if User is in a group
Func UserInGroup($Domain, $UserName, $InGroup)
;local $sRet
Local $objUser = ObjGet("WinNT://" & $Domain & "/" & $UserName)
For $oGroup In $objUser.Groups
If $oGroup.Name = $InGroup Then Return 1
Next
Return 0
EndFunc ;==>UserInGroup
;COM Error function
Func ComError()
If IsObj($oMyError) Then
$HexNumber = Hex($oMyError.number, 8)
SetError($HexNumber)
Else
SetError(1)
EndIf
Return 0
EndFunc ;==>ComError
#cs
; Generated by AutoIt Scriptomatic
$wbemFlagReturnImmediately = 0x10
$wbemFlagForwardOnly = 0x20
$colItems = ""
$strComputer = "localhost"
$Output=""
$Output = $Output & "Computer: " & $strComputer & #CRLF
$Output = $Output & "==========================================" & #CRLF
$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
$colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_GroupUser", "WQL", _
$wbemFlagReturnImmediately + $wbemFlagForwardOnly)
If IsObj($colItems) then
For $objItem In $colItems
$Output = $Output & "GroupComponent: " & $objItem.GroupComponent & #CRLF
$Output = $Output & "PartComponent: " & $objItem.PartComponent & #CRLF
if Msgbox(1,"WMI Output",$Output) = 2 then ExitLoop
$Output=""
Next
Else
Msgbox(0,"WMI Output","No WMI Objects Found for class: " & "Win32_GroupUser" )
Endif
#ce
#include <Constants.au3> ; required for StdoutRead
; populate $groupstring with the output of net user /domain
; remove the /domain if you are just interested in local machine groups
$foo = Run(#ComSpec & " /c net user " & #UserName & " /domain", #SystemDir, #SW_HIDE, $STDOUT_CHILD)
$groupstring = ""
While 1
$groupstring &= StdoutRead($foo)
If #error = -1 Then ExitLoop
WEnd
Func ingroup($which)
If $which = "*" Then Return 1
$which = StringLeft($which, 21) ; net user /domain returns only the first 21 chars of each group
$which = "*" & $which
If StringInStr($groupstring, $which) Then
Return 1
Else
Return 0
EndIf
EndFunc ;==>ingroup
;example usage
If ingroup("Domain Admins") Then
$admin = True
Else
$admin = False
EndIf
Related
I have multiple inputs in columns from which I need to create table for each column which has headers, Create connection using power query, Using these connections I need to add to the power query, and export it to sheet2. I have attached sample excel sheet for reference. Below is the half code for the same, I am not pro in vba if any one could help in solving the same. Here is the link for the same which I need to automate.
data set
Option Explicit
Public Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Dim lo As ListObject
Dim tableobjects As ListObject
Dim sName As String
Dim sFormula As String
Dim wq As WorkbookQuery
Dim bExists As Boolean
Dim vbAnswer As VbMsgBoxResult
Dim vbDataModel As VbMsgBoxResult
Dim i As Long
Dim j As Long
Dim k, l As Long
Dim dStart As Double
Dim dTime As Double
Dim CellAddr As String
Dim CellValue As String
Dim RangeAddr As String
Dim Temp As String
Dim TotalNumberInputs As Integer
Dim answer As Integer
Dim TableExists As Boolean
Dim ListObj As ListObject
Repeat:
TotalNumberInputs = InputBox("Enter the total inputs", "input int number")
If TotalNumberInputs = 0 Then
MsgBox "Invalid Input!!!"
answer = MsgBox("Invalid Input!!! Do you want to continue Macro?", vbQuestion + vbYesNo + vbDefaultButton2, "Next step")
If answer = vbYes Then
GoTo Repeat
Else
Exit Sub
End If
End If
'Set variables
dStart = Timer
Set wb = ActiveWorkbook
Set ws = ActiveSheet
'Check of table exist or else create table
For k = 1 To TotalNumberInputs
ws.Cells(1, k).Select
CellAddr = Selection.Address(RowAbsolute:=False, ColumnAbsolute:=False)
CellValue = Cells(1, l).Value ' "Table" & (k + "0") ' Selection.Value
On Error Resume Next
Set ListObj = ActiveSheet.ListObjects(CellValue)
On Error GoTo 0
If ListObj Is Nothing Then
Range(CellAddr).Select
Range(Selection, Selection.End(xlDown)).Select
RangeAddr = Selection.Address
Range(RangeAddr).Activate
ws.ListObjects.Add(SourceType:=xlSrcRange, Source:=Range(RangeAddr), LinkSource:=False, XlListObjectHasHeaders:=xlYes, tablestyleName:="TableStyleMedium28").Name = CellValue
Else
'If the table does exist clear filter from column C
' ActiveSheet.ListObjects(CellValue).Range.AutoFilter Field:=3
End If
Next k
l = 1
'Loop sheets and tables
' For Each ws In ActiveWorkbook.Worksheets
For Each lo In ws.ListObjects ' For j = 1 To TotalNumberInputs ' For Each lo In ws.ListObjects
sName = lo.Name ' ws.Cells(1, l).Value ' lo.Name
l = l + 1
sFormula = "Excel.CurrentWorkbook(){[Name=""" & sName & """]}[Content]"
'Check if query exists
bExists = False
For Each wq In wb.Queries
If InStr(1, wq.Formula, sFormula) > 0 Then
bExists = True
End If
Next wq
'Add query if it does not exist
If bExists = False Then
' Add a Query
wb.Queries.Add Name:=sName, Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Excel.CurrentWorkbook(){[Name=""" & sName & """]}[Content]," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(Source,{{""" & sName & """, type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Changed Type"""
'Add connection
wb.Connections.Add2 Name:="Query - " & sName, _
Description:="Connection to the '" & sName & "' query in the workbook.", _
ConnectionString:="OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & sName & ";Extended Properties=""""", _
CommandText:="SELECT * FROM [" & sName & "]", _
lCmdtype:=2, _
CreateModelConnection:=False, _
ImportRelationships:=False
'Count connections
i = i + 1
End If
Next lo ' Next j ' Next lo
'Next ws
'Calc run time
dTime = Timer - dStart
MsgBox i & " connections have been created in " & Format(dTime, "0.0") & " seconds.", vbOKOnly, "Process Complete"
End Sub
Set myFile = objFSO.OpenTextFile("savedhosts.txt", ForReading, True)
Set myTemp = objFSO.OpenTextFile("savedhosts.txt" & ".tmp", ForWriting, True)
Do Until myFile.AtEndofStream
myLine = myFile.ReadLine
'msgbox "hostname = " & hostname
If InStr(myLine, hostname) Then
MsgBox "found hostname = " & hostname & " in the savedhosts.txt file"
myLine = hostname & ";" & hostname_IP_value
myTemp.WriteLine myLine
myFile.Close
myTemp.Close
objFSO.DeleteFile("savedhosts.txt")
objFSO.MoveFile "savedhosts.txt" & ".tmp", "savedhosts.txt"
Exit Sub
Else
Set objTextFile = objFSO.OpenTextFile("savedhosts.txt", ForAppending, True)
'MsgBox "hostname & ; & hostname_IP_value = " & hostname & ";" & hostname_IP_value
objTextFile.WriteLine(hostname_value & ";" & hostname_IP_value)
objTextFile.Close
document.getElementById("hostname").value=hostname
Exit Sub
End If
Loop
Even when inputting identical hostname values the script doesn't capture the condition to display the
MsgBox "found hostname = " & hostname & " in the savedhosts.txt file"
Instead it just appends it to the txt file, resulting in 2 text names with different values, which is not desirable!
I would change your Exit Sub statements to Exit Do. If that doesn't fix it, then specify VBTextCompare in the InStr function (eg, InStr(myLine, hostname, 1)). If that still doesn't fix it, check your data because it may not be in the format you believe its in. You may have to Escape(myLine) (and/or hostname since you don't mention how that variable gets set) to ensure you're comparing apples to apples.
I need to extract numeric info from text.
Ready
State: CTYG Work Request #: 2880087 General
Job Address
Contact
Work Request Search
My code :
$Text = WinGetText("[ACTIVE]")
Sleep(4000)
$Value = StringSplit($Text, #CRLF)
MsgBox(0, "Hello", $Value, 10) ;---1st message box
Sleep(4000)
For $i = 1 To $Value[0]
If StringRegExp($Value[$i], "[0-9][^:alpha:]") Then
MsgBox(0, "Hello1", $Value[$i], 5) ;---2nd message box
Sleep(200)
$newWR = $Value[$i]
MsgBox(0, "Hello2", $newWR, 10)
ConsoleWrite($newWR) ;---3rd message box
EndIf
Next
1st MsgBox() shows nothing. The 2nd and 3rd show State: CTYG Work Request #: 2880087 General. But I don't need the entire line, I just want 2880087.
What about this? This will delete everything but numbers.
$str = "State: CTYG Work Request #: 2880087 General"
ConsoleWrite(StringRegExpReplace($str, '\D', '') & #CRLF)
… i just want 2880087 …
Example using regular expression State: .+ #: (\d+) :
#include <StringConstants.au3>; StringRegExp()
#include <Array.au3>
Global Const $g_sText = 'Ready' & #CRLF & #CRLF _
& 'State: CTYG Work Request #: 2880087 General' & #CRLF & #CRLF _
& 'Job Address' & #CRLF & #CRLF _
& 'Contact' & #CRLF & #CRLF _
& 'Work Request Search'
Global Const $g_sRegEx = 'State: .+ #: (\d+)'
Global Const $g_aResult = StringRegExp($g_sText, $g_sRegEx, $STR_REGEXPARRAYMATCH)
ConsoleWrite($g_sText & #CRLF)
_ArrayDisplay($g_aResult)
Stores 2880087 to $g_aResult[0].
so I am writing a program to find specific lines in a dump from the uninstall registry, and then write those lines to a new text file. Here is the code.
fileName = "export.txt"
outputFileName = input("Enter the Output File Name")
inputFile = open(fileName, "r")
outputFile = open(outputFileName, "w")
displayName = ""
displayVersion = ""
publisher = ""
for line in inputFile:
if "DisplayName" in line:
lst = line.split("=")
displayName = lst[1][1:len(lst[1])-1]
if "DisplayVersion" in line:
lst = line.split("=")
displayVersion = lst[1][1:len(lst[1])-1]
if "Publisher" in line:
lst = line.split("=")
publisher = lst[1][1:len(lst[1])-1]
if displayName!= "" or displayVersion != "" or publisher != "":
outputFile.write(displayName + "\t" + displayVersion + "\t" +publisher + "\n")
displayName = ""
displayVersion = ""
publisher = ""
inputFile.close()
outputFile.close()
For some reason, the first three if statements are not being entered. Here is a snippet from the export.txt text file.
[HKEY_LOCAL_MACHINE\SoftWare\Microsoft\Windows\CurrentVersion\Uninstall\Matlab R2016b]
"DisplayName"="MATLAB R2016b"
"UninstallString"="C:\\Program Files\\MATLAB\\R2016b\\uninstall\\bin\\win64\\uninstall.exe C:\\Program Files\\MATLAB\\R2016b"
"DisplayIcon"="C:\\Program Files\\MATLAB\\R2016b\\bin\\win64\\matlab.ico"
"InstallLocation"="C:\\Program Files\\MATLAB\\R2016b"
"DisplayVersion"="9.1"
"URLInfoAbout"="www.mathworks.com"
"Publisher"="MathWorks"
"HelpLink"="www.mathworks.com/support"
"Comments"=" "
ê[HKEY_LOCAL_MACHINE\SoftWare\Microsoft\Windows\CurrentVersion\Uninstall\Matlab
R2016b]
“DisplayName””MATLAB R201 6b”
“UninstallString””C: \\Prograrn
Files\\MATLAB\\R2016b\\uninstall\\bin\\win64\\uninstall.exe C: \\Prograrn
Files\\frIATLAB\\R201 6b”
“Displaylcon””C:\\Prograrn Files\\MATLAB\\R2016b\\bin\\win64\\matlab. ico”
“InstallLocation””C: \\Prograrn Files\\MATLAB\\R201 6b”
“DisplayVersion””9. 1”
“URLlnfoAbout””www. mathworks. corn”
“Publisher”=”MathWorks”
“HelpLink””www. rnathworks. corn/support”
“Comments”” “
The logic of your last if statement is completely reversed. It should be or instead of and in order for your statement to work properly.
What about checking in a different way using find()?
if line.find("DisplayName") != -1:
do stuff.
I ran this fine, here's the code:
fileName = "export.txt"
outputFileName = input("Enter the Output File Name")
inputFile = open(fileName, "r")
outputFile = open(outputFileName, "w")
displayName = ""
displayVersion = ""
publisher = ""
for line in inputFile:
print line
if line.find("DisplayName") != -1:
lst = line.split("=")
displayName = lst[1][1:len(lst[1])-2]
if line.find("DisplayVersion") != -1:
print "here2"
lst = line.split("=")
displayVersion = lst[1][1:len(lst[1])-2]
if line.find("Publisher") != -1:
print "here3"
lst = line.split("=")
publisher = lst[1][1:len(lst[1])-2]
if displayName!= "" and displayVersion != "" and publisher != "":
print "Here4"
print displayName + "\t" + displayVersion + "\t" +publisher
outputFile.write(displayName + "\t" + displayVersion + "\t" +publisher)
displayName = ""
displayVersion = ""
publisher = ""
inputFile.close()
outputFile.close()
produces:
MATLAB R2016b 9.1 MathWorks
The output while running the script looks like this:
Enter the Output File Name"out.txt"
[HKEY_LOCAL_MACHINE\SoftWare\Microsoft\Windows\CurrentVersion\Uninstall\Matlab R2016b]
"DisplayName"="MATLAB R2016b"
"UninstallString"="C:\Program Files\MATLAB\R2016b\uninstall\bin\win64\uninstall.exe C:\Program Files\MATLAB\R2016b"
"DisplayIcon"="C:\Program Files\MATLAB\R2016b\bin\win64\matlab.ico"
"InstallLocation"="C:\Program Files\MATLAB\R2016b"
"DisplayVersion"="9.1"
here2
"URLInfoAbout"="www.mathworks.com"
"Publisher"="MathWorks"
here3
Here4
MATLAB R2016b 9.1 MathWorks
"HelpLink"="www.mathworks.com/support"
"Comments"=" "
I have the string of the following format:
example 1: ABC,0,ABCD,ABC,ABC,ABC,ABC,ABC,11,ABC,ABC,toRemove,012,234
example 2: ABC,0,ABCD,ABC,ABC,ABC,ABC,ABC,11,ABC,ABC, toRemove,012,234
If the string contains 14 Values (instead of 13 values) separated by comma, then remove the 12. value
The second line above contains a white space, that should also removed if exists.
StringSplit has already a counter (element 0), so no need to use Ubound).
Like StringSplit converts a string to an array, ArrayToString converts an array back to a string.
#include <array.au3>
$tmp_line = "ABC,0,ABCD,ABC,ABC,ABC,ABC,ABC,11,ABC,ABC, ToRemove,012,234"
$line = StringSplit($tmp_line, ",")
If $line[0] = 14 Then
$new_line = ArrayToString($line, ",", 1, 11) & "," & ArrayToString($line, ",", 13)
Else
$new_line = $line ; shouldn't this be $new_line = $tmp_line ?
EndIf
MsgBox(0, $line[0], $tmp_line & #CRLF & $new_line)
Solved:
$line = StringSplit($tmp_line, ",")
$count_values = Ubound($line)
If $count_values = 14 Then
$new_line = $line[1] & "," & $line[2] & "," & $line[3] & "," & $line[4] & "," & $line[5] & "," & $line[6] & "," & $line[7] & "," & $line[8] & "," & $line[9] & "," & $line[10] & "," & $line[12] & "," & $line[13]
Else
$new_line = $line
EndIf