Sign in to follow this  
Followers 0
PrairieSailor

Simple question from a newbie (writing a file)

12 posts in this topic

Hello,

I am struggling to understand AutoIt and scripting as a whole so please go easy here. I found a snippet of code from the forum, which does what I want but only outputs using a message box. I would like to have it write to a CSV file, and append to it each time it's run. I looked through help but there are so many functions that all look similar I'm getting lost.

Here is the code as-is.

$i = 0
$ComputerName = "."
$wmiServices = ObjGet ( _
"winmgmts:{impersonationLevel=Impersonate}!//" _
& $ComputerName)
$wmiDiskDrives = $wmiServices.InstancesOf("Win32_DiskDrive")
For $wmiDiskDrive In $wmiDiskDrives
$i = $i + 1
If $wmiDiskDrive.InterfaceType = "USB" Then
$DeviceID = $wmiDiskDrive.PNPDeviceID
MsgBox (0,"PNPDeviceID",$DeviceID)

EndIf
Next

Share this post


Link to post
Share on other sites



Maybe this'll get you going. I haven't tested this, and while it's mainly just code copied from the help file, you'd probably be better off validating this code before you run it..

$file = FileOpen("test.txt", 1)

; Check if file opened for writing OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

$i = 0
$ComputerName = "."
$wmiServices = ObjGet ( _
"winmgmts:{impersonationLevel=Impersonate}!//" _
& $ComputerName)
$wmiDiskDrives = $wmiServices.InstancesOf("Win32_DiskDrive")
For $wmiDiskDrive In $wmiDiskDrives
    $i = $i + 1
    If $wmiDiskDrive.InterfaceType = "USB" Then
        $DeviceID = $wmiDiskDrive.PNPDeviceID
        ;MsgBox (0,"PNPDeviceID",$DeviceID)
        FileWriteLine($file, "PNPDeviceID, " & $DeviceID & @CRLF)
    EndIf
Next
FileClose($file)

- Bruce /*somdcomputerguy */  If you change the way you look at things, the things you look at change.

Share this post


Link to post
Share on other sites

PrairieSailor,

Welcome to the AutoIt forum. :mellow:

You need to open, use and close a file. This gives you the idea:

$i = 0
$ComputerName = "."
$wmiServices = ObjGet( _
        "winmgmts:{impersonationLevel=Impersonate}!//" _
         & $ComputerName)
$wmiDiskDrives = $wmiServices.InstancesOf("Win32_DiskDrive")

; Open a file and delete an existing file of that name
$hFile = FileOpen(@ScriptDir & "\USB_Drives.csv", 2)

For $wmiDiskDrive In $wmiDiskDrives
    $i = $i + 1
    If $wmiDiskDrive.InterfaceType = "USB" Then
        $DeviceID = $wmiDiskDrive.PNPDeviceID
        ; Write to the file and add a comma at the end of each entry
        FileWrite($hFile,  $DeviceID & ";")
    EndIf
Next

; Close the file
FileClose($hFile)

Just one problem might occur, you have an un-needed comma at the end of the list - if that is a problem, we can work on it. :party:

Ask if anything is unclear. :P

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Hello, and thank you for the quick help already! WOW

That makes it very clear what the process is. I tried it, and also added two lines to trim what I need. The problem is the file doesn't seem to append each time, but instead overwrite.

I see that there is a FileWriteLine but now I'm really confused because the first time it has to create the file, but subsequently append the file with a new line. This gets more complicated I guess?

$i = 0
$ComputerName = "."
$wmiServices = ObjGet ( _
"winmgmts:{impersonationLevel=Impersonate}!//" _
& $ComputerName)
$wmiDiskDrives = $wmiServices.InstancesOf("Win32_DiskDrive")

; Open a file and delete an existing file of that name
$hFile = FileOpen(@ScriptDir & "\USB_Drives.csv", 2)

