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

时间:2014-06-19 08:57:15

标签: 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\$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写入五个首先复制的文件夹,依此类推。

E.g。它看起来像那样:Fish1中的prefs.js中的“Plane”,Fish2,Fish3,Fish4,Fish5。 Fish6,Fish7,Fish8,Fish9,Fish10等中的prefs.js中的“Car”。

1 个答案:

答案 0 :(得分:2)

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

我不知道你是如何枚举文件夹的,但是这会增加每5个文件夹增量($ i)的值数组索引($ ValIdx),增加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。