Page 1 of 2 12 LastLast
Results 1 to 15 of 19
  1. #1
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,435
    Thanks
    372
    Thanked 1,457 Times in 1,326 Posts

    It's head scratching time again!

    Hey Y'all,

    I've been working the last 2 evenings on this post:

    I've developed some PS code that should do the trick but it's been giving me fits.

    I register the USB events with this code which works.
    Code:
    # Define a WMI event query, that looks for new instances of Win32_LogicalDisk where DriveType is "2"
    # http://msdn.microsoft.com/en-us/library/aa394173(v=vs.85).aspx
    $Query = "select * from __InstanceCreationEvent within 5 where TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2";
    
    # Define a PowerShell ScriptBlock that will be executed when an event occurs
    $Action = { & G:\BEKDocs\Scripts\DirTreeToFile.ps1  $event.SourceEventArgs.NewEvent.TargetInstance.Caption;  };
    
    # Create the event registration
    # NOTE: Event Registration only good while the PS Shell is OPEN!!!!!!!!!
    Register-WmiEvent -Query $Query -Action $Action -SourceIdentifier USBFlashDrive;
    
    $Query = "select * from __InstanceCreationEvent within 5 where TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 3";
    
    # Define a PowerShell ScriptBlock that will be executed when an event occurs
    $Action = { & G:\BEKDocs\Scripts\DirTreeToFile.ps1  $event.SourceEventArgs.NewEvent.TargetInstance.Caption;  };
    
    # Create the event registration
    # NOTE: Event Registration only good while the PS Shell is OPEN!!!!!!!!!
    Register-WmiEvent -Query $Query -Action $Action -SourceIdentifier USBHDDrive;
    I know the call works because it calls the second program and it's diagnostic statements print their values.
    Code:
    <# +-------------------------------------------+
       | Program Name: DirTreeToFile.ps1           |
       | Programmed by: ComputerMentor             |
       |           AKA: RetiredGeek (WSL)          |
       | Created      : 04/07/2015                 |
       | Last Update  :                            |
       | Version No.  : 1.0                        |
       +-------------------------------------------+
    #>
    Param (
           [string] $SourceDrivePath 
          )
    
    #Start-Sleep -Seconds 30
    Clear-Host
    
    $FileTypeToList = "*"
    $VolLabel = Get-Volume $SourceDrivePath.Substring(0,1) 
    $VolLabel = $VolLabel.FileSystemLabel
    
    if ($VolLabel -eq "") {
      $VolLabel = "NoVolLabel"
    }
    
    $DestDrivePath = "G:\Test\$VolLabel.txt"   #Replace drive\dir with your values
    
    
    Write-Host "Source: $SourceDrivePath - Volume Label: $VolLabel  Dest: $DestDrivePath"
    Write-Host "Filter: *.$FileTypeToList"
    
    Get-ChildItem -Path $SourceDrivePath -Filter "*.$FileTypeToList" `
                  -Recurse -Force  -ErrorAction "SilentlyContinue"
    
    #     Out-File -FilePath "$DestDrivePath" -Force -Width 160
    
    Write-Host "Done!"
    However, it will not produce the directory listing to a file (currently commented out) or to the screen!

    However if I run the program manually and pass the exact same value d: (where d is a drive letter) the code executes just as it should. As you can see I even tried inserting a delay of 30 seconds but it had no effect except to slow down my testing cycle.

    Any Ideas? I'm sure it's another PS Newbie error but I sure can't see it.

    PowerShell results:
    Code:
    PS> .\RegEventUSBInserted.ps1
    
    Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
    --     ----            -------------   -----         -----------     --------             -------
    2      USBFlashDrive                   NotStarted    False                                 & G:\BEKDocs\Scripts\...
    3      USBHDDrive                      NotStarted    False                                 & G:\BEKDocs\Scripts\...
    
    
    PS>
    
    Output when USB Flash Drive is inserted.
    
    Source: X: - Volume Label: UTILITYUSB  Dest: G:\Test\UTILITYUSB.txt
    Filter: *.*
    Done!
    
    Partial - Output when program is executed manually:
    
    PS>DirTreeToFile.ps1 X:  
    
    Source: x: - Volume Label: UTILITYUSB  Dest: G:\Test\UTILITYUSB.txt
    Filter: *.*
    
    
        Directory: X:\
    
    
    Mode                LastWriteTime     Length Name
    ----                -------------     ------ ----
    d----         5/22/2013   9:37 AM            Sysinternals Suite
    d----         5/22/2013   9:40 AM            NirSoft Utilities
    d--hs          1/1/2015   1:37 PM            System Volume Information
    -a-h-         5/22/2013  10:21 AM         26 autorun.inf
    -a---         4/12/2013   5:06 PM    3544064 wscc.exe
    -a---         2/27/2013   2:46 PM       2640 wscc.license.txt
    -a---          1/1/2015   1:44 PM       1828 wscc.readme.txt
    -a---          1/1/2015   1:39 PM    3263168 wscc.cache
    -a---          1/1/2015   1:39 PM     291948 wscc.dat
    
    
        Directory: X:\Sysinternals Suite
    
    
    Mode                LastWriteTime     Length Name
    ----                -------------     ------ ----
    -a---         11/6/2007   8:17 AM         39 psversion.txt
    -a---         5/15/2013  11:46 PM     328384 accesschk.exe
    -a---         11/1/2006  12:06 PM     174968 AccessEnum.exe
    -a---         7/28/2006   8:32 AM       7005 Eula.txt
    -a---         7/12/2007   5:26 AM      50379 AdExplorer.chm
    ...
    -a---         1/28/2015   8:50 AM     115296 ProduKey.exe
    -a---         1/28/2015   8:52 AM        590 ProduKey.cfg
    -a---          4/7/2015   4:51 PM       1074 USBDeview.cfg
    
    
        Directory: X:\System Volume Information
    
    
    Mode                LastWriteTime     Length Name
    ----                -------------     ------ ----
    -a---          1/1/2015   1:37 PM         76 IndexerVolumeGuid
    Done!
    
    PS>
    Thanks.
    Last edited by RetiredGeek; 2015-06-02 at 07:52.
    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  2. #2
    WS Lounge VIP
    Join Date
    Dec 2009
    Location
    Earth
    Posts
    8,191
    Thanks
    48
    Thanked 984 Times in 914 Posts
    You are using WMI to run the program so my guess is WMI does not have permission / access to print to the screen or a file, or access to the drives as letters. Can you try sending the output to Event Viewer / specifying the drives via something other than Caption?

    cheers, Paul

  3. #3
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,435
    Thanks
    372
    Thanked 1,457 Times in 1,326 Posts
    Paul,

    Thanks for looking. I don't think it is a permissions problem as the WIM does call the secondary program and pass the drive letter as shown in the posted test runs. This actually worked at one time writing to a file for a USB key. When I tried to get it to work with USB HDD it started to fail for both devices. It creates the file but it is empty. Thanks again.
    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  4. #4
    Super Moderator satrow's Avatar
    Join Date
    Dec 2009
    Location
    Cardiff, UK
    Posts
    4,490
    Thanks
    284
    Thanked 577 Times in 480 Posts
    71 WMI commands with output examples plus loads of WMI links here, if it's of any use: http://www.sysnative.com/forums/wind...8-7-vista.html

    USBDLM might be useful for locking USB drives to individual drive letters: http://www.uwe-sieber.de/usbdlm_e.html

    Edit: add this to your bedtime reading : http://skwire.dcmembers.com/fp/?page=zero-zipper
    Last edited by satrow; 2015-04-09 at 15:07.

  5. #5
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,435
    Thanks
    372
    Thanked 1,457 Times in 1,326 Posts
    Satrow,

    Thanks!

    I'm already using USBDLM on my machine but don't know if the OP who's problem I'm trying to solve has it. I'll give the other links a look.
    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  6. #6
    Super Moderator satrow's Avatar
    Join Date
    Dec 2009
    Location
    Cardiff, UK
    Posts
    4,490
    Thanks
    284
    Thanked 577 Times in 480 Posts
    Re USBDLM: me too, it's fine - but some AV/AM might freak out and freeze it, not sure which, maybe SpyHunter (spit) or Spybot, something I recently tested froze it, I might have the logs - but it's as safe as, well, anything.

    There's another potentially useful tool for this over on skwire, forgotten what it is though ...

  7. #7
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,435
    Thanks
    372
    Thanked 1,457 Times in 1,326 Posts
    Hey Y'all,

    I'm still working on this and looking for ideas!
    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  8. #8
    Super Moderator satrow's Avatar
    Join Date
    Dec 2009
    Location
    Cardiff, UK
    Posts
    4,490
    Thanks
    284
    Thanked 577 Times in 480 Posts
    I noticed the same topic on Majorgeeks several days ago, maybe there was something there that did the job?

    EDIT: http://forums.majorgeeks.com/showthread.php?t=291863
    Last edited by satrow; 2015-04-14 at 18:48.

  9. #9
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,435
    Thanks
    372
    Thanked 1,457 Times in 1,326 Posts
    Satrow,

    Thanks for the link. Unfortunately not what I'm after at this time but may be helpful for the OP. I'm trying to figure out why the PowerShell doesn't work when everything I can see says it should.
    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  10. #10
    jwoods
    Guest
    Using the "pipe" symbol before the Out-File Cmdlet will write the results to the text file...

    Get-ChildItem -Path $SourceDrivePath -Filter "*.$FileTypeToList" `
    -Recurse -Force -ErrorAction "SilentlyContinue" | Out-File -FilePath $DestDrivePath -Force -Width 160

  11. #11
    Lounger
    Join Date
    Dec 2009
    Location
    Gillingham, Dorset, UK
    Posts
    30
    Thanks
    0
    Thanked 13 Times in 11 Posts
    RG,

    I do not understand why your script does not work, but take a look at this page:
    Monitor Volume Change Event in PowerShell

    You should be able to tweak the script to achieve the result that you are after.

    Hope it helps. Good luck.

  12. #12
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,435
    Thanks
    372
    Thanked 1,457 Times in 1,326 Posts
    Cliff,

    Thanks for the link. The link used a different WMI event so I gave it a try. Unfortunately, the same results. The drive letter is passed to the program but the Get-ChildItem statement does nothing. I even tried combining it all into one program as shown in your link making the external program an internal function and still no luck.

    So I've stripped down the thing to a single file and eliminated all the extraneous/unnecessary stuff to just try to get it to list to the screen and it still does not work. Here's the test file if anyone else cares to give it a try.

    Code:
    Function DirTreeToFile {
    Param (
           [string] $SourceDrivePath 
          )
    
    Clear-Host
    
    $VolLabel = Get-Volume $SourceDrivePath.Substring(0,1) 
    $VolLabel = $VolLabel.FileSystemLabel
    
    if ($VolLabel -eq "") {
      $VolLabel = "NoVolLabel"
    }
    
    Write-Host "Source: $SourceDrivePath"
    
    Get-ChildItem -Path "$SourceDrivePath\"  -Recurse -Force  
    
    Write-Host "Done!"
    }
    
    #Query for finding all device arrival events
    $query = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType=2"            
    
    # Define a PowerShell ScriptBlock that will be executed when an event occurs
    $Action = { DirTreeToFile  $Event.SourceEventArgs.NewEvent.DriveName }
    
    # Create the event registration
    # NOTE: Event Registration only good while the PS Shell is OPEN!!!!!!!!!
    Register-WmiEvent -Query $Query -Action $Action -SourceIdentifier USBFlashDrive;
    Note: You MUST keep the powershell session OPEN! Also, if you make changes you need to close powershell and restart before running again. BTW I tried inserting both 20 & 40 second delays with the Start-Sleep command to see if it was just a delay problem but still no love!
    PSLastrun.JPG
    Thanks again to all for looking at this.

    UPDATE: This is now cross posted here:
    Last edited by RetiredGeek; 2015-04-16 at 15:24.
    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  13. #13
    Lounger
    Join Date
    Dec 2009
    Location
    Gillingham, Dorset, UK
    Posts
    30
    Thanks
    0
    Thanked 13 Times in 11 Posts
    RG,

    This appears to work.

    Code:
    $Query = "SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2"
    Register-WmiEvent -Query $Query -SourceIdentifier USBFlashDrive
    
    Do {
    	$event = Wait-Event -SourceIdentifier USBFlashDrive
    	$drive = $event.SourceEventArgs.NewEvent.TargetInstance.Caption
    	$label = $event.SourceEventArgs.NewEvent.TargetInstance.VolumeName
    	Get-ChildItem -Path $drive -Recurse -Force
    	Remove-Event -SourceIdentifier USBFlashDrive
    } While ( $True )
    
    # NOTE: Press CTRL+C to break out of the loop, then execute the following command
    #	Unregister-Event -SourceIdentifier USBFlashDrive
    # OR, close the PS Host
    Give it a try. Good luck.

  14. The Following 2 Users Say Thank You to Cliff.H For This Useful Post:

    jackmeat (2015-06-01),RetiredGeek (2015-04-16)

  15. #14
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,435
    Thanks
    372
    Thanked 1,457 Times in 1,326 Posts
    Cliff,

    Very nicely done!

    I'd still like to know why the original code doesn't work?
    It'll bug (pun intended) the heck out of me until I get an explaination.

    Thanks again.
    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  16. #15
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Location
    Manning, South Carolina
    Posts
    9,435
    Thanks
    372
    Thanked 1,457 Times in 1,326 Posts
    Cliff,

    Here's your code with changes to meet the OP's specs of writing to a file.
    Code:
    $Query = "SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2"
    # Create the event registration
    # NOTE: Event Registration only good while the PS Shell is OPEN!!!!!!!!!
    Register-WmiEvent -Query $Query -SourceIdentifier USBFlashDrive
    
    Do {
    
    	$event = Wait-Event -SourceIdentifier USBFlashDrive
    	$drive = $event.SourceEventArgs.NewEvent.TargetInstance.Caption
    	$VolLabel = $event.SourceEventArgs.NewEvent.TargetInstance.VolumeName
    
        if ($VolLabel -eq "") {
          $VolLabel = "NoVolLabel"
        }
    
        $DestDrivePath = "G:\Test\$VolLabel.txt"   #Replace drive\dir with your values
    
    	Get-ChildItem -Path $drive -Recurse -Force | `
           Out-File -FilePath "$DestDrivePath" -Force -Width 75
    	Remove-Event -SourceIdentifier USBFlashDrive
    
    } While ( $True )
    
    # NOTE: Press CTRL+C to break out of the loop, then execute the following command
    #	Unregister-Event -SourceIdentifier USBFlashDrive
    # OR, close the PS Host
    FYI: I did a little testing and using your code (with my mods) uses 0.05% of the CPU...
    Using my original that setups the event to call another program (file) uses only 0.01% of the CPU.
    Note: My original version uses the same Event query as your code so it's apples to apples.
    This is the reason (although I know it isn't much) for trying to make that version run. Not to mention that it is driving me CRAZY!

    May the Forces of good computing be with you!

    RG

    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  17. The Following User Says Thank You to RetiredGeek For This Useful Post:

    jackmeat (2015-06-01)

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •