Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用PowerShell将位于多个目录中的文件的第一行分配给每个文件的变量?_Powershell - Fatal编程技术网

如何使用PowerShell将位于多个目录中的文件的第一行分配给每个文件的变量?

如何使用PowerShell将位于多个目录中的文件的第一行分配给每个文件的变量?,powershell,Powershell,数据集 C:\temp\powershelltest\ \目录1\test.txt \目录2\test.txt \目录3\test.txt \test.ps1 目录[0-9]\test.txt 文件目录[0-9] 地狱世界 企图 test.ps1 $content=获取内容C:\temp\powershelltest\dir.[0-9]\test.txt 写入主机$content[0] 结果 当前结果 PS C:\Windows\system32>。C:\temp\powershelltest\

数据集

C:\temp\powershelltest\ \目录1\test.txt \目录2\test.txt \目录3\test.txt \test.ps1 目录[0-9]\test.txt

文件目录[0-9] 地狱世界 企图

test.ps1

$content=获取内容C:\temp\powershelltest\dir.[0-9]\test.txt 写入主机$content[0] 结果

当前结果

PS C:\Windows\system32>。C:\temp\powershelltest\test.ps1 文件dir1 预期结果

PS C:\Windows\system32>。C:\temp\powershelltest\test.ps1 文件dir1 文件dir2 文件dir3 获取内容不使用Regex进行过滤,而是使用。我会用Get ChildItem和你的wilcards来解决这个问题。注意,您还需要指定Recurse以从子文件夹中获取结果

获取子项C:\temp\powershelltest\dir.[0-9]-Recurse-Filter test.txt ForEach对象{Get Content$\ FullName | Select Object-First 1} 这将从每个包含dir的test.txt文档中提取第一行。后跟一位数字表示父目录

其结果是:

PS C:\Windows\system32>。C:\temp\powershelltest\test.ps1 文件dir1 文件dir2 文件dir3
@乌得勒支我现在批准了编辑。我的解决方案必须已经完成循环。我将使用您的数据集进行测试,看看会发生什么。还修复了丢失的}的语法错误。这是我在ISE之外编写代码时得到的。@utrecht因此text.txt中的第一行包含文件dir,目录号在哪里?@utrecht用您的数据样本对此进行了测试。合并您的gci路径,因为它更干净,然后使用where子句。无需分配给变量,因为它将直接输出到控制台或问题:Get ChildItem C:\temp\powershell\dir。[0-9]应为Get ChildItem C:\temp\powershelltest\dir。[0-9]@utrecht我只使用C:\temp\powershell进行了测试。我甚至没有注意到。我更新了它。谢谢