Answered by:
powershell - check folder for new files

Question
-
I was wondering if it is possible to have a powershell script that checks a specified folder for new files. Everytime a new file is deposited in the folder, the filename, date and time is recorded in the log and the file is moved to a production folder for processing.
I saw something similar using vbscript from here: http://blogs.technet.com/heyscriptingguy/archive/2007/02/14/how-can-i-automatically-open-new-files-added-to-a-folder.aspx
but was wondering if it is possible to have an equivalent in powershell? I have also tried using the register-wmievent described here: http://www.microsoft.com/technet/scriptcenter/topics/winpsh/events.mspx but do not know how to retrieve the new file info.
Thanks,
Kayser SozeWednesday, March 17, 2010 4:19 AM
Answers
-
This code demonstrates how to listen for new file creation on a specific folder and its subfolders. Set the IncludeSubdirectories property to $false, or simply remove the line if that is not a requirement.
In its Action block, it gathers the data you want to log, writes a message to the host and moves the file to a destination folder. You may need to check for file existence at the destination folder for cases where files with same name, and decide to overwrite or modify the name.
You don’t say how you’ll log the activity. Check my reply to this thread, it shows one way to append data to an Excel worksheet. But if you’ll be appending to a CSV file, check this blog entry.
$folder = '<full path to the folder to watch>'
$filter = '*.*' # <-- set this according to your requirements
$destination = '<full path to the destination folder>'
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
IncludeSubdirectories = $true # <-- set this according to your requirements
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp"
Move-Item $path -Destination $destination -Force -Verbose # Force will overwrite files with same name
}Eventually, unregister the subscription:
Unregister-Event -SourceIdentifier FileCreated
Robert
Wednesday, March 17, 2010 3:16 PM -
You might want to check out the PowerShellPack here:
http://code.msdn.microsoft.com/PowerShellPack
PS C:\Windows\system32> import-module filesystem
PS C:\Windows\system32> get-command -module filesystemCommandType Name Definition
----------- ---- ----------
Function Copy-ToZip ...
Function Get-DuplicateFile ...
Function Get-FreeDiskSpace ...
Function Get-SHA1 ...
Function Mount-SpecialFolder ...
Function New-Zip ...
Function Rename-Drive ...
Function Resolve-ShortcutFile ...
Function Start-FileSystemWatcher ...
PS C:\Windows\system32> get-help start-filesystemwatcherNAME
Start-FileSystemWatcherSYNOPSIS
Starts monitoring for file changes
SYNTAX
Start-FileSystemWatcher [-File] <String> [-Filter <String>] [-Recurse] [-On <String[]>] [-Do <ScriptBlock[]>] [<Com
monParameters>]
DESCRIPTION
Starts monitoring for file changes using the events on IO.FileSystemWatcher
RELATED LINKSREMARKS
To see the examples, type: "get-help Start-FileSystemWatcher -examples".
For more information, type: "get-help Start-FileSystemWatcher -detailed".
For technical information, type: "get-help Start-FileSystemWatcher -full".PS C:\Windows\system32>
- Marked as answer by IamMred Sunday, March 21, 2010 3:44 AM
Wednesday, March 17, 2010 12:57 PM -
One way of doing this is to use Register-WMIevent cmdlet in powershell. Example below:
register-wmiEvent -query "select * from __instancecreationevent within 10 where targetinstance isa
'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent='Win32_Directory.Name=""c:\\\\Jas""'" -sourceidentifier "
createfile"
this can be followed with a Script Block, or ou can use get-event cmdlet and pass createfile as source identifier.
Regards
Jas
Jaswinder Singh- Proposed as answer by Rajesh J S Wednesday, March 17, 2010 5:44 AM
- Marked as answer by IamMred Sunday, March 21, 2010 3:44 AM
Wednesday, March 17, 2010 5:42 AM
All replies
-
One way of doing this is to use Register-WMIevent cmdlet in powershell. Example below:
register-wmiEvent -query "select * from __instancecreationevent within 10 where targetinstance isa
'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent='Win32_Directory.Name=""c:\\\\Jas""'" -sourceidentifier "
createfile"
this can be followed with a Script Block, or ou can use get-event cmdlet and pass createfile as source identifier.
Regards
Jas
Jaswinder Singh- Proposed as answer by Rajesh J S Wednesday, March 17, 2010 5:44 AM
- Marked as answer by IamMred Sunday, March 21, 2010 3:44 AM
Wednesday, March 17, 2010 5:42 AM -
You might want to check out the PowerShellPack here:
http://code.msdn.microsoft.com/PowerShellPack
PS C:\Windows\system32> import-module filesystem
PS C:\Windows\system32> get-command -module filesystemCommandType Name Definition
----------- ---- ----------
Function Copy-ToZip ...
Function Get-DuplicateFile ...
Function Get-FreeDiskSpace ...
Function Get-SHA1 ...
Function Mount-SpecialFolder ...
Function New-Zip ...
Function Rename-Drive ...
Function Resolve-ShortcutFile ...
Function Start-FileSystemWatcher ...
PS C:\Windows\system32> get-help start-filesystemwatcherNAME
Start-FileSystemWatcherSYNOPSIS
Starts monitoring for file changes
SYNTAX
Start-FileSystemWatcher [-File] <String> [-Filter <String>] [-Recurse] [-On <String[]>] [-Do <ScriptBlock[]>] [<Com
monParameters>]
DESCRIPTION
Starts monitoring for file changes using the events on IO.FileSystemWatcher
RELATED LINKSREMARKS
To see the examples, type: "get-help Start-FileSystemWatcher -examples".
For more information, type: "get-help Start-FileSystemWatcher -detailed".
For technical information, type: "get-help Start-FileSystemWatcher -full".PS C:\Windows\system32>
- Marked as answer by IamMred Sunday, March 21, 2010 3:44 AM
Wednesday, March 17, 2010 12:57 PM -
This code demonstrates how to listen for new file creation on a specific folder and its subfolders. Set the IncludeSubdirectories property to $false, or simply remove the line if that is not a requirement.
In its Action block, it gathers the data you want to log, writes a message to the host and moves the file to a destination folder. You may need to check for file existence at the destination folder for cases where files with same name, and decide to overwrite or modify the name.
You don’t say how you’ll log the activity. Check my reply to this thread, it shows one way to append data to an Excel worksheet. But if you’ll be appending to a CSV file, check this blog entry.
$folder = '<full path to the folder to watch>'
$filter = '*.*' # <-- set this according to your requirements
$destination = '<full path to the destination folder>'
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
IncludeSubdirectories = $true # <-- set this according to your requirements
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp"
Move-Item $path -Destination $destination -Force -Verbose # Force will overwrite files with same name
}Eventually, unregister the subscription:
Unregister-Event -SourceIdentifier FileCreated
Robert
Wednesday, March 17, 2010 3:16 PM -
Thanks - a combination of Robert's and SinghJas' code did the trick.
@Mjolinor - thanks for the links to the powershellpack.
Monday, March 22, 2010 3:27 AM -
Kayser Soze, mind posting your completed script to share? Thanks!Thursday, May 3, 2012 8:13 AM
-
Hi,
This question has already been marked as answered. If you still need help, please start a new question.
Bill
Wednesday, November 28, 2012 3:12 PM -
Thanks for your reply, I solved this issue by change the batch file as below (add -NoExit and -WindowStyle Hidden):
@echo off
cd /d %~dp0
Powershell -NoExit -WindowStyle Hidden -File E:\Monitor_and_Move_File.ps1
pauseThank you all!!
Thursday, November 29, 2012 1:18 AM -
I understand this is old, but this solution is almost absolutely perfect, what I'm wondering is at the end where you have the Move-Item $path <> how would I move item so that it still moves, but renames the existing file with same file name, yyyyMMddfilename.txt.
Wednesday, November 25, 2015 2:02 PM -
use 'Set-Variable'
Set-Variable -Name destination -Scope Global
$folder = '<full path to the folder to watch>'
$filter = '*.*' # <-- set this according to your requirements
$destination = '<full path to the destination folder>'Thursday, August 10, 2017 2:08 AM -
I found this answer very useful, but I needed to declare the destination variable Global: to make it work in my PowerShell console. For reasons I don't understand it worked as-is if run in PowerShell ISE, but using ISE is not an option for my application.
Simply put I changed:
$destination = <full path>
to$Global:destination = <full path>
I think someone has commented below that this can be done using Set-Variable - probably amounts to the same thing.
Tuesday, July 3, 2018 5:11 PM -
Hi How do you revert back after running the script?
please help
Wednesday, June 19, 2019 2:48 PM -
Just do:
Unregister-Event -SourceIdentifier FileCreated
Regards
Stefan LousbergTuesday, September 17, 2019 10:47 AM