PowerShell获取文件列表踩坑

PowerShell获取文件列表踩坑

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

初步实现

假设有一个路径如下:

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

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

perl 复制代码
$file_list=Get-ChildItem ./ -Recurse  abc_*
​
for ($i=0; $i -lt $file_list.Length; $i++)
{
    write-host $i":" $file_list[$i].FullName
}

运行结果如下:

makefile 复制代码
0: E:\Test\abc_a.txt
1: E:\Test\abc_b.txt
2: E:\Test\abc_d.txt

把上面的abc_*换成a_*

perl 复制代码
$file_list=Get-ChildItem ./ -Recurse  a_*
​
for ($i=0; $i -lt $file_list.Length; $i++)
{
    write-host $i":" $file_list[$i].FullName
}

运行结果如下:

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

咋这样了呢?

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

查看了一下:

bash 复制代码
PS E:\Test> cat .\a_bcd.txt
01234
​
PS E:\Test> $file_list.Length
16

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

所以不能用Length,改成Count。

优化实现

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

运行结果:

makefile 复制代码
0: E:\Test\a_bcd.txt

进阶实现

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

perl 复制代码
$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均可。

相关推荐
J***Q29218 小时前
DevOps金融服务安全要求
运维·安全·devops
D***t13118 小时前
DevOps技能提升路径
运维·devops
小奶包他干奶奶1 天前
Webpack学习——原理理解
学习·webpack·devops
N***73851 天前
DevOps在金融科技中的安全合规
科技·金融·devops
mzlogin2 天前
借助 Let's Encrypt 节省 SSL 证书费用
后端·devops
U***e632 天前
DevOps在云原生中的Service Mesh
云原生·devops·service_mesh
4***99742 天前
DevOps在云原生中的CI/CD流水线
ci/cd·云原生·devops
S***y3962 天前
DevOps监控告警体系
运维·devops
S***q1923 天前
DevOps在云中的云计算
运维·云计算·devops
青靴3 天前
虚拟机上实现最简 CI/CD
ci/cd·devops