首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Powershell,批量移动特定类型的文件

Powershell,批量移动特定类型的文件
EN

Stack Overflow用户
提问于 2011-08-23 01:50:10
回答 3查看 16.6K关注 0票数 6

我想做一个脚本,这将采取一个父目录,其中有许多子目录,其中有文件。使用一个列表,我希望将子目录中的所有文件移到父目录中。

到目前为止,我已经创建了以下代码,它列出了子目录中指定类型的所有文件,但我不确定如何批量移动所有子文件。

代码语言:javascript
运行
复制
    Write-host "Please enter source Dir:"
$sourceDir = read-host

Write-Host "Format to look for with .  :"
$format = read-host

#Write-host "Please enter output Dir:"
#$outDir = read-host

$Dir = get-childitem -Path $sourceDir -Filter $format -recurse | format-table name

$files = $Dir | where {$_.extension -eq "$format"} 
$files #| format-table name
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-08-23 04:29:02

以下是一些事情:

  1. 您可以将写入屏幕的文本直接传递给读取主机cmdlet,这样可以为每个用户输入节省一行。
  2. 根据经验,如果您计划对命令的输出执行更多操作,请不要将其通过管道传输到-*cmdlet格式。格式化cmdlet生成格式化对象,指示powershell如何在屏幕上显示结果。
  3. 尽量避免将结果赋值给变量,如果结果包含大量文件系统,内存消耗可能会非常高,并且您可能会在性能方面遇到性能问题,请尝试使用cmdlet参数而不是where-object cmdlet(服务器端筛选与客户端筛选)。前者过滤目标上的对象,而后者仅在get到达您的计算机后过滤对象。

WhatIf开关将显示要移动的文件。删除它以执行命令。您可能还需要twick它来处理重复的文件名。

代码语言:javascript
运行
复制
$sourceDir = read-host "Please enter source Dir"
$format = read-host "Format to look for"

Get-ChildItem -Path $sourceDir -Filter $format -Recurse | Move-Item -Destination $sourceDir -Whatif
票数 12
EN

Stack Overflow用户

发布于 2011-08-23 02:58:21

如果我没理解错的话,您可以在文件上使用Move-Item将它们移动到输出目录:

代码语言:javascript
运行
复制
$Dir = get-childitem $sourceDir -recurse
$files = $Dir | where {$_.extension -eq "$format"}
$files | move-item -destination $outDir
票数 4
EN

Stack Overflow用户

发布于 2017-12-07 14:36:34

之前的一个帖子指出,该脚本将覆盖同名的文件。通过测试扩展脚本并避免这种可能性是可能的。如下所示:

代码语言:javascript
运行
复制
$sourceDir = read-host "Please enter source Dir"
$format = read-host "Format to look for?"
$destDir = read-host "Please enter Destination Dir"

Get-ChildItem -Path $sourceDir -Filter $format -Recurse | Copy-Item   -Destination $DestDir 
$files = $DestDir | where {$_.extension -eq "$format"} 

If (Test-Path $files) {
    $i = 0
    While (Test-Path $DestinationFile) {
        $i += 1
        $DestinationFile = "$files$i.$format"
        Copy-Item -Destination $DestDir  $DestinationFile
    }
} 
Else {
    $DestinationFile = "$files$i.$format"
    Copy-Item -Destination $DestDir $DestinationFile
}
Copy-Item -Path $SourceFile -Destination $DestinationFile -Force
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7151408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档