0

我有以下 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"}
4

1 回答 1

0

我相信它按预期工作。如果副本实际上是动作的一部分,请尝试在动作脚本块内移动该行。

变量 $name 在动作脚本块之外是空的,因为 ObjectEvent 有自己的范围。如果您需要从 Action 脚本块外部访问此变量,您可以使用 $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"
}
于 2015-02-16T10:10:10.603 回答