You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中Move-Item无法移动当前目录内容至新子目录求助

问题解决:PowerShell移动有声书文件失败排查与修复

问题分析

你的脚本能正确提取作者名、创建目标目录,但无法移动*.ico、*.m4b、*.jpg文件且无报错,核心原因是:

  • Get-ChildItem默认不读取隐藏文件,如果这些有声书关联文件是隐藏属性,会被直接跳过
  • 原脚本创建子目录时未处理“目录已存在”的情况,可能静默终止后续操作(但你反馈脚本看似成功,大概率是隐藏文件的问题)

修复后的完整脚本

param([switch]$Elevated)
function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Test-Admin) -eq $false)  {
    if ($elevated) {
        # 提权失败,终止执行
        exit
    } else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
        exit
    }
}
'已获取管理员权限'
$mainDir = "E:\scripttest"
# 获取主目录下所有子目录
$directories = Get-ChildItem -Path $mainDir -Directory
foreach ($dir in $directories) {
    # 匹配"作者 - 书名[...]"格式的目录名
    if ($dir.Name -match "^(.*?) - (.*)$") {
        $author = $matches[1].Trim()
        $title = $matches[2].Trim()
        $authorDir = Join-Path -Path $mainDir -ChildPath $author
        # 仅当作者目录不存在时创建
        if (-not (Test-Path -Path $authorDir)) {
            New-Item -Path $authorDir -ItemType Directory | Out-Null
        }
        $newSubDir = Join-Path -Path $authorDir -ChildPath $title
        # 强制创建子目录,已存在时不报错
        New-Item -Path $newSubDir -ItemType Directory -Force | Out-Null
        # 读取源目录下所有文件(含隐藏文件)并移动
        Get-ChildItem -Path $dir.FullName -File -Force | ForEach-Object {
            Move-Item -Path $_.FullName -Destination $newSubDir -Force -ErrorAction Stop
        }
        # 可选:移动完成后删除原空目录
        # Remove-Item -Path $dir.FullName -Force
    }
}

关键修复点说明

  • Get-ChildItem添加-Force:强制读取隐藏文件,确保所有有声书关联文件被识别
  • Get-ChildItem添加-File:只处理文件,避免误移动原目录下的子目录(如果存在)
  • New-Item添加-Force:子目录已存在时不抛出错误,保证脚本执行流畅
  • Move-Item添加-ErrorAction Stop:移动失败时抛出明确错误,方便排查问题
  • .Trim()处理作者/书名:去除匹配结果前后的多余空格(比如原目录名中-后的空格)

测试建议

  1. 先复制测试目录到E:\scripttest,避免误操作真实文件
  2. 执行脚本后检查目标目录是否包含所有ico、m4b、jpg文件
  3. 若仍有问题,执行Get-ChildItem -Path 原目录路径 -Force,确认是否能列出所有文件

内容的提问来源于stack exchange,提问作者wrx20l

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 19:53:29