【发布时间】:2017-03-13 08:53:09
【问题描述】:
我想创建一个文件观察器并使用 PowerShell 执行以下流程:
注意文件夹A中的文件(.zip)→将文件移动到文件夹B(.zip)→解压缩文件夹C中移动的文件(同名)→并触发批处理文件→对更多传入的.zip执行相同操作文件。
我在 StackOverflow 中检查了 related question,但我需要更多帮助。
我的 PowerShell 脚本如下(我使用的是 PowerShell ISE):
while ($true) {
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "D:\LocalData\Desktop\folderA"
$watcher.Filter = "*.zip*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
$tempfolder = "D:\LocalData\Desktop\folderA\folderB"
$outpath = "D:\LocalData\Desktop\folderA\folderB\folderC"
#Function to Unzip the moved item
Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip {
Param([string]$path, [string]$outpath)
[System.IO.Compression.ZipFile]::ExtractToDirectory($path, $outpath)
}
$action = {
$path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$name = $Event.SourceEventArgs.Name
Move-Item $path $tempfolder
Unzip $path $outpath -Force # this line is not being read, it goes to the function block, and slips down to the action block
$logline = "$(Get-Date), $changeType, $path" # no log is generated
Add-Content -Path "d:\LocalData\folderA\Watcherlog.log" $logline
Start-Process -Path "d:\LocalData\process.bat"
}
Register-ObjectEvent $watcher "Created" -Action $action
Start-Sleep 2
}
Unregister-Event -SourceIdentifier FileCreated
【问题讨论】:
-
将
Unzip定义移动到脚本块中。 -
谢谢@AnsgarWiechers --> scriptblock - 你的意思是我必须在动作块内移动 Unzip 函数。?如果我误解了你的回复,我很抱歉,你能指导我更多吗?
-
是的,我就是这个意思。
-
@AnsgarWiechers 不,仍然无法正常工作。
标签: powershell powershell-3.0 filesystemwatcher