我正在尝试将文件从一个文件夹移动到另一个文件夹,下面是我提出的PowerShell代码:
$folder = 'C:\test'
$filter = '*.*' # <-- set this according to your requirements
$destination = 'C:\Folder1'
$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"
#$UNI_PRINT = Select-String -Path C:\Test\*.Print_Job -Pattern "SATO"\\
$file = Get-Content -Path $folder
$containsWord = $file | %{$_ -match "SATO"}
if ($containsWord -contains $true)
{
Write-Host Contains String
Move-Item $path -Destination $destination -Force -Verbose # Force will overwrite files with same name
}
else
{
Write-Host Not Contains String
}
}
C:\ test文件夹连续获得5到6个扩展名为.Print_Job的文件。
所以我编写了Filecreated事件,以便我可以持续监视文件夹以检查文件是否已创建。
在内部我想根据以下标准阅读每个文件的内容。
我怎样才能在poweshell中做到这一点。
期待您的解决方案。
提前致谢。
答案 0 :(得分:2)
修改现在适用于要求。
Get-Variable
评估目标文件夹,如果不存在则创建并移动文件(使用可选的-whatif)## Q:\Test\2018\04\27\SO_50067617.ps1
$directory_source = '.\*'
$directory_target_motorola = 'c:\test\folder1'
$directory_target_sato = 'c:\test\folder2'
$directory_target_zebra = 'c:\test\folder3'
$FilePattern = @{}
Get-ChildItem $directory_source -File | Select-String "(MOTOROLA|SATO|ZEBRA)" |
ForEach-Object {
$FilePattern[$_.FileName] = $_.Matches.Value
}
$FilePattern.GetEnumerator() | ForEach-Object {
$Target = (Get-Variable "directory_target_$($_.Value)").Value
If (!(Test-Path $Target)) { md $Target }
mv $_.Name $Target -whatif
}
答案 1 :(得分:1)
这样的事情应该有用......
$directory_source = '<path>'
$directory_target_motorola = '<path>'
$directory_target_sato = '<path>'
$directory_target_zebra = '<path>'
$files = $(ls $directory)
foreach ($file in $files) {
if ( $(gc $file | Select-String "motorola" -Quiet) ) {
mv -Path $file.Fullname -Destination $directory_target_motorola
} elseif ( $(gc $file | Select-String "sato" -Quiet) ) {
mv -Path $file.Fullname -Destination $directory_target_sato
} elseif ( $(gc $file | Select-String "zebra" -Quiet) ) {
mv -Path $file.Fullname -Destination $directory_target_zebra
}
}
注意,我没有尝试过这个。
祝你好运。