SOLVED-PSCP无法从FOR循环中的ip数组检索,但可以在FOREACH中使用?

问题描述 投票:0回答:3

我有一个powershell脚本,所以基本上我需要将文件从多个源传输到一个本地。在这种情况下,我不想使用pslurp。

[基本上,如果我在for循环中运行数组,我会得到多个远程源...错误,但是为什么每个原因都起作用?

现在问题是我无法更改目标路径,因为我不知道让我的目标数组在foreach循环中运行的位置。如果我指定一个源IP,它可以循环发送到diff目标。因此,我的数组和循环在技术上可以正常工作。

总体代码(不起作用,有更多的远程源不支持错误)

$ArrayIP=@("[email protected]","[email protected]")
$ArrayDestination=@("C:/Users/me/save01","C:/Users/me/save01"}

for (i=0; i -le2; i++){
pscp -pw testing -r $ArrayIP[i]":"/cf/conf/backup/* $ArrayDestination[i]
}

所以我更改为FOREACH ...,但现在我不知道如何将其保存到其他目标位置?出于测试目的,我用两种方法都指定了一个目标位置并且它可以工作。我不再遇到一个以上的远程源错误。

foreach ($IP in $ArrayIP){
pscp -pw testing -r $IP":"/cf/conf/backup/* <insert destination? dk how to make it run an arrayDestination>
}

现在,我在考虑是否应该执行2D数组...这将有助于我在foreach循环中运行不同的变量吗?或者,如果有人可以使用object命令指导我...我已经阅读了有关它的论坛,但仍不确定如何使用]

arrays powershell for-loop foreach pscp
3个回答
0
投票

有两件事使您的第一个样本无法正常工作:

首先,您当前的for循环无效-PowerShell中的变量名称以$开头:

for ($i=0; $i -le 2; $i++){
   ...
}

第二,PowerShell将命令行参数视为可扩展字符串,并且数组索引操作无法在字符串中正确扩展-包含在子表达式$()中以正确扩展引用的数组索引:

for ($i=0; $i -le 2; $i++){
    pscp -pw testing -r "$($ArrayIP[$i]):/cf/conf/backup/*" "$($ArrayDestination[$i])"
}

0
投票

您可以尝试这个,用不会与文件名冲突的字符串值连接目标路径和IP,并在循环内按该值分割。

$Array=@("[email protected]:/Users/me/save01","[email protected]:/Users/me/save01")

foreach ($Entry in $ArrayIP){
    $Split = $Entry -split '--'
    pscp -pw testing -r "$Split[0]:/cf/conf/backup/*" $Split[1]
}

0
投票

第一次使用Powershell?这接近第一个示例。使用@()制作数组是很多人迷恋的神话。我喜欢使用单引号,除非里面有一个变量。

$ArrayIP = '[email protected]', '[email protected]'
$ArrayDestination = 'C:/Users/me/save01', 'C:/Users/me/save01'

for ($i=0; $i -lt 2; $i++){
  pscp -pw testing -r ($ArrayIP[$i] + ':/cf/conf/backup/*') $ArrayDestination[$i]
}

我像这样用pscp测试了该行,以确保我得到正确的字符串。使用其他方法,我最终在两者之间留有多余的空格。

for ($i=0; $i -lt 2; $i++){
  cmd /c echo pscp -pw testing -r ($ArrayIP[$i] + ':/cf/conf/backup/*') $ArrayDestination[$i]
}

pscp -pw testing -r [email protected]:/cf/conf/backup/* C:/Users/me/save01
pscp -pw testing -r [email protected]:/cf/conf/backup/* C:/Users/me/save01

这里有些杂物,有很多哈希。或者,您可以导入一个csv。

$hashes = @{source='[email protected]:/cf/conf/backup/*'; destination='C:/Users/me/save01'},
          @{source='[email protected]:/cf/conf/backup/*'; destination='C:/Users/me/save01'}

foreach ($item in $hashes) {
  pscp -pw testing -r $item.source $item.destination
}

© www.soinside.com 2019 - 2024. All rights reserved.