For $wmiDiskDrive In $wmiDiskDrives
$i = $i + 1
If $wmiDiskDrive.InterfaceType = "USB" Then
$DeviceID = $wmiDiskDrive.PNPDeviceID

$left = StringTrimLeft($DeviceID, 56)
$right = StringTrimRight($left, 2)

; Write to the file and add a comma at the end of each entry
        FileWrite($hFile,  $right & ",")
EndIf
Next

FileClose($hFile)

Share this post


Link to post
Share on other sites

PrairieSailor,

Look at the second parameter of FileOpen. I set it to 2 (Write mode (erase previous contents)) - just set it to 1 (Write mode (append to end of file)). Then you will get the new data added to the end of the file.

If you were to use FileWriteLine, you would not get a csv format file because (as explained in the Help file):

"a DOS linefeed (@CRLF) will be automatically added"

As often with AutoIt there are multiple ways to do something - you just need to choose the one that best suits your requirements. :P

All clear? :mellow:

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

The problem is the file doesn't seem to append each time, but instead overwrite.

The function FileOpen takes a few different modes to handle this.

- Bruce /*somdcomputerguy */  If you change the way you look at things, the things you look at change.

Share this post


Link to post
Share on other sites

Yep, that is clear! I'm sorry I didn't see that in the help file when I was looking.

Now I do have ONE other thing I was trying to do. With "if" "else". I want a MsgBox and to end the script if the

If $wmiDiskDrive.InterfaceType = "USB"
is not true because nothing would be recorded in this situation.

Because this is already an IF statement I'm not sure where this goes. I was trying it like this but then I get my not found error every time.

$i = 0
$ComputerName = "."
$wmiServices = ObjGet ( _
"winmgmts:{impersonationLevel=Impersonate}!//" _
& $ComputerName)
$wmiDiskDrives = $wmiServices.InstancesOf("Win32_DiskDrive")

; Open a file and delete an existing file of that name
$hFile = FileOpen(@ScriptDir & "\USB_Drives.csv", 1)

For $wmiDiskDrive In $wmiDiskDrives
$i = $i + 1
If $wmiDiskDrive.InterfaceType = "USB" Then
$DeviceID = $wmiDiskDrive.PNPDeviceID

Else
    MsgBox(4096,"", "Device not found!")

$left = StringTrimLeft($DeviceID, 56)
$right = StringTrimRight($left, 2)


; Write to the file and add a comma at the end of each entry
        FileWrite($hFile,  $right & ";")
        
        
EndIf
Next
MsgBox(0,"Completed", "USB Serial Number has been recorded")
FileClose($hFile)

I know this is more than I thought first, but now I realize this would be a necessity.

Share this post


Link to post
Share on other sites

PrairieSailor,

Follow-on questions are our speciality - as everyone seems to ask them! :P

You need to restructure your If...Then code:

$i = 0
$ComputerName = "."
$wmiServices = ObjGet( _
        "winmgmts:{impersonationLevel=Impersonate}!//" _
         & $ComputerName)
$wmiDiskDrives = $wmiServices.InstancesOf("Win32_DiskDrive")

; Open a file and delete an existing file of that name
;$hFile = FileOpen(@ScriptDir & "\USB_Drives.csv", 1)

For $wmiDiskDrive In $wmiDiskDrives

    ConsoleWrite( $wmiDiskDrive.InterfaceType & @CRLF)

    $i = $i + 1
    If $wmiDiskDrive.InterfaceType = "USB" Then
        $DeviceID = $wmiDiskDrive.PNPDeviceID
        $left = StringTrimLeft($DeviceID, 56)
        $right = StringTrimRight($left, 2)

        ; Write to the file and add a comma at the end of each entry
        ;FileWrite($hFile, $right & ";")
        ConsoleWrite("Writing to file" & @CRLF)

    Else
        ;MsgBox(4096, "", "Device not found!")
        ConsoleWrite("Not USB" & @CRLF)

    EndIf
