I am searching through a directory looking for files that only contain the number 0
.
I have used the code:
$fileList = Select-String -Path c:\cnt\*.txt -pattern "0"
And it outputs a list, such as:
C:\cnt\itm123.txt:1:0
c:\cnt\itm1234.txt:1:0
c:\cnt\itm123456.txt:1:0
I need to only extract the itm###
but the total numbers in the filename can range from 3-6.
Using the example above I need a list that looks like:
itm123
itm1234
itm123456
Once I get that I will run each through a SQL query, but I am not worried about that part.
The Select-String cmdlet returns a list of Microsoft.PowerShell.Commands.MatchInfo
objects. If you call the Get-Member cmdlet with the parameter -MemberType Properties
you will get a list of all exposed properties:
Name MemberType Definition
---- ---------- ----------
Context Property Microsoft.PowerShell.Commands.MatchInfoContext Context {get;set;}
Filename Property string Filename {get;}
IgnoreCase Property bool IgnoreCase {get;set;}
Line Property string Line {get;set;}
LineNumber Property int LineNumber {get;set;}
Matches Property System.Text.RegularExpressions.Match[] Matches {get;set;}
Path Property string Path {get;set;}
Pattern Property string Pattern {get;set;}
In this case, you are looking for the Filename
property. So if you execute
Select-String -Path c:\cnt\*.txt -pattern "0" | select FileName
you will get all filenames:
itm123.txt
itm1234.txt
itm123456.txt
Now all you have to do is to remove the file extension which can be done using the .NET
method GetFileNameWithoutExtension :
Select-String -Path c:\cnt\*.txt -pattern "0" |
ForEach-Object { [io.path]::GetFileNameWithoutExtension($_.FileName)}
Output :
itm123
itm1234
itm123456
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.