Windows 将文件夹名称前置到数组中的路径
我希望使用foreach语句在(相对)路径数组的开头加上一个文件夹名,但它没有对数组进行任何更改(也没有错误) 注意:这更多是出于教育目的,而不是功能性目的,因为我使用了一个我已经注释掉的for循环,但我对学习foreach语句的工作方式感兴趣Windows 将文件夹名称前置到数组中的路径,windows,powershell,filenames,string-concatenation,prepend,Windows,Powershell,Filenames,String Concatenation,Prepend,我希望使用foreach语句在(相对)路径数组的开头加上一个文件夹名,但它没有对数组进行任何更改(也没有错误) 注意:这更多是出于教育目的,而不是功能性目的,因为我使用了一个我已经注释掉的for循环,但我对学习foreach语句的工作方式感兴趣 $myFiles = @( "blah1\blah2\file1.txt" "blah3\blah4\file2.txt" "blah5\blah6\file3.txt" ) $checkoutFolder = "folder1
$myFiles = @(
"blah1\blah2\file1.txt"
"blah3\blah4\file2.txt"
"blah5\blah6\file3.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
但同样的结果是。
输出:
最好开始使用
Join-Path
cmdlet,以避免创建省略或加倍反斜杠的路径
像这样的东西可以做到:
$checkoutFolder = "folder1"
$myFiles = "blah1\blah2\file1.txt", "blah3\blah4\file2.txt", "blah5\blah6\file3.txt" | ForEach-Object {
Join-Path -Path $checkoutFolder -ChildPath $_
}
$myFiles
输出:
我可以想出两种方法: 使用已修改的旧阵列数据创建新阵列
$myFiles = @(
"blah1\blah2\file1.txt"
"blah3\blah4\file2.txt"
"blah5\blah6\file3.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 = @(
"blah1\blah2\file1.txt"
"blah3\blah4\file2.txt"
"blah5\blah6\file3.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
可以用文件夹名称替换每个字符串的正则表达式开头。这也是生成计算机名的一个有用的习惯用法
'blah1\blah2\file1.txt','blah3\blah4\file2.txt','blah5\blah6\file3.txt' -replace '^','folder1\'
folder1\blah1\blah2\file1.txt
folder1\blah3\blah4\file2.txt
folder1\blah5\blah6\file3.txt
您的主要问题是在循环中重新使用“当前循环项”。除非有必要,否则不要这样做。[grin]您的
$Buffer
具备您所需的功能。。。所以直接用吧,我们没有你的消息。。给出的答案解决了你的问题吗?如果是,请点击✓ 在左边。这将帮助其他有类似问题的人更容易地找到它。
$myFiles = @(
"blah1\blah2\file1.txt"
"blah3\blah4\file2.txt"
"blah5\blah6\file3.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
'blah1\blah2\file1.txt','blah3\blah4\file2.txt','blah5\blah6\file3.txt' -replace '^','folder1\'
folder1\blah1\blah2\file1.txt
folder1\blah3\blah4\file2.txt
folder1\blah5\blah6\file3.txt