Jump to content
Sign in to follow this  
EllisDee

My 1st Script - 1 problem & Streamlining needed

Recommended Posts

EllisDee

Hi all,

First of all, not sure whether to post this here or example scripts as although it works it does have a problem

This is my first script I have made with AutoIT, its very basic but does some deployment tasks to make my life easier.

Script:

; Deployment Script
; This script requires full Administrative rights
#requireadmin
; Do not display Autoit tray icon
;#notrayicon
; Gathering information
   ;Getting username to add to local admin
$username = InputBox( "Input", "Enter the persons name who will use this computer in the format SURNAME, FORENAME: " )
If $username = @error = 0 or StringLen($Username) < 1 Then
    MsgBox(0, "Error", "No data entered or Cancel was pressed", 1)
Exit
Else
; Get the MAC Address of the computer
Send ("{LWin}")
sleep (1000)
Send ("cmd.exe")
Send ("{ENTER}")
WinWait ("C:\Windows\system32\cmd.exe")
Send ("ipconfig /All")
Send ("{ENTER}")
; Check if Corp. IS&T have been contacted
$yesnobox = MsgBox(4, "Check!", "Have you registered the MAC# with Corporate IS&T for ACS (Authentication)")
If $yesnobox = 7 Then
Exit
Else
  
; Disable Autotuning on network card
Send ("{LWin}")
sleep (1000)
Send ("cmd.exe")
Send ("{ENTER}")
WinWait ("C:\Windows\system32\cmd.exe")
Send ("{CTRLUP}{SHIFTUP}")
Send ("cls")
Send ("{ENTER}")
Send ("netsh interface tcp set global autotuning=disabled")
Send ("{ENTER}")
Send ("Exit")
Send ("{ENTER}")
EndIf
    
; Locate USB Drive & assigned drive letter, then copy files.
$var = DriveGetDrive( "removable" )
If NOT @error Then
For $i = 1 to $var[0]
   If $var[$i] = "a:" Then ContinueLoop
$usbdrive = $var[$i]    

sleep (3000)
filecopy($usbdrive & "\7_Deployment\Shortcuts\*.*", "C:\Users\Public\Desktop", 1)
    Else
   MsgBox(4112, "Error", "USB Drive not found")
   Exit
   Next
EndIf  

