powershell - 在 Powershell 中创建文件夹和移动文件

标签 powershell

我见过类似的问题,并将它们用作我在这里尝试做的事情的基础。我有一个文件夹,其中包含许多文件,其名称类似于“作者姓名 - 书名.azw”。

我想为每个作者创建子文件夹,并将他们的所有书籍移至该文件夹中。这是我到目前为止的脚本。它成功地为作者创建了文件夹,但它在移动项目上卡住了,说找不到路径的一部分。

$files = Get-ChildItem -file

foreach ($file in $files){

$title = $file.ToString().Split('-') 
$author = $title[0]
if (!(Test-Path $author))
{
    Write-Output "Creating Folder $author"
    New-Item -ItemType Directory -Force -Path $author
}

Write-Output "Moving $file to $author" 
Move-Item -Path $file -Destination $author -Force
}

最佳答案

你必须使用这个:


Get-ChildItem -file | foreach {
  $title = $_.ToString().Split('-') 
  $author = $title[0]
  if (!(Test-Path $author))
  {
    Write-Host "Creating Folder $($author)"
    New-Item -ItemType Directory -Force -Path "$author"
   }

  Write-Host "Moving $($_) to $($author)" 
Move-Item -Path "$_" -Destination "$author" -Force
}

您必须将文件路径用双引号引起来。所以你的代码不起作用。

关于powershell - 在 Powershell 中创建文件夹和移动文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59517101/

相关文章:

c# - Powershell 中的 HashSet : Collection was of a fixed size

powershell - 从内部方法访问$ args/params

algorithm - 如何使用 Powershell 获取证书的安全哈希算法

arrays - Powershell 根据元素的数量返回不同的数据类型

powershell - 在工作时间之间运行 PowerShell if 语句

powershell - 在 powershell 中创建目录快捷方式

.net - 为什么在 Get-SPWeb 中引发的错误不会传播到 powershell?

arrays - 查找两个 PowerShell 数组中的共同项

powershell - powershell变量内联扩展作为cmdlet参数?

powershell - 如何使用输出文件在同一行上打印多个值