将文件夹名称前置到数组中的路径



我希望使用foreach语句在(相对(路径数组的开头预加一个文件夹名称,但它不会对数组进行任何更改(也没有错误(

注意:这更多的是为了教育目的,而不是功能性的,因为我使用了一个我已经评论过的for循环,但我有兴趣学习foreach语句是如何工作的

$myFiles = @(
"blah1blah2file1.txt"
"blah3blah4file2.txt"
"blah5blah6file3.txt"
)
$checkoutFolder = "folder1"
#for ($h = 0; $h -lt $myFiles.Length; $h++) {
#$myFiles[$h] = $checkoutFolder + "" + $myFiles[$h]
#}
foreach ($path in $myFiles) {
$path = $checkoutFolder + "" + $path
}
$myFiles

我还尝试使用缓冲变量,例如

$buffer = $checkoutFolder + "" + $path
$path = $buffer

但相同的结果,即。输出:

blah1blah2file1.txt
blah3blah4file2.txt
blah5blah6file3.txt

我可以想出两种方法:

使用旧阵列的修改数据创建新阵列

$myFiles = @(
"blah1blah2file1.txt"
"blah3blah4file2.txt"
"blah5blah6file3.txt"
)
$checkoutFolder = "folder1"
#Create new array $myFilesnew
$myFilesnew = @()
#For each line in in old array
foreach ($file in $myFiles)
{
#Create new row from modied row $file of $myFiles array
$row = $checkoutFolder+""+$file
#Add row $row to a new array $myFilesnew
$myFilesnew+=$row
}
$myFilesnew

修改现有阵列的每一行:

$myFiles = @(
"blah1blah2file1.txt"
"blah3blah4file2.txt"
"blah5blah6file3.txt"
)
$checkoutFolder = "folder1"
$i=0
while($i-lt $myFiles.Count)
{
#Get $i row $myFiles[$i] from aray, perform insert of modified data, write data back to $myFiles[$i] row of the array
$myfiles[$i]=$myFiles[$i].Insert(0,$checkoutFolder+"");
#Add +1 to $i
$i++
}
$myFiles

最好开始使用Join-Pathcmdlet,以避免创建省略或加倍反斜杠的路径。

像这样的东西可以做到:

$checkoutFolder = "folder1"
$myFiles = "blah1blah2file1.txt", "blah3blah4file2.txt", "blah5blah6file3.txt" | ForEach-Object {
Join-Path -Path $checkoutFolder -ChildPath $_
}
$myFiles

输出:

folder1blah1blah2file1.txt
folder1blah3blah4file2.txt
folder1blah5blah6file3.txt

您可以将每个字符串的regex开头替换为文件夹名称。这对于生成计算机名也是一个有用的习惯用法。

'blah1blah2file1.txt','blah3blah4file2.txt','blah5blah6file3.txt' -replace '^','folder1'
folder1blah1blah2file1.txt
folder1blah3blah4file2.txt
folder1blah5blah6file3.txt

相关内容

  • 没有找到相关文章

最新更新