如何使用Powershell将数组读入特定文件中的变量以使用Powershell中的变量
问题描述:
如何使用PowerShell将文件中的数据从文件读入变量? 我ListOfFileNames.txt具有都是这样的一个数组:如何使用Powershell将数组读入特定文件中的变量以使用Powershell中的变量
#Begin ArrayOneList:
Filename4.txt
FilenameD.png
myone.exe
#Begin ArrayTwo:
myFile2.txt
Filename1.gif
#Begin ArrayNextOne:
speficifFile.doc
ExcelFile.xls
File3.png
AnotherFile.png
logFile.log
现在我想读入数组变量和PowerShell中与他们合作:
$ArrayOneList = Get-Content C:\Scripts\ListOfFileNames.txt
foreach($File in $ArrayOneList)
{
$Weekday = $File.LastWriteTime.DayOfWeek
$Destination = "D:\Test\$Weekday"
Copy-Item $File.FullName -Destination $Destination -Recurse
}
$ArrayTwo = Get-Content C:\Scripts\ListOfFileNames.txt
foreach($File in $ArrayTwo)
{
$Weekday = $File.LastWriteTime.DayOfWeek
$Destination = "E:\Dir\Dest"
Copy-Item $File.FullName -Destination $Destination -Recurse
}
$ArrayNextOne= Get-Content C:\Scripts\ListOfFileNames.txt
foreach($File in $ArrayNextOne)
{
$Weekday = $File.LastWriteTime.DayOfWeek
$Destination = "E:\Dir\SpecificDirectory"
Copy-Item $File.FullName -Destination $Destination -Recurse
}
我怎样才能阅读所有的数组从一个文件到变量?
答
你可以这样做:
param(
[parameter(Mandatory=$true)]
[string[]]$myarr
)
参考THIS例子也
在你的情况,你可以这样做:
param(
[parameter(Mandatory=$False)]
[string[]][email protected]("ArrayOneList","ArrayTwo","ArrayNextOne")
)
答
如果你可以使用JSON作为格式你的输入文件,你可以简单地“反序列化”数组。示例:
PS C:\temp> [string[]]$array = @("1","2","3")
PS C:\temp> ConvertTo-Json $array
[
"1",
"2",
"3"
]
PS C:\temp> ConvertTo-Json $array | Out-File array.json
PS C:\temp> Get-Content .\array.json | ConvertFrom-Json
1
2
3
PS C:\temp> [string[]]$array2 = Get-Content .\array.json | ConvertFrom-Json
PS C:\temp> $array2.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String[] System.Array
PS C:\temp> $array2
1
2
3
要使用多个数组,您可以创建一个包含这些数组的哈希表。例如:
PS C:\temp> $arr1 = @("1","2")
PS C:\temp> $arr2 = @("3","4")
PS C:\temp> $arrays = @{"arr1"=$arr1; "arr2"=$arr2}
PS C:\temp> $arrays
Name Value
---- -----
arr1 {1, 2}
arr2 {3, 4}
PS C:\temp> $arrays | ConvertTo-Json
{
"arr1": [
"1",
"2"
],
"arr2": [
"3",
"4"
]
}
PS C:\temp> $arrays | ConvertTo-Json | Out-File hash.json
PS C:\temp> $recreatedHash = get-content .\hash.json | ConvertFrom-Json
PS C:\temp> $recreatedHash
arr1 arr2
---- ----
{1, 2} {3, 4}
希望帮助
+0
对不起,这似乎是专家可以理解,但不适合我。我在哪里打电话给我的ListOfFileNames.txt?我在哪里声明阵列“ArrayOneList,ArrayTwo,ArrayNextOne ...”的名称? – Mailo
答
这里是阅读,其中部分由空行分隔的文本文件的内容(小)的解决方案:
# First read the file as one string
$a = Get-Content 'D:\temp\test.txt' -raw
# Get your arrays (here on the fact that the separator is an empty line
$b = $a -split '\n\r'
# Use array One
foreach ($file in $($b[0] -split '\n'))
{
}
# You can use $b[1] for file two etc...
难道我已经像这样调用它?:Powershell.exe -File“MyScriptPath-ps1”“ArrayOneList,ArrayTwo,ArrayNextOne”如何在不从外部调用数组的情况下使用这些参数,而只能从脚本内部调用这些参数? – Mailo
@Mailo:是的,你必须这样打电话。我给出的链接,你可以看到一些例子 –
没有例子说明如何在不从外部调用参数的情况下使用它。我只想调用poweeshellfile.ps1 withouth参数 – Mailo