; Delete Infoworks File from Public Desktop
FileDelete ("C:\Users\Public\Desktop\InfoWorks 4.url")
; Copy Citrix file to default users - stops WCSError on boot
If Not FileExists ("C:\Temp") Then
   DirCreate ("C:\Temp")
   filecopy($usbdrive & "\7_Deployment\Citrix Fix\APPSRV.INI", "C:\Users\Default\AppData\Roaming\ICAClient\", 1)
Else
   filecopy($usbdrive & "\7_Deployment\Citrix Fix\APPSRV.INI", "C:\Users\Default\AppData\Roaming\ICAClient\", 1)
EndIf
; Add user to local admins
Send ("{LWin}")
sleep (1000)
Send ("mmc.exe lusrmgr.msc")
Send ("{ENTER}")
WinWaitActive ("lusrmgr")
Send ("{TAB}")
Send ("{DOWN}")
Send ("{ENTER}")
Send ("{DOWN}")
Send ("{TAB}")
Send ("{ENTER}")
WinWaitActive ("Administrators Properties")
Send ("!d")
WinWaitActive ("Select Users")
Send(($username) & ";user1" & ";user2")
Send ("{ENTER}")
If WinActive ("Local Users and Groups") Then
   Sleep (5000)
Else
WinWaitActive ("Administrators Properties")
Send ("{ENTER}")
Endif
Endif
Exit

2 Questions:

1, Why doesn't this part work? If the Computer has a floppy disk, the script still tries to read it even though I have specified no A:\ When it tries to read A:\ the files do not copy from the usb stick & then the script continues to add users to admins.

; Locate USB Drive & assigned drive letter, then copy files.
$var = DriveGetDrive( "removable" )
If NOT @error Then
For $i = 1 to $var[0]
   If $var[$i] = "a:" Then ContinueLoop
$usbdrive = $var[$i]

2, Can you suggest any improvements to the code, as I've said this is my first one and I've never tried scripting before.

Share this post


Link to post
Share on other sites
kor

; Deployment Script
#RequireAdmin ; script requires admin rights
#NoTrayIcon ; do not display autoit tray icon
#include <Constants.au3>

; Gather information
$hUser = InputBox("Input", "Enter the persons name who will use this computer in the format USERNAME, FORENAME: ")
If $hUser = @error Or $hUser = 0 Or StringLen($hUser) < 1 Then
    MsgBox(0, "Error", "No data entered or cancel was pressed", 5) ; changed timeout to 5 seconds
    Exit
Else
    ; Read and format MAC address
    $hRun = Run(@ComSpec & " /c getmac /fo csv /nh", '', @SW_HIDE, $STDOUT_CHILD) ; get mac address
    While ProcessExists($hRun)
        Sleep(100) ; wait for window to close
    WEnd
    $sMAC = StringLeft(StringReplace(StringReplace(StringStripWS(StdoutRead($hRun), 8), "-", ""), """", ""), 12) ; format MAC address
    ; Check if Corp. IS&T has been contacted
    $hYesNo = MsgBox(4, "Check!", "Have you registered the MAC# with Corporate IS&T for ACS (Authentication)")
    If $hYesNo = 7 Then
        Exit
    Else
        RunWait(@ComSpec & " /c netsh interface tcp set global autotuning=disabled") ; disable autotuning on network card
        ; Locate USB Drive & assigned driver letter, then copy files
        $aVar = DriveGetDrive("removable")
        If Not @error Then
            For $i = 1 to UBound($aVar) - 1
                If $aVar[$i] = "a:" Then ContinueLoop
                $sUsb = $aVar[$i]
                Sleep(3000)
                FileCopy($sUsb & "7_DeploymentShortcuts*.*", "C:UsersPublicDesktop", 1)
            Next
        Else
            MsgBox(4112, "Error", "USB Drive not found")
            Exit
        EndIf
        FileDelete ("C:UsersPublicDesktopInfoWorks 4.url") ; delete infoworks file from public desktop
        If Not FileExists("C:Temp") Then DirCreate("C:Temp") ; create directory if it doesnt exist
        FileCopy($sUsb & "7_DeploymentCitrix FixAPPSRV.INI", "C:UsersDefaultAppDataRoamingICAClient", 1) ; copy citrix file to default users - stops WCSError on boot
        ; code for adding user as an administrator. not sure what you are doing here and why, so letting you figure out a better way to work that code.
        ; the above code should help you understand how to make your code more efficient
    EndIf
EndIf

I have not tested it, but it passes syntax checks.

I'm not sure why you are getting the machines MAC addres since your code doesn't seem to do anything with it. But you can use my code I've found that works quite well to get a machines MAC address. I store it in the variable $sMAC

Edited by kor

Share this post


Link to post
Share on other sites
EllisDee

Regarding the MAC address, its just to have it on screen if the person deploying hasn't already contacted the department to add it to network.

Share this post


Link to post
Share on other sites
kor

Regarding the MAC address, its just to have it on screen if the person deploying hasn't already contacted the department to add it to network.

Then change

$sMAC = StringLeft(StringReplace(StringReplace(StringStripWS(StdoutRead($hRun), 8), "-", ""), """", ""), 12) ; format MAC address
    ; Check if Corp. IS&T has been contacted
    $hYesNo = MsgBox(4, "Check!", "Have you registered the MAC# with Corporate IS&T for ACS (Authentication)")

To

$sMAC = StringLeft(StringReplace(StringStripWS(StdoutRead($hRun), 8), """", ""), 17) ; format MAC address
    ; Check if Corp. IS&T has been contacted
    $hYesNo = MsgBox(4, "Check!", "Have you registered the MAC " & $sMAC & " with Corporate IS&T for ACS (Authentication)")
  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • Tats
      By Tats
      Hi,
      Good Day!
      I have a problem and having difficulty implementing it. I want to copy the files in a certain folder, rename it, and when it exist in the destination folder it will add an index counter.
       
      Example source folder having files like:
      AA_123.TXT
      BB_123.TXT
      CC_123.TXT
      DD_123.TXT
       
      After file copy the target folder would be like this:
      123.TXT
      123_1.TXT
      123_2.TXT
      123_3.TXT
       
      How to achieve this?
      Thanks in advance
       
       
    • BigMac121263
      By BigMac121263
      I know that this theme was discussed several times but I read all These threats with no helping result.
      I have two pieces of TEMPer1F USB Thermometer.
      It is a Standard Windows HID device with no add. Driver needed.
      With the device I got an App reading from it and showing Graphs and much more and which can handle several devices.
      With the Software came also a RDingUSB.dll file handling the communication with the device.
      I can call the dll without any error. But the Problem is how to Access the device using the DLL and Access more than one of same VID/PID
      by Serial or anything else useful.
      I have also sources in c# doing the Job, but no experience in C# to successfuly port it to AutoIT.
       
      So my question: Can anyone help me to realize the simple pull of the temperature value from the devices based on C# source?
      The rest to write it to MySQL DB and repeat it etc. is no Problem for me.
      ***************************************
      The C# part with the DLL functions class:
      ***************************************
      using System;
      using System.Runtime.InteropServices;
      namespace TEMPer
      {
        internal class RDing
        {
          [DllImport("RDingUSB.dll")]
          public static extern IntPtr OpenUSBDevice(int VID, int PID);
          [DllImport("RDingUSB.dll")]
          public static extern IntPtr CloseUSBDevice(IntPtr hDevice);
          [DllImport("RDingUSB.dll")]
          public static extern bool WriteUSB(IntPtr hDevice, byte[] pBuffer, uint dwBytesToWrite, ref ulong lpNumberOfBytesWritten);
          [DllImport("RDingUSB.dll")]
          public static extern bool ReadUSB(IntPtr hDevice, byte[] pBuffer, uint dwBytesToRead, ref ulong lpNumberOfBytesRead);
          [DllImport("RDingUSB.dll")]
          public static extern ushort GetInputLength(IntPtr hDevice);
          [DllImport("RDingUSB.dll")]
          public static extern ushort GetOutputLength(IntPtr hDevice);
          [DllImport("RDingUSB.dll")]
          public static extern uint GetErrorMsg(ref string[] lpErrorMsg, uint dwErrorMsgSize);
        }
      }
      *********************************
      The C# code snippet working with the functions of the class above is in the attachment
      this is the interesting part where the data is sent and pulled which I
      do not understand to transcode to AutoIT
      Important my devices are the type2 (TEMPer1F) :
      *********************************
      So in the end I Need: Call DLL, read all devices in array
      Loop the Array until ubound(Array) and for each device in Array read the temperature value and prepare the data to
      decimal 6,1 (SQL Format) and °C
      So how to pull the value from the devices?
      Maybe somwbody finds the important part in the C#  (the code above is for different models, mine is TEMPer1F
      Or maybe someone has solved this and has maybe a uDF for this
       
       
      MainForm.cs
    • JRSmile
      By JRSmile
      Hi,
      i searched the forum to communicate with a logitech G600 without using Shortcuts or Default Mouse Keys.
      the code below lets u use your sidekeys whenever you press down the ring key.
      before using the code you will have to unassign the keys in the logitech mouse driver software.
      The source of my code is a wacom usb script, wich was heavily modified to work.
      you might find some parts wierd, thats because this is my first attempt to communicate via raw hid. 
      #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Change2CUI=y #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #include <APISysConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WinAPIGdi.au3> #include <WinAPIMisc.au3> #include <WinAPISys.au3> #include <WindowsConstants.au3> #cs ; #include "CommMG.au3" $mgdebug = True Global $sportSetError $tset = _ComGetPortNames() for $i = 0 to UBound($tset) -1 if $tset[$i][1] = "Serielles USB-Gerät" Then $COMPort = StringTrimLeft($tset[$i][0],3) ConsoleWrite("Teensy an Port COM" & $COMPort & " gefunden!" & @CRLF) EndIf Next $resOpen = _CommSetPort($COMPort,$sportSetError,31250, 8,0,1,0,0,0) if $resOpen = 0 then ConsoleWrite($sportSetError & @LF) ;~ Exit EndIf #ce $atagRID_DEVICE_INFO_HID = 'struct;dword VendorId;dword ProductId;dword VersionNumber;ushort UsagePage;ushort Usage;endstruct' $atagRID_INFO_HID = 'dword Size;dword Type;' & $atagRID_DEVICE_INFO_HID & ';dword Unused[2]' Opt('TrayAutoPause', 0) ; Create GUI Global $g_hForm = GUICreate('G600', 100, 25, -1, -1, BitOR($WS_CAPTION, $WS_POPUP, $WS_SYSMENU)) Local $tRID = DllStructCreate($tagRAWINPUTDEVICE) DllStructSetData($tRID, 'Flags', $RIDEV_INPUTSINK) DllStructSetData($tRID, 'hTarget', $g_hForm) DllStructSetData($tRID, 'UsagePage', 0x80) ; Logitech G600 DllStructSetData($tRID, 'Usage', 0x0A) ; _WinAPI_RegisterRawInputDevices($tRID) ; Now iterate to find other devices Local $tText, $aData = _WinAPI_EnumRawInputDevices() If IsArray($aData) Then ReDim $aData[$aData[0][0] + 1][3] $tText = DllStructCreate('wchar[256]') For $i = 1 To $aData[0][0] If _WinAPI_GetRawInputDeviceInfo($aData[$i][0], $tText, 256, $RIDI_DEVICENAME) Then $aData[$i][2] = DllStructGetData($tText, 1) Else $aData[$i][2] = '' EndIf If $aData[$i][1] = $RIM_TYPEHID Then $devInf = DllStructCreate($atagRID_INFO_HID) If _WinAPI_GetRawInputDeviceInfo($aData[$i][0], $devInf, DllStructGetSize($devInf), $RIDI_DEVICEINFO ) Then If DllStructGetData($devInf, 'VendorId') = 0x046D And DllStructGetData($devInf, 'ProductId') = 0xC24A then ; G600 VID & PID ConsoleWrite ("Device Info:-" & @CRLF) ConsoleWrite ('VendorId: ' & Hex(DllStructGetData($devInf, 'VendorId'),4) & @CRLF) ConsoleWrite ('ProductId: ' & Hex(DllStructGetData($devInf, 'ProductId'),4) & @CRLF) ConsoleWrite ('VersionNumber: ' & DllStructGetData($devInf, 'VersionNumber') & @CRLF) ConsoleWrite ('UsagePage: ' & Hex(DllStructGetData($devInf, 'UsagePage'),2) & @CRLF) ConsoleWrite ('Usage: ' & Hex(DllStructGetData($devInf, 'Usage'),2) & @CRLF) DllStructSetData($tRID, 'UsagePage', DllStructGetData($devInf, 'UsagePage')) DllStructSetData($tRID, 'Usage', DllStructGetData($devInf, 'Usage')) _WinAPI_RegisterRawInputDevices($tRID) EndIf EndIf EndIf Next EndIf ; Register WM_INPUT message GUIRegisterMsg($WM_INPUT, 'WM_INPUT') GUISetState(@SW_SHOW) Global $structHID_DATA = "struct;" & _ "dword Type;" & _ "dword Size;" & _ "handle hDevice;" & _ "wparam wParam;" & _ "dword dwSizeHid;" & _ "dword dwCount;" & _ "endstruct;" Global $structWACOM_PEN_DATA = "struct;" & _ "dword Type;" & _ "dword Size;" & _ "handle hDevice;" & _ "wparam wParam;" & _ "dword dwSizeHid;" & _ "dword dwCount;" & _ "ubyte bRawData00;" & _ "ubyte penvsEraser;" & _ "word x;" & _ "word y;" & _ "word proximity;" & _ "word pressure;" & _ "ubyte bRawData09;" & _ "ubyte bRawData10;" & _ "ubyte bRawData11;" & _ "ubyte bRawData12;" & _ "ubyte bRawData13;" & _ "ubyte bRawData14;" & _ "ubyte bRawData15;" & _ "ubyte bRawData16;" & _ "ubyte bRawData17;" & _ "ubyte bRawData18;" & _ "ubyte bRawData19;" & _ "ubyte bRawData20;" & _ "ubyte bRawData21;" & _ "ubyte bRawData22;" & _ "ubyte bRawData23;" & _ "ubyte bRawData24;" & _ "ubyte bRawData25;" & _ "ubyte bRawData26;" & _ "ubyte bRawData27;" & _ "ubyte bRawData28;" & _ "ubyte bRawData29;" & _ "ubyte bRawData30;" & _ "ubyte bRawData31;" & _ "ubyte bRawData32;" & _ "ubyte bRawData33;" & _ "ubyte tilt_ba;" & _ "ubyte bRawData35;" & _ "ubyte tilt_na;" & _ "ubyte bRawData37;" & _ "endstruct;" Do Until GUIGetMsg() = $GUI_EVENT_CLOSE Func WM_INPUT($hWnd, $iMsg, $wParam, $lParam) #forceref $iMsg, $wParam Switch $hWnd Case $g_hForm Local $tRIM = DllStructCreate($tagRAWINPUTHEADER) If _WinAPI_GetRawInputData($lParam, $tRIM, DllStructGetSize($tRIM), $RID_HEADER) Then ; Retrieves the raw input from the specified device $devType = DllStructGetData($tRIM, 'Type') $devSize = DllStructGetData($tRIM, 'Size') Else ConsoleWrite ("Device Header Retrieval Failed" & @CRLF) Return EndIf ; Now use the handle to the device to get it's name Local $tText = DllStructCreate('wchar[256]') If _WinAPI_GetRawInputDeviceInfo(DllStructGetData($tRIM, 'hDevice'), $tText, 256, $RIDI_DEVICENAME) Then $devName = DllStructGetData($tText, 1) Else ConsoleWrite ("Device Name Retrieval Failed" & @CRLF) EndIf if $devType = $RIM_TYPEHID Then $tRIM = DllStructCreate($structWACOM_PEN_DATA) If _WinAPI_GetRawInputData($lParam, $tRIM, DllStructGetSize($tRIM), $RID_INPUT) Then if DllStructGetData($tRIM, 8) = 32 Then ; filter for ring key down (G-Mode) Switch DllStructGetData($tRIM, 9) ; if in g mode assign the Keys G9 to G20 to autoit functions. case 0 Return ; key released case 1 g1() case 2 g2() case 4 g3() case 8 g4() case 16 g5() case 32 g6() case 64 g7() case 128 g8() case 256 g9() case 512 g10() case 1024 g11() case 2048 g12() Case Else ;;; ConsoleWrite(DllStructGetData($tRIM, 9) & @CRLF) EndSwitch EndIf EndIf EndIf EndSwitch sleep(50) Return $GUI_RUNDEFMSG EndFunc ;==>WM_INPUT Func g1() ;~ Send("2") ConsoleWrite("g1" & @CRLF) ;~ _CommSendString("KEY_TAB" & @LF) ;~ Sleep(random(50,100,1)) ;~ _CommSendString("KEY_RELEASE_ALL" & @LF) ;~ Sleep(random(50,100,1)) ;~ _CommSendString("KEY_2" & @LF) ;~ Sleep(random(50,100,1)) ;~ _CommSendString("KEY_RELEASE_ALL" & @LF) EndFunc Func g2() ConsoleWrite("g2" & @CRLF) EndFunc Func g3() ConsoleWrite("g3" & @CRLF) EndFunc Func g4() ConsoleWrite("g4" & @CRLF) EndFunc Func g5() ConsoleWrite("g5" & @CRLF) EndFunc Func g6() ConsoleWrite("g6" & @CRLF) EndFunc Func g7() ConsoleWrite("g7" & @CRLF) EndFunc Func g8() ConsoleWrite("g8" & @CRLF) EndFunc Func g9() ConsoleWrite("g9" & @CRLF) EndFunc Func g10() ConsoleWrite("g10" & @CRLF) EndFunc Func g11() ConsoleWrite("g11" & @CRLF) EndFunc Func g12() ConsoleWrite("g12" & @CRLF) EndFunc  
    • fopetesl
      By fopetesl
      Struggling to get Filecopy() working
      MsgBox(0,"Moving file: ", $fLine) ; C:\AlmeterS3\AI74_No2.csv FileCopy( $fLine, "C:\AlmeterS3\S3_Database\") ; FileCopy( $fLine, $BatchDir & "\S3_Database\") If @error Then MsgBox($MB_SYSTEMMODAL, "ERROR!", "database write error " & @error) EndIf FileDelete( $fLine) doesn't copy only creates a file "C:\AlmeterS3\S3_Database" (actually AI74_No2.csv)
      Again my typo I should have added
      $FC_OVERWRITE + $FC_CREATEPATH since folder didn't actually exist.
    • Simpel
      By Simpel
      Hi,
      I do recognize bad behaviour at this snippet:
      #include <AutoItConstants.au3> Global $g_sSD = @ScriptDir & "\" Global $g_sBurstPath = $g_sSD & "Burst\" DirCreate($g_sBurstPath) Local $sFileName = "Test_mit_3_Seiten.pdf" ; any PDF with more than 1 page inside @ScriptDir FileCopy($g_sSD & $sFileName, $g_sBurstPath & $sFileName, 1) ;~ Sleep(13000) Local $hTimer = TimerInit() ConsoleWrite("Start" & @CRLF) _Burst($g_sBurstPath & $sFileName) ; bursts PDF into single pages ;~ While _FileInUse($g_sBurstPath & $sFileName) ;~ WEnd ConsoleWrite("End: " & Round(TimerDiff($hTimer)) & "ms" & @CRLF) Exit Func _quotePath($sPath) ; because of possible "spaces" inside pathes $sPath = '"' & $sPath & '"' Return $sPath EndFunc Func _Burst($sFile) Local $sPDFtk = $g_sSD & "pdftk.exe" ; path to pdftk.exe (and libiconv2.dll) Local $sCurrWorkingDir = @WorkingDir FileChangeDir($g_sBurstPath) ; it has to change for reasons Local $iPID = Run(_quotePath($sPDFtk) & ' ' & _quotePath($sFile) & ' burst', "", @SW_SHOW, $STDOUT_CHILD + $STDERR_CHILD) ; @SW_SHOW just to see "PDFtk is working" Local $sOutput, $sError While 1 $sOutput &= StdoutRead($iPID) $sError &= StderrRead($iPID) If @error Then ExitLoop Sleep(10) WEnd FileChangeDir($sCurrWorkingDir) ; back to normal EndFunc Func _FileInUse($sFilename) ; by Siao Local $aRet, $hFile $aRet = DllCall("Kernel32.dll", "hwnd", "CreateFile", _ "str", $sFilename, _ ;lpFileName "dword", 0x80000000, _ ;dwDesiredAccess = GENERIC_READ "dword", 0, _ ;dwShareMode = DO NOT SHARE "dword", 0, _ ;lpSecurityAttributes = NULL "dword", 3, _ ;dwCreationDisposition = OPEN_EXISTING "dword", 128, _ ;dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL "hwnd", 0) ;hTemplateFile = NULL $hFile = $aRet[0] If $hFile = -1 Then ;INVALID_HANDLE_VALUE = -1 $aRet = DllCall("Kernel32.dll", "int", "GetLastError") SetError($aRet[0]) Return 1 ; file in use (@error contains system error code) Else ;close file handle DllCall("Kernel32.dll", "int", "CloseHandle", "hwnd", $hFile) Return 0 ; file not in use EndIf EndFunc This bursting took about 15000ms. If I activate line 8 "Sleep(13000)" then the bursting itself never needed more than 1000ms. Round about 13000ms delay is needed until bursting is acting very fast, otherwise needing about 15000ms.
      Then I tested _FileInUse() instead of _Burst() w/o Sleep(13000). This runs in 3ms. It seemes to me that FileCopy() and Burst() are interacting in a way I can't see.
      Any ideas? Regards, Conrad
      P.S. You need pdftk.exe and libiconv2.dll at @ScriptDir. This you can get free here: https://www.pdflabs.com/tools/pdftk-server/ (I'm not sure whether I'm allowed to attach it here).
       
×