【问题标题】:Powershell script to list ,in reverse order, files recursively, similarly to this bash scriptPowershell 脚本以相反的顺序递归地列出文件,类似于此 bash 脚本
【发布时间】:2018-04-08 15:26:51
【问题描述】:

我正在尝试将此 bash 脚本转换为 powershell。我这样做是因为适用于 Linux 的 Windows 子系统目前无法在 Google Drive File System 安装的驱动器上运行,因此我需要使用 powershell。

背景

我需要在顶级父文件夹上运行这个 powershell 脚本,以在大约 700,000 个深度嵌套的文件夹中导入 8700 万个 json 文件。我愿意接受更好的方法。

我的 Bash 解决方案

#!/bin/sh

function import_from_start() {
    echo "starting import from front"
    find "$1" -name '*.json' | while read file; do
        mongoimport --host=datalake7 --db=CA_facebook_copy --collection=test_import --type="json" --file="$file"
    done
}

function import_from_end() {
    echo "starting import from back end"
    find "$1" -name '*.json' | sort -r | cut -f2 | while read file; do
        mongoimport --host=datalake7 --db=CA_facebook_copy --collection=test_import --type="json" --file="$file"
    done
}

import_from_start "$1" &
import_from_end "$1"

我当前尝试的 powershell 脚本

param (
    [Parameter(Mandatory=$true)][string]$Src,
    [Parameter(Mandatory=$true)][string]$Collection
 )

$Extension = '*.json'
Get-ChildItem -Path $Src -Filter $Extension -Recurse | Where-Object {!$_.PsIsContainer} | ForEach-Object {

    .\mongoimport.exe --host datalake7 --db CA_facebook_copy --collection $Collection --type json --file $_.FullName
}

我的目标

我需要同时从文件列表的开头和结尾导入。我正在使用这种方法,因为它为每个文件创建和销毁与 mongodb 的连接非常慢。

【问题讨论】:

  • 什么不起作用?还是它有效,您只需要向后排序?还是只是为了放慢速度?
  • 我需要同时从文件列表的开头和结尾导入。我使用这种方法是因为为每个文件创建和销毁与 mongodb 的连接非常慢。
  • 鉴于您为每个文件名调用mongoimport,您的 Bash 方法如何不会每次都创建新的 MongoDB 连接?鉴于cut 的默认分隔符是\t,cut -f2 的意义何在?鉴于这两个命令最终会处理 all 文件,您如何防止处理同一个文件两次?
  • 你是对的,确实如此。但是由于某种我不知道的原因,它在 powershell 中比 bash 慢得多。为了回答您的第二个问题,我在 json id 上使用了唯一键,因此跳过了重复项。

标签: powershell


【解决方案1】:

现在排序可以基于任何列。因此,在您的情况下,您可以获取所有文件 fullname.length 因为您使用了 fullname 并且可以按降序对其进行排序。

替换

Get-ChildItem -Path $Src -Filter $Extension -Recurse | Where-Object {!$_.PsIsContainer} | ForEach-Object {

    .\mongoimport.exe --host datalake7 --db CA_facebook_copy --collection $Collection --type json --file $_.FullName
}

有了这个:

Get-ChildItem -Path $Src -Filter $Extension -Recurse | Where-Object {!$_.PsIsContainer} | ForEach-Object {

    .\mongoimport.exe --host datalake7 --db CA_facebook_copy --collection $Collection --type json --file $_.FullName
}| Sort-Object @{expression = {$_.fullname.length}} -descending

我在 foreach 循环之后添加了排序对象部分。

希望对你有帮助。

【讨论】:

  • | Sort-Object @{expression = {$_.fullname.length}} -descending 是我所需要的。谢谢!
猜你喜欢
  • 2013-06-29
  • 2011-10-31
  • 1970-01-01
  • 2010-10-05
  • 1970-01-01
  • 2011-12-25
  • 2021-12-18
  • 2017-10-23
  • 2011-08-23
相关资源
最近更新 更多