【问题标题】:PowerShell, search specific directories for specific filenamePowerShell,在特定目录中搜​​索特定文件名
【发布时间】:2013-09-07 10:57:00
【问题描述】:

我现在有一个程序将文件名输出到控制台。

我想给它一系列目录来搜索(按顺序)搜索以找到该文件名,如果找到,则复制到另一个目录。

我已经走到这一步了:

[string]$fileName = "document12**2013" #** for wildcard chars
[bool]$found = false
Get-ChildItem -Path "C:\Users\Public\Documents" -Recurse | Where-Object { !$PsIsContainer -and GetFileNameWithoutExtension($_.Name) -eq "filename" -and $found = true }

if($found = true){
Copy-Item C:\Users\Public\Documents\ c:\test
}

就目前而言,我有两个问题。我只知道如何浏览一个目录,我不知道如何指定脚本来复制我刚刚找到的特定文件。

【问题讨论】:

    标签: search powershell directory copy


    【解决方案1】:

    Path 参数接受一组路径,因此您可以指定多个。您可以使用 Filter 参数获取您要查找的文件名,并将结果通过管道传送到 Copy-Item cmdlet:

    Get-ChildItem -Path C:\Users\Public\Documents,$path2,$path3 -Recurse -Filter $fileName | 
    Copy-Item -Destination $Destination
    

    【讨论】:

    • 只要您一次只搜索一个目录,这会变得非常容易dir C:\Users -recurse -filter "filename.txt" -File
    【解决方案2】:

    您可以在一个管道中完成所有这些操作:

    $folders = 'C:\path\to\folder_A', 'C:\path\to\folder_B', ...
    
    $folders | Get-ChildItem -Recurse -Filter filename.* |
        ? { -not $_.PSIsContainer } | Copy-Item -Destination 'C:\test\'
    

    请注意,如果您在Copy-Item 中使用文件夹作为目标,则必须有一个尾部反斜杠,否则 cmdlet 将尝试将文件夹 C:\test 替换为文件 @987654324 @,会报错。

    【讨论】:

    • 您不需要通过管道将路径传递给gci。查看@ShayLevy 的回答
    • 我们不知道路径来自哪里,因此可能(或可能没有)管道代替$folders。使用 Shay 的方法,您必须先将其结果分配给变量,或者将其作为子表达式运行。
    【解决方案3】:

    把它包装成一个函数怎么样?

    使用谢伊的方法:

    function copyfile($path,$fileName,$Destination) {
    Get-ChildItem -Path  $path -Recurse -Filter $fileName | 
    Copy-Item -Destination $Destination
    }
    
    $path1=C:\Users\Public\Documents
    $path2=C:\Users\Public\Music
    $path3=C:\Users\Public\Pictures
    
    copyfile $path1 corporate_policy.docx \\workstation\c$\users\Public\Documents
    copyfile $path2 intro_from_ceo.mp3 \\workstation\c$\users\Public\Music
    copyfile $path3 corporate_logo.jpg \\workstation\c$\users\Public\Pictures
    

    【讨论】:

      猜你喜欢
      • 2010-12-21
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多