【发布时间】:2019-02-18 08:12:54
【问题描述】:
正在处理一个项目,我需要用不同的前缀替换“path prefix”。自动复制文件,然后我将在本地使用这些文件。我认为与其制作新变量,不如重新利用复制完成后不需要的旧变量。循环遍历数组时遇到替换问题。我能够为这种特殊情况找到解决方案,但想了解为什么我的循环不起作用
没有显示任何错误来告诉我为什么它不工作。
任何帮助理解为什么循环时替换不起作用会有所帮助
我如何构建路径的示例代码
[string]$Root_Path = "\\Main_Blah_Path\"
[string]$Software = $Root_Path + "Software\"
[string]$Adobe_Reader = $Software + "Adobe_Reader\"
[string]$Firefox = $Software + "Firefox\"
[string]$Google_Chrome = $Software + "Google_Chrome\"
[System.Collections.ArrayList]$List_Of_Software = @(
$Adobe_Reader
$Firefox
$Google_Chrome
)
我进行替换的方法示例。这些工作并将所需的输出写入控制台
foreach ($Path in $List_Of_Software) {
$Path -replace '\\\\Main_Blah_Path\\','C:\Folder\'
}
$List_Of_Software | ForEach-Object {$_ -replace '\\\\Main_Blah_Path\\','C:\Folder\'}
我遇到的失败示例。我无法替换并将数据保存到自身中以进行替换。我根本无法让.replace 工作
foreach ($Path in $List_Of_Software) {
$Path = $Path -replace '\\\\Main_Blah_Path\\','C:\Folder\'
}
$List_Of_Software | ForEach-Object {$_ = $_ -replace '\\\\Main_Blah_Path\\','C:\Folder\'}
foreach ($Path in $List_Of_Software) {
$Path.Replace('\\\\Main_Blah_Path\\','C:\Folder\')
}
我在当前场景中使用的解决方案,但我可以预见到未来的一些事情,这种方法可能不是一个可行的选择
$List_Of_Software = $List_Of_Software -replace '\\\\Main_Blah_Path\\','C:\Folder\'
【问题讨论】:
标签: arrays powershell loops replace