【问题标题】:Powershell script to create folders from list of names in a filePowershell脚本从文件中的名称列表创建文件夹
【发布时间】:2018-04-28 17:42:04
【问题描述】:

我有一个文本文件,其中包含不同目录中的文件列表,例如

  • C:\FolderOne\Testing.jpg
  • C:\FolderTwo\Test.jpg

我想把这些名字变成文件夹。如果两个文件存在于一个文件夹中,例如FolderOne,那么这两个文件都应该放在同一个文件夹中。

我知道反斜杠也必须替换为下划线,冒号也必须替换为下划线。

到目前为止,我能够从文件列表中获取内容并将其复制到指定的文件夹中。我想为文件列表中的每个文件创建一个文件夹,但是文件夹名称需要包括C_FolderOneC_FolderTwo等等....

任何帮助将不胜感激!

到目前为止我所拥有的:

Param (
    [String]$model
)

# Debug line
$model = "DEV2";

[String]$drive = "C:";

#Go to the PG_dump directory
CD "C:\Program Files\PostgreSQL\9.4\bin"

##Execute PG_dump with no password
.\pg_dump.exe --host localhost --port 5432 --username "postgres" --role "postgres" --no-password  --format custom --blobs --verbose --file     "C:\Test\$date-DEV-$X.backup" "DEV"

#Get the content from the file list
$file_list = Get-Content "$drive\Testing\DEV33.txt" 
foreach ($file in $file_list)
{    
    Copy-Item  $file -Destination "C:\Testing"
}

【问题讨论】:

  • 您的问题不清楚。你到底想做什么?
  • 在“work”文件夹下创建的路径(例如 - “C:\Testing”)是否包含多个段(例如 - C:\Folder A\Folder A - Sub Folder 0\ ...\filename.jpg")?
  • @TheIncorrigible1 基本上,尝试为文件列表中的每个文件创建一个文件夹。创建的文件夹应以文件夹的路径命名,例如,如果名为“Winter.jpg”的文件位于“C:\TestFolder\Winter.jpg”,则应创建名为 C_TestFolder 的文件夹。
  • @codemaker 你好,是的,在“work”文件夹下创建的路径可以包含多个段。
  • (Split-Path -Path $Path -Parent) -replace ':\\','_' @TheManBehindTheMan 制定逻辑以捕获 `\\` 的其余部分

标签: windows powershell scripting directory copy-item


【解决方案1】:

这是一种执行您所要求的方法。它将获取文件的父路径并创建目标文件夹。

## Get the content from the file list.
foreach ($file in Get-Content -Path "$drive\Testing\DEV33.txt") {
    $name = (Split-Path -Path $file -Parent) -replace '\\', '_' -replace ':'
    New-Item -Path "path\to\$name" -ItemType Directory
}

【讨论】:

  • 我欠你鸡翅我的朋友或任何你喜欢的东西哈哈。通过一些调整,它完全符合我的要求!非常感谢。
  • @TheManBehindTheMan 太棒了!请投票/标记为答案。需要进行哪些调整?
  • 我必须添加一个 if 语句,以便如果文件夹不存在,则应该创建它。但是,我已向您投了赞成票,因为我的声誉低于 15,因为我才加入,我会看到一条消息,说它已被记录但不会更改公开显示的分数。亲切的问候。
  • @TheManBehindTheMan 如果将-Force 添加到New-Item,它将自动创建文件夹结构。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多