你能告诉我如何将同一个PowerShell源应用于多个文件夹吗



我有一个可用的PowerShell源。但是,您需要将同一PowerShell源应用于文件夹中的多个子文件夹。

有一个"-"在子文件夹名称的中间。有数百个文件夹。我想立即应用PowerShell源。我没有学习PowerShell。请告诉我。

要应用的PowerShell源如下所示。

$Subfolder=Get-location
$Fullname=(Split-path $Subfolder -Leaf).ToString();
$di=$Fullname.IndexOf("-");
$Fnametoend=$Fullname.SubString($di);
$Fnametoend=$Fnametoend.TrimStart("-")
foreach($dir in $Subfolder){
$path=$Subfolder
$dir
Get-Childitem -Path $path -Filter "*.jpeg" -File |
Group-Object -Property @{Expression = {$_.Fnametoend}}|
ForEach-Object {
$dir=$Fnametoend
$nr=1
foreach($file in $_.Group){
$file | Rename-item -Newname("{0}_2020_{1}.jpeg"-f $dir, $nr++)
}
}
}

项目文件夹中有许多子文件夹,jpeg文件也在这些子文件夹中。

当我进入项目文件夹并运行PowerShell时,我希望在众多子文件夹中的每个子文件夹中运行PowerShell源。

这是项目文件夹的示例图片。

在此处输入图像描述

像这样,我想应用项目文件夹中多个子文件夹中的PowerShell源。不幸的是,我正在通过逐个单击文件夹来应用powershell源代码。

我想一次将PowerShell源应用于所有文件夹。你能帮忙吗?我想一次将powershell源应用于所有文件夹。

如果将根文件夹设置为Get-Location,则只有一个路径(脚本从其中运行(
您需要做的是定义源文件夹的路径,然后使用Get-ChildItem迭代其中的所有子文件夹。

在下面的代码中,我放了很多代码注释,所以您应该能够遵循它所采取的每一步。

# enter the path to where all subfolders to process are.
$rootFolder = 'D:Test'
# find all '*.jpeg' files in the subfolders. 
# -Depth 1 ensures it only searches in subfolders 1 level deep under the root folder.
# If these have subfolders of their own you need to go through, either remove '-Depth 1'
# or set a higher number of levels to search through.
Get-Childitem -Path $rootFolder -Filter "*.jpeg" -File -Recurse -Depth 1 |
# make sure the folder the files are in has a hyphen in its name
Where-Object { $_.Directory.Name -like '*-*' } |
# group the found files on the last part after the '-' in the folder name
Group-Object @{Expression = {($_.Directory.Name -split '-')[-1]}} |
ForEach-Object {
# $_.Name is the name of the group, which we set to ($_.Directory.Name -split '-')[-1]
$nr = 1
# loop through all files in the group and rename
foreach($file in $_.Group){
$file | Rename-item -Newname ("{0}_2020_{1}.jpeg"-f $_.Name, $nr++)
}
}

示例:

之前

D:TEST
+---ASWQ-12H4JV7S
|       AnotherPicture.jpeg
|       SomePicture.jpeg
|
---QWEQ-8E8W4G44
Arnold.jpeg
Bruce.jpeg
Lee.jpeg
Schwartzenegger.jpeg

之后

D:TEST
+---ASWQ-12H4JV7S
|       12H4JV7S_2020_1.jpeg
|       12H4JV7S_2020_2.jpeg
|
---QWEQ-8E8W4G44
8E8W4G44_2020_1.jpeg
8E8W4G44_2020_2.jpeg
8E8W4G44_2020_3.jpeg
8E8W4G44_2020_4.jpeg