我需要使用基于名称存储在目录中的文件的文件名来填充powershell数组。我需要为每组文件使用不同的数组(请参阅示例文件夹结构)以用作另一个进程的一部分。
我希望这是自动的并且动态创建数组,所以我的数组包含以processor123
开头的所有文件名,另一个包含processorabc
和processorxyz
的文件名。这些数组的名称可以存储在另一个名为$arrynames
的数组中。如果引入了新的处理器,它需要是动态的,我不想依赖用户输入文件名。
示例文件夹结构;
c:\directory\processor123\processor123.log.20150604
c:\directory\processor123\processor123.log.20150603
c:\directory\processor123\processor123.log.20150602
c:\directory\processor123\processor123.log.20150601
c:\directory\processor123\processor123.log.20150531
c:\directory\processorabc.log.20150604
c:\directory\processorabc.log.20150603
c:\directory\processorabc.log.20150602
c:\directory\processorabc.log.20150601
c:\directory\processorabc.log.20150531
c:\directory\processorxyz.log.20150604
c:\directory\processorxyz.log.20150603
c:\directory\processorxyz.log.20150602
c:\directory\processorxyz.log.20150601
c:\directory\processorxyz.log.20150531
$ ArryNames
processor123
processorabc
processorxyz
$ processor123
c:\directory\processor123\processor123.log.20150604
c:\directory\processor123\processor123.log.20150603
c:\directory\processor123\processor123.log.20150602
c:\directory\processor123\processor123.log.20150601
c:\directory\processor123\processor123.log.20150531
$ processorabc
c:\directory\processorabc.log.20150604
c:\directory\processorabc.log.20150603
c:\directory\processorabc.log.20150602
c:\directory\processorabc.log.20150601
c:\directory\processorabc.log.20150531
答案 0 :(得分:1)
那么,你想要为每个字符串做些什么:
正如评论中已经提到的,您可以使用哈希表来保存数组,文件前缀是关键:
# Set up a hashtable
$HashTable = @{}
# Pipe your list of file paths to ForEach-Object
Get-Content C:\filenames.txt |ForEach-Object {
# Extract the filename with [System.IO.Path]::GetFileName(), split it by dots and grab only the part before the first dot
$Prefix = [System.IO.Path]::GetFileName($_) -split "\." |Select-Object -First 1
# Use the extracted prefix to place the string in the correct hashtable entry
$HashTable[$Prefix] += $_
}
现在,您可以使用$HashTable["processor123"]