我正在尝试创建一个powershell脚本来处理目录中的文件,但是当尝试使用-recurse
param时,我只移动整个文件夹文件。
# where $source = C:\Files
# and my folder 'Files' have two subfolders '001' and '002' with files inside
Get-ChildItem -Path $source -Recurse -Filter * |
ForEach-Object {
# Get the current date
$date = (Get-Date).ToString();
# Add to log file
Add-Content -Path $log " $date - The file $_ was moved from $source to $target";
# Show on cmdlet
Write-Host " $date - O arquivo $_ foi transferido de $source para $target";
# Move items
Move-Item $_.FullName $target;
}
当我在cmdlet上尝试此命令Get-ChildItem -Path $source -Recurse ...
时,工作正常。
答案 0 :(得分:2)
正如EBGreen指出的那样,您正在枚举文件夹和文件。要在版本2中对其进行过滤,您可以执行以下操作:
Get-ChildItem -Path $source -Recurse -Filter * |
Where-Object { -not $_.PSIsContainer } |
ForEach-Object {
# Get the current date
$date = (Get-Date).ToString();
# Add to log file
Add-Content -Path $log " $date - The file $_ was moved from $source to $target";
# Show on cmdlet
Write-Host " $date - O arquivo $_ foi transferido de $source para $target";
# Move items
Move-Item $_.FullName $target;
}
当项目是容器(文件夹)而不是叶子(文件)时,.PSIsContainer
属性返回true。
在PowerShell v3及更高版本中,您可以这样做:
Get-ChildItem -Path $Source -Directory -Recurse -Filter *