PowerShell获取文件列表踩坑

PowerShell-getlist

PowerShell获取文件列表踩坑

Powershell强大的函数库,确实很方便,但是也有些坑。

初步实现

假设有一个路径如下:

image-20240324110625507

需要获取abc_开头还有a_开头的的文件列表, 并打印/处理

按照常规思路,简单写一个:

$file_list=Get-ChildItem ./ -Recurse  abc_*

for ($i=0; $i -lt $file_list.Length; $i++)
{
    write-host $i":" $file_list[$i].FullName
}

运行结果如下:

0: E:\Test\abc_a.txt
1: E:\Test\abc_b.txt
2: E:\Test\abc_d.txt

把上面的abc_*换成a_*

$file_list=Get-ChildItem ./ -Recurse  a_*

for ($i=0; $i -lt $file_list.Length; $i++)
{
    write-host $i":" $file_list[$i].FullName
}

运行结果如下:

0: E:\Test\a_bcd.txt
1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
10: 
11: 
12: 
13: 
14: 
15: 

咋这样了呢?

发现是当文件只有一个的时候,就会翻车!

查看了一下:

PS E:\Test> cat .\a_bcd.txt
01234

PS E:\Test> $file_list.Length
16

此时的$file_list.Length代表的是$file_list文件的长度

所以不能用Length,改成Count。

优化实现

$file_list=Get-ChildItem ./ -Recurse  a_*

for ($i=0; $i -lt $file_list.Count; $i++)
{
    write-host $i":" $file_list[$i].FullName
}

运行结果:

0: E:\Test\a_bcd.txt

进阶实现

保险起见,将这个$file_list定义为数组。

$file_list=@()
$file_list+=Get-ChildItem ./ -Recurse  a_*
for ($i=0; $i -lt $file_list.Count; $i++)
{
    write-host $i":" $file_list[$i].FullName
}

用Count还是Length均可。


【更多干货分享】

  • 微信公众号"Lucas-Den"(Lucas.D)

相关推荐

  1. VSCode之PowerShell中创建项目

    2024-03-24 13:36:06       31 阅读
  2. koa-session获取不到session记录

    2024-03-24 13:36:06       15 阅读
  3. php获取文件列表(所有子目录文件)

    2024-03-24 13:36:06       17 阅读
  4. mySQL记录

    2024-03-24 13:36:06       43 阅读
  5. Pinia 记录

    2024-03-24 13:36:06       33 阅读
  6. FollowYourPose 安装

    2024-03-24 13:36:06       29 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-24 13:36:06       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-24 13:36:06       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-24 13:36:06       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-24 13:36:06       18 阅读

热门阅读

  1. cookie、session和token的区别

    2024-03-24 13:36:06       21 阅读
  2. 读《舞!舞!舞!》有感

    2024-03-24 13:36:06       19 阅读
  3. SpringBoot全局异常处理方法

    2024-03-24 13:36:06       19 阅读
  4. 【Node.js】events

    2024-03-24 13:36:06       21 阅读
  5. 【jvm】young gc full gc

    2024-03-24 13:36:06       16 阅读
  6. Python爬虫之urllib库

    2024-03-24 13:36:06       17 阅读
  7. 游戏中线上已有功能迭代的兼容问题

    2024-03-24 13:36:06       17 阅读
  8. Python爬虫之requests库

    2024-03-24 13:36:06       15 阅读