使用powershell根据文件名移动/创建文件夹/子文件夹

使用powershell根据文件名移动/创建文件夹/子文件夹,powershell,Powershell,我在powershell方面没有太多经验,但我有需要组织的文件。这些文件都是pdf格式,格式类似于“Dept123\u Name\u year.pdf” 我想将文档移动到基于“Dept123”和子文件夹“Name”的文件夹中。如果文件夹尚未存在,我希望它创建文件夹/子文件夹 为了方便起见,我考虑在桌面上创建一个“组织”文件夹,并在上面运行程序。如果你认为换个方法会容易些,请告诉我 提前感谢。您可以使用正则表达式匹配文件名的不同组件,然后基于此生成目录结构。mkdir的-Force参数允许您忽略目

我在powershell方面没有太多经验,但我有需要组织的文件。这些文件都是pdf格式,格式类似于“Dept123\u Name\u year.pdf”

我想将文档移动到基于“Dept123”和子文件夹“Name”的文件夹中。如果文件夹尚未存在,我希望它创建文件夹/子文件夹

为了方便起见,我考虑在桌面上创建一个“组织”文件夹,并在上面运行程序。如果你认为换个方法会容易些,请告诉我


提前感谢。

您可以使用正则表达式匹配文件名的不同组件,然后基于此生成目录结构。
mkdir
-Force
参数允许您忽略目录是否已存在:

$list = ls
for ($i=0; $i -le $list.Length; $i++) {
    if ($list[$i].Name -match '([A-Za-z0-9]+)_([A-Za-z]+)_.*\.pdf') {
        $path = Join-Path $matches[1] $matches[2]
        mkdir -Force -Path $path
        cp $list[$i] "$path\."
    }
}

正则表达式部分在引号中;您可能需要修改它以满足您的特定需要。请注意,圆括号中的部分对应于所提取名称的不同部分;这些部件按顺序加载到自动生成的
$matches
变量中。例如,
'([A-Za-z0-9]+)\.txt'
将匹配名称中仅包含字母或数字的任何文本文件,并将使用正则表达式和完整形式的Powershell将实际名称(减去扩展名)粘贴到
$matches[1]

中:

# using ?<name> within a () block in regex causes powershell to 'name' the property 
# with the given name within the automatic variable, $matches, object.
$Pattern = "(?<Dept>.*)_(?<Name>.*)_(?<Year>.*)\.pdf"

# Get a list of all items in the current location.  The location should be set using
# set-location, or specified to the command by adding -Path $location
$list = Get-ChildItem

# Foreach-Object loop based on the list of files
foreach ($file in $list) {
    # send $true/$false results from -matches operation to $null
    $File.Name -matches $Pattern 2> $Null

    # build destination path from the results of the regex match operation above
    $Destination = Join-Path $matches.Dept $matches.Name

    # Create the destination if it does not exist
    if (!(Test-Path $Destination) ) { 
        New-Item -ItemType Directory -Path $destination 
    }

    # Copy the file, keeping only the year part of the name
    Copy-Item $file "$destination\$($matches.year)"+".pdf"
}
#使用什么?在regex的()块中,会导致powershell“命名”属性
#在自动变量$matches对象中使用给定名称。
$Pattern=“(?*)\u(?.*)\ u(?.*)\.pdf”
#获取当前位置中所有项目的列表。应使用以下命令设置位置:
#设置位置,或通过添加-Path$location指定给命令
$list=获取子项
#基于文件列表的Foreach对象循环
foreach($列表中的文件){
#将$true/$false结果从-matches操作发送到$null
$File.Name-匹配$Pattern 2>$Null
#根据上面正则表达式匹配操作的结果生成目标路径
$Destination=加入路径$matches.Dept$matches.Name
#如果目标不存在,则创建该目标
如果(!(测试路径$Destination)){
新项目-项目类型目录-路径$destination
}
#复制文件,仅保留名称的年份部分
复制项目$file“$destination\$($matches.year)”+“.pdf”
}

问题是什么?到目前为止您尝试了什么?
获取帮助
获取命令
获取成员
。用这些来学习你的方法。
Get Alias
cmdlet将帮助您确定与您所知道的CMD命令相当的PS。因此,请尝试
Get Alias dir
Get Alias cd
dir
Get ChildItem
的别名,因此您可以使用
Get Help GetChildItem
了解如何使用它。在web上搜索Powershell教程。操作文件是通常用于说明脚本概念的任务。为了获得最佳结果,请使用此论坛获取有关您编写的代码的帮助,这些代码会生成错误或其他意外结果。(显示代码和错误)谢谢。我喜欢最后一部分的想法,但有几次需要发送或复制这些文件,所以去掉名称的前半部分没有什么意义。无论如何,您的代码帮助我更好地理解powershell。我将最后一行更改为
移动项目$file“$Destination\$($file.Name)”
。但是,如果我不止一次地使用代码(在文件最初分类之后),它会开始将所有其他文件夹移动到另一个文件夹中。我没办法弄明白。