[英]Powershell script to locate only files starting with specified letters and ending with .csv
cd 'A:\P\E\D'
$files = Get-ChildItem . *.CSV -rec
ForEach ($file in $files) {
(Get-Content $file -Raw) | ForEach-Object {
*some simple code*
} | Set-Content $file
}
How to modify this powershell script to locate only files starting with letters A/a to O/o and ending with.csv in specified directory cd?如何修改此 powershell 脚本以仅在指定目录 cd 中定位以字母 A/a 到 O/o 并以 .csv 结尾的文件?
I thought the solution below would work, but the test file M_K_O_X.CSV stored in the cd directory was not found and modified.原以为下面的解决方法可以,但是cd目录下存放的测试文件M_K_O_X.CSV找不到修改。 The solution above will find and modify the file.上面的解决方案将找到并修改文件。 It's possible that I have the regex expression wrong or the problem is somewhere else?可能是我的正则表达式错误或者问题出在其他地方? I tried also this regex -- "[AO] . .CSV"我也试过这个正则表达式——“[AO ] ..CSV”
cd 'A:\P\E\D'
$files = Get-ChildItem . -rec | Where-Object { $_.Name -like "[a-oA-O]*.*.CSV" }
ForEach ($file in $files) {
(Get-Content $file -Raw) | ForEach-Object {
*some simple code*
} | Set-Content $file
}
Looking at your wildcard pattern , seems like you have an extra *.
查看您的通配符模式,似乎您有一个额外的*.
that shouldn't be there:那不应该在那里:
'M_K_O_X.CSV' -like '[a-oA-O]*.*.CSV' # False
'M_K_O_X.CSV' -like '[a-oA-O]*.CSV' # True
In this case you could simply use the -Include
Parameter which supports character ranges.在这种情况下,您可以简单地使用支持字符范围的-Include
参数。 Also PowerShell is case insensitive by default, [a-oA-O]*.CSV
can be reduced to [ao]*.CSV
:另外 PowerShell 默认不区分大小写, [a-oA-O]*.CSV
可以简化为[ao]*.CSV
:
Get-ChildItem 'A:\P\E\D' -Recurse -Include '[a-o]*.csv' | ForEach-Object {
($_ | Get-Content -Raw) | ForEach-Object {
# *some simple code*
} | Set-Content -LiteralPath $_.FullName
}
As commented, I would use the standard wildcard -Filter to filter for all files with a.csv extension.如评论所述,我将使用标准通配符 -Filter 来过滤所有扩展名为 .csv 的文件。
Then pipe to a Where-Object clause in which you can use regex -match
然后 pipe 到 Where-Object 子句,您可以在其中使用 regex -match
$files = Get-ChildItem -Path 'A:\P\E\D' -Filter '*.csv' -File -Recurse |
Where-Object { $_.Name -match '^[a-o]' }
foreach ($file in $files) {
# switch `-Raw` makes Get-Content return a single multiline string, so no need for a loop
$content = Get-Content -Path $file.FullName -Raw
# *some simple code manipulating $content*
$content | Set-Content -Path $file.FullName
}
However, if these are valid csv files, I would not recommend using a pure textual manipulation on them, instead use Import-Csv -Path $file.FullName
and work on the properties on each of the objects returned.但是,如果这些是有效的 csv 文件,我不建议对它们使用纯文本操作,而是使用Import-Csv -Path $file.FullName
并处理返回的每个对象的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.