我有一个包含三个文件的目录:.xlsx,.docx和.txt,在同一目录中也有名为xlsx,docx和txt的文件夹。基本上是尝试将每个文件放入其相应的文件夹中,以练习PowerShell的技能。我是PowerShell的新手,并尝试了以下方法。我可以说出它的错误,但我不太确定为什么。
$folders = Get-ChildItem -Directory
$files = Get-ChildItem -File
foreach ($file in $files) {
foreach ($folder in $folders) {
if ("*$file.extension*" -like "*$folder.Name*") {
move-item $file -Destination "C:\Users\userA\Desktop\$folder.name"
}
}
}
请尝试下面的代码。使用Where-Object
功能,您可以找到相应的文件。我删除了该点,因为否则它包含在扩展名中。
$folders = Get-ChildItem -Directory
$files = Get-ChildItem -File
foreach ($file in $files) {
$folder = $folders | Where-Object { $_.Name -Like $file.Extension.Replace(".","") }
Move-Item -Path $file -Destination $folder
}
在您的示例中,请注意字符串的实际解释方式。如果您有"*$item.Name*"
,则字符串实际上为“ * 变量。Name *”。在这种情况下,您需要使用"*$($var.Name)*"
来获取正确的字符串。
以下是对您的方法进行的一些调整,使其可以使用。将-Destination参数分解为一个单独的变量$ newpath,可以在其中设置调试语句,以便可以轻松检查其创建内容。
$folders = Get-ChildItem -Directory
$files = Get-ChildItem -File
foreach ($file in $files) {
foreach ($folder in $folders) {
if ($file.extension.trim(".") -like $folder.Name) {
$newpath = ("{0}\{1}" -f $folder.FullName, $file.Name)
move-item $file -Destination $newpath
}
}
}
如果扩展名还不存在,您甚至可以为其创建目标文件夹:
$SourceFolder = C:\sample
$TargetFolder = D:\sample
Get-ChildItem -Path $SourceFolder -File |
ForEach-Object{
$DesinationFolder = Join-Path -Path $TargetFolder -ChildPath $_.Extension.TrimStart('.')
if(-not (Test-Path -Path $DesinationFolder)){
New-Item -Path $DesinationFolder -ItemType Directory | Out-Null
}
Copy-Item -Path $_.FullName -Destination $DesinationFolder -Force
}