2014-06-19 54 views
0

这是现在我的脚本:如何在PowerShell中将相同的变量写入x次?

[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-- 
} 

我想实现的事情是,我会写$变量1至五个第一复制文件夹等。

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

+0

请退后一步并描述实际问题正在努力解决,而不是你认为的解决方案。你想通过这样做来达到什么目的? –

+3

如果您必须使用100个变量,请使用[array](http://technet.microsoft.com/zh-cn/library/hh847882.aspx)。 – vonPryz

回答

2

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

我不知道你是怎么得到的文件夹列举,但是这会增加数值数组索引($ 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正在评估它为布尔(真/假)并返回相反的值。 $ ValIdx是一个[int],所以布尔值被强制为[int]用于+ =操作。

当$ i是5的倍数时,($ i%5)为零,它会以$ false的形式投射到[bool]。 -not会将其翻转为$ true。如果它不是5的倍数,($ i%5)将返回一个非零值,该值将转换为$ true,并翻转为$ false。

对于+ =操作,当布尔型转换为[int]时,它对于$ true变为1或对于$ false变为0。最终的结果是,每当$ i达到5的倍数,$ ValIdx就会增加1.如果它不是5的倍数,$ ValIdx会增加0.

+0

感谢您的回答!这些文件夹是用$ DestinationDirectory枚举的。但是没有办法用变量来做到这一点,因为实际上我的变量的长度非常长,所以PITA将它们全部放入数组中。 (为了说明一个变量的长度 - “Mozilla/5.0(Windows NT 6.1; Avant TriCore)AppleWebKit/537.36(KHTML,像Gecko)Chrome/31.0.1650.63 Safari/537.36” – JohannesTK

+1

这是可能的,但会产生大量的开销如果他们这么长时间,我会认为你会把他们存储在一个文件中,并且只会做一个$ values = get-content 。 – mjolinor

+0

Okey。详细说明你的答案中的代码?我似乎无法完全理解它,因为我还是一个初学者。 – JohannesTK