我有以下的powershell脚本,不像我想的那样工作。我想将源文件夹($ folder)中新创建的文件复制到我的目标文件夹($ DestFolder),但不复制任何文件。有谁看到可能出错的地方?
$SourceFolder = 'd:\temp\' # Enter the root path you want to monitor.
$folder = 'd:\temp' # Enter the root path you want to monitor.
$Destfolder = 'd:\temp2\' # Enter the root path you want to monitor.
$global:MySourceFolder = 'd:\temp\' # Enter the root path you want to monitor.
$global:MyDestfolder = 'd:\temp2\' # Enter the root path you want to monitor.
$filter = '*.*' # You can enter a wildcard filter here.
# In the following line, you can change 'IncludeSubdirectories to $true if required.
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
#Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
Write-Host "path : $MyDestfolder$name" -fore green
Copy-Item (Join-Path $MySourceFolder $name) ($Destfolder)
Out-File -FilePath d:\temp\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}
答案 0 :(得分:0)
我相信它按预期工作。如果副本实际上是操作的一部分,请尝试在动作脚本块中移动该行。
变量$ name在action scriptblock之外是空的,因为ObjectEvent有自己的范围。如果需要从Action scriptblock外部访问此变量,可以使用$ global:name。
声明变量以下内容确实应该可以使用(替换为此但保存代码副本,以便首先获得备份)
$folder = 'd:\temp'
$Destfolder = 'd:\temp2'
$filter = '*.*'
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
IncludeSubdirectories = $false
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
Copy-Item -Path (Join-Path $folder $name) -Destination $Destfolder
Out-File -FilePath "d:\temp\filechange\outlog.txt" -Append -InputObject "The file '$name' was $changeType at $timeStamp"
}