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

PowerShell提取文件名前缀并移动文件至对应文件夹的技术需求

PowerShell Solution: Extract Prefix & Move Files to Corresponding Folders

Got it, let's work through this problem. The core goal is to grab that leading prefix (before the first space) from each filename, create a folder named after that prefix, and move the file into it—even when the prefix length varies. Here's a robust, ready-to-use script with explanations:

# Define the path where your files are located
$sourcePath = "C:\Path\To\Your\Files"

# Get all files in the source directory (skip folders)
$files = Get-ChildItem -Path $sourcePath -File

foreach ($file in $files) {
    # Extract the prefix: everything before the first whitespace
    # Using regex for reliability—matches all non-whitespace characters at the start
    if ($file.BaseName -match '^(\S+)') {
        $prefix = $matches[1]
    } else {
        # Fallback: if no spaces in filename, use the full base name as prefix
        $prefix = $file.BaseName
    }

    # Build the target folder path (inside the source directory)
    $targetFolder = Join-Path -Path $sourcePath -ChildPath $prefix

    # Create the folder if it doesn't already exist
    if (-not (Test-Path -Path $targetFolder)) {
        New-Item -ItemType Directory -Path $targetFolder | Out-Null
        Write-Host "Created folder: $targetFolder"
    }

    # Move the file to the target folder
    # Add -WhatIf to the end first to test without moving files!
    Move-Item -Path $file.FullName -Destination $targetFolder -Force
    Write-Host "Moved file: $($file.Name) -> $targetFolder"
}

Key Details & Customization Tips:

  • Update the source path: Replace C:\Path\To\Your\Files with the actual directory holding your files.
  • Regex prefix extraction: The ^(\S+) regex ensures we grab every character from the start of the filename until the first space—works no matter how long the prefix is. If a filename has no spaces, the fallback uses the full filename as the prefix.
  • Testing first: Add -WhatIf to the Move-Item line (like Move-Item ... -Force -WhatIf) to run a dry test. This shows you what files would be moved where without actually making changes.
  • Overwriting behavior: The -Force parameter lets the script overwrite files with the same name in the target folder. If you don't want this, remove -Force—the script will prompt you before overwriting.

Example Walkthrough:

For a file named X02348957 RANDOM WORDS HERE.txt:

  1. The script extracts X02348957 as the prefix.
  2. Creates a folder C:\Path\To\Your\Files\X02348957 if it doesn't exist.
  3. Moves X02348957 RANDOM WORDS HERE.txt into that folder.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:48:11