Next
MsgBox(0, "Completed", "USB Serial Number has been recorded")
;FileClose($hFile)

Just remove the ConsoleWrite lines and uncomment the File* lines when you are happy with what is going on. :mellow:

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Getting close....

By doing that I realized that IF won't work either because there is always an IDE device type as well as USB so both the success AND the failure happen :mellow:

I tried changing the layout to account for this by adding another variable before the loop ($DeviceType = 0) then tried to change it to 1 when the USB is found. In my mind this make sense, but I'm not that smart!

Am I out to lunch?

$i = 0
$ComputerName = "."
$wmiServices = ObjGet( _
        "winmgmts:{impersonationLevel=Impersonate}!//" _
         & $ComputerName)
$wmiDiskDrives = $wmiServices.InstancesOf("Win32_DiskDrive")

; Open a file and delete an existing file of that name
$hFile = FileOpen(@ScriptDir & "\USB_Drives.txt", 1)

$DeviceType = 0

For $wmiDiskDrive In $wmiDiskDrives

    ;ConsoleWrite( $wmiDiskDrive.InterfaceType & @CRLF)

    $i = $i + 1
    If $wmiDiskDrive.InterfaceType = "USB" Then
        $DeviceID = $wmiDiskDrive.PNPDeviceID
        $DeviceType = 1
        $left = StringTrimLeft($DeviceID, 56)
        $right = StringTrimRight($left, 2)
        

        ; Write to the file and add a comma at the end of each entry
        FileWrite($hFile, $right & @CRLF)
        ;ConsoleWrite("Writing to file" & @CRLF)
        MsgBox(0, "Completed", $right & @CRLF & "USB Drive Recorded")

    EndIf
    
    If $DeviceType = 0 THEN
        MsgBox(4096, "", "Device not found!")
        ConsoleWrite("Not USB" & @CRLF)
    
    EndIf
    
    Next
    
    
;MsgBox(0, "Completed", "Script Complete")
FileClose($hFile)

Thanks for hanging on...I know simple stuff.

Share this post


Link to post
Share on other sites

PrairieSailor,

Ah, it seems I did not understand the question fully - I think I do now. :mellow:

Try this code:

$i = 0
$ComputerName = "."
$wmiServices = ObjGet( _
        "winmgmts:{impersonationLevel=Impersonate}!//" _
         & $ComputerName)
$wmiDiskDrives = $wmiServices.InstancesOf("Win32_DiskDrive")

ConsoleWrite($wmiDiskDrives & @CRLF)

; Open a file and delete an existing file of that name
;$hFile = FileOpen(@ScriptDir & "\USB_Drives.csv", 1)

For $wmiDiskDrive In $wmiDiskDrives


    If $wmiDiskDrive.InterfaceType = "USB" Then
        $i = $i + 1
        $DeviceID = $wmiDiskDrive.PNPDeviceID
        $left = StringTrimLeft($DeviceID, 56)
        $right = StringTrimRight($left, 2)
        ; Write to the file and add a comma at the end of each entry
        ;FileWrite($hFile, $right & ";")
        ConsoleWrite("Writing to file" & @CRLF)
    EndIf

Next

If $i = 0 Then
    ;MsgBox(4096, "", "No USB devices found")
    ConsoleWrite("No USB devices found" & @CRLF)
Else
    MsgBox(0, "Completed", "USB Serial Number has been recorded")
EndIf

;FileClose($hFile)

This will only error if there are no USB devices in the list - it ignores any other types.

Are we getting close? :P

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Fabulous!

I think I was on the right track...silly me didn't think hard enough that there already was a variable assigned just for this purpose :mellow:

I now have what I want, and will continue to play knowing I can always revert to what I know works. Thank you for your time.

Share this post


Link to post
Share on other sites

PrairieSailor,

Glad I could help. :mellow:

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

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  
Followers 0