如何将相同的变量x次写入PowerShell中的文件?

如何将相同的变量x次写入PowerShell中的文件?,powershell,Powershell,这是我现在的脚本: [int]$NumberOfProfiles = Read-Host "Enter the number of profiles You need" $WhereToWrite = Read-Host "Enter the full path where You'd like to install the profiles" $Source = Get-Location $FolderName = "Fish" $SourceDirectory = "$Source\

这是我现在的脚本:

[int]$NumberOfProfiles = Read-Host "Enter the number of profiles You need"
 $WhereToWrite = Read-Host "Enter the full path where You'd like to install the profiles" 

$Source = Get-Location 
$FolderName = "Fish"
$SourceDirectory = "$Source\$Foldername"

$Variable1 = "Plane"
$Variable2 = "Car"
...
$Variable100 = "Boat"

while ($NumberOfProfiles -gt 0) {
  $DestinationDirectory = Join-Path $WhereToWrite "$Foldername$NumberOfProfiles"
  $PrefsDirectory = "$DestinationDirectory\Data\profile\prefs.js"
$Changer = Get-Variable -Name "Variable$NumberOfProfiles" -ValueOnly 
  Copy-Item $SourceDirectory $DestinationDirectory -Recurse -Container
    Write-Host "Made a new profile to" $DestinationDirectory
        (Get-Content $PrefsDirectory) | %{$_.Replace("SomeInfo", "Changer")} | Set-Content $PrefsDirectory 
$NumberOfProfiles--
}
我希望实现的是,我将$Variable1写入五个第一次复制的文件夹,以此类推


例如,在Fish1、Fish2、Fish3、Fish4、Fish5中,prefs.js中的“平面”看起来像这样。Fish6、Fish7、Fish8、Fish9、Fish10等中prefs.js中的“Car”

将值放入数组,并使用数组索引选择要写入的值

我不知道如何枚举文件夹,但这将使数组索引值($ValIdx)每5个文件夹增量($I)增加一次,增加500个文件夹增量:

$values = ("15","45"..."72")
$ValIdx = 0

for ($i = 1;$i -le 500;$i++)
 {
   '{0} {1}' -f $i,$ValIdx  #Write $Values[$ValIdx] to $folders[$i] here
   $valIdx += -not ($i % 5)
}
解释-模运算符(%)返回除法运算的剩余部分。($i%5)将$i除以5,并返回余数。-not将其作为布尔值(true/false)进行计算并返回相反的值$ValIdx是一个[int],因此布尔值被强制为+=操作的[int]

当$i是5的倍数时,($i%5)为零,这将向[bool]强制转换为$false。而-not会将其转换为$true。如果不是5的倍数,($i%5)将返回一些非零值,该值将转换为$true,并转换为$false


当+=运算的布尔值被强制转换为[int]时,对于$true,它变为1;对于$false,它变为0。最终结果是,每当$i达到5的倍数时,$ValIdx就会增加1。如果不是5的倍数,$ValIdx将增加0。

请后退一步,描述您试图解决的实际问题,而不是您认为的解决方案。您希望通过这样做实现什么?如果必须使用100个变量,请使用。谢谢您的回答!已使用$DestinationDirectory枚举文件夹。但是对于变量没有任何方法可以做到这一点,因为实际上我的变量的长度非常长,所以把它们都放到数组中是非常困难的。(举例说明一个变量的长度——“Mozilla/5.0(Windows NT 6.1;Avant TriCore)AppleWebKit/537.36(KHTML,如Gecko)Chrome/31.0.1650.63 Safari/537.36”这是可能的,但会带来巨大的开销,这显然是一种不好的做法。如果它们那么长,我想你会把它们存储在一个文件中,然后只做$values=get content。好的。但是你能不能在你的答案中详细说明一下代码?我似乎不能完全理解,因为我还是一个初学者。这是对t的解释他回答。嘿!但是我怎么能改变它,当$I除以5时,它已经增加了$Validx的值。例如,$I=6,那么它首先从$values数组中取“15”,然后从$values数组中取“45”。它对我不起作用,因为我现在使用的是while循环和$NumberOfProfiles的读取主机。请参见图示-