Powershell - 为目录中的文件创建目录
Powershell - create directories form files in a dierectory
我正在尝试通过创建子目录然后将文件复制到新目录来清理和分组目录中的文件。
示例:
test01.a.jpg
test01.a.txt
test01.b.bak
test01.b.txt
test02.a.txt
test02.a.jpg
test02.a.bak
test03.a.txt
test03.a.bak
test03.b.txt
我希望创建子目录,如 test01
、test02
、test03
,最好将相关文件复制过来。所有组都会有一个 txt 文件,但或多或少会有其他文件。
要创建我目前得到的目录
gci -file *.txt | New-Item -ItemType directory $_.name
没有按预期工作。
如果你的文件有这样的名字,你可以简单地在点上拆分文件名,只取第一部分作为新文件夹名。
然后测试这样的子文件夹是否已经存在(如果不创建)并移动文件。
像这样
$sourcePath = 'D:\Test' # put the real path to the files here
# if you want only the files with extension .txt, use filter '*.*.txt'
(Get-ChildItem -Path $sourcePath -File -Filter '*.*.*') | ForEach-Object {
# use the first part of the file name for subdirectory name
$destinationPath = Join-Path -Path $sourcePath -ChildPath $_.Name.Split(".")[0]
if (!(Test-Path -Path $destinationPath -PathType Container)) {
# if a subdirectory with that name does not already exist, create it
$null = New-Item -Path $destinationPath -ItemType Directory
}
# now move the file to that (new) destination folder
$_ | Move-Item -Destination $destinationPath
}
其实算法很简单(之前不需要比较文件名,只需要$_.BaseName 属性)
<#Creating folders and moving files using BaseName property #>
gci *.txt | % { new-item -ItemType Directory -Path ($_.Directory.ToString() + "\" + $_.BaseName.ToString())}
gci -file | % { Move-item $_.Fullname ($_.Directory.ToString() + "\" + $_.BaseName.ToString())}
我正在尝试通过创建子目录然后将文件复制到新目录来清理和分组目录中的文件。
示例:
test01.a.jpg
test01.a.txt
test01.b.bak
test01.b.txt
test02.a.txt
test02.a.jpg
test02.a.bak
test03.a.txt
test03.a.bak
test03.b.txt
我希望创建子目录,如 test01
、test02
、test03
,最好将相关文件复制过来。所有组都会有一个 txt 文件,但或多或少会有其他文件。
要创建我目前得到的目录
gci -file *.txt | New-Item -ItemType directory $_.name
没有按预期工作。
如果你的文件有这样的名字,你可以简单地在点上拆分文件名,只取第一部分作为新文件夹名。
然后测试这样的子文件夹是否已经存在(如果不创建)并移动文件。 像这样
$sourcePath = 'D:\Test' # put the real path to the files here
# if you want only the files with extension .txt, use filter '*.*.txt'
(Get-ChildItem -Path $sourcePath -File -Filter '*.*.*') | ForEach-Object {
# use the first part of the file name for subdirectory name
$destinationPath = Join-Path -Path $sourcePath -ChildPath $_.Name.Split(".")[0]
if (!(Test-Path -Path $destinationPath -PathType Container)) {
# if a subdirectory with that name does not already exist, create it
$null = New-Item -Path $destinationPath -ItemType Directory
}
# now move the file to that (new) destination folder
$_ | Move-Item -Destination $destinationPath
}
其实算法很简单(之前不需要比较文件名,只需要$_.BaseName 属性)
<#Creating folders and moving files using BaseName property #>
gci *.txt | % { new-item -ItemType Directory -Path ($_.Directory.ToString() + "\" + $_.BaseName.ToString())}
gci -file | % { Move-item $_.Fullname ($_.Directory.ToString() + "\" + $_.BaseName.ToString())}