I have a large number of files in numerous directories with this type of naming convention: "filename_yymmdd.csv", etc. I need to remove the underscore and the yymmdd. So the new file name would be "filename.csv". i need to recursively search through for .csv files and remove the date and underscore in powershell V2.0
$pattern = '(.*)_\d{6}(.csv)'
Get-ChildItem -Recurse | ? { $_.Name -match $pattern } |
Rename-Item -NewName { $_.Name -replace $pattern, '$1$2' }
Related
I am trying to parse an INF; specifically, driver version from the file. I am new to PowerShell, so I've gotten only this far.
The file looks like this:
[Version]
Signature = "$WINDOWS NT$"
Class = Bluetooth
ClassGuid = {e0cbf06c-cd8b-4647-bb8a-263b43f0f974}
Provider = %PROVIDER_NAME%
CatalogFile = ibtusb.cat
DriverVer=11/04/2014,17.1.1440.02
CatalogFile=ibtusb.cat
The second last line has the information I am looking for. I am trying to parse out just 17.1.1440.02.
One file may contain multiple lines with DriverVer=..., but I am only interested in the first instance.
Right now I've the following script.
$path = "C:\FilePath\file.inf"
$driverVersoin = Select-String -Pattern "DriverVer" -path $path
$driverVersoin[0] # lists only first instance of 'DriverVer'
$driverVersoin # lists all of the instances with 'DriverVer'
Output is:
Filepath\file.inf:7:DriverVer=11/04/2014,17.1.1440.02
But I am only looking for 17.1.1440.02
Make your expression more specific and make the part you want to extract a capturing group.
$pattern = 'DriverVer\s*=\s*(?:\d+/\d+/\d+,)?(.*)'
Select-String -Pattern $pattern -Path $path |
select -Expand Matches -First 1 |
% { $_.Groups[1].Value }
Regular expression breakdown:
DriverVer\s*=\s* matches the string "DriverVer" followed by any amount of whitespace, an equals sign and again any amount of whitespace.
(?:\d+/\d+/\d+,)? matches an optional date followed by a comma in a non-capturing group ((?:...)).
(.*) matches the rest of the line, i.e. the version number you want to extract. The parentheses without the ?: make it a capturing group.
Another option (if the version number is always preceded by a date) would be to just split the line at the comma and select the last field (index -1):
Get-Content $path |
Where-Object { $_ -like 'DriverVer*' } |
Select-Object -First 1 |
ForEach-Object { $_.Split(',')[-1] }
I need to get part of this file for example, I need extract the following
Main, Branches\Branch1
in one variable also the I cannot have duplicate values
It is possible with powershell?
This is the file:
This is a garbage line
This is another garbage line
c:\Folder\Main\Folder\..\Folder
c:\Folder\Main\Folder\..\Folder
c:\Folder\Branches\Branch1\Folder\..\Folder
c:\Folder\Branches\Branch1\Folder\..\Folder
c:\Folder\Branches\Branch1\Folder\..\Folder
c:\Folder\Main\Folder\..\Folder
c:\Folder\Main\Folder\..\Folder
this is the final line..
But of course ...
According to the fact $files contain your lines
$files = Get-content "your file"
You can use the following to be sure that there is no duplicate :
$files | Sort-Object -Unique
Then you can use Test-path to be sure that path exists
$files | Sort-Object -Unique | where {Test-Path $_ -ErrorAction SilentlyContinue}
This will extract those values from the sample data using a -like filter to take out the garbage and a -replace to do the extract. The sort -unique will remove the duplicates, but it won't keep the extracted values in the same order they were in the file.
(get-content testfile.txt) -like 'c:\Folder*' -replace 'c:\\Folder\\(.+?)\\Folder.+','$1' |
sort -unique
I am working on some PowerShell scripting stuff not having a strong PowerShell skill under my belt. Basically I am more into Java, but I need to use PowerShell to get some things done at work.
What I have so far is a little snippet that parses my desired log file, returns an object and writes it to a file.
# find all lines with "successfully installed":
Select-String -Path $env:windir\WindowsUpdate.log -Pattern 'successfully installed' |
ForEach-Object {
$information = $_ | Select-Object -Property Date, Product
$parts = $_.Line -split '\t'
[DateTime]$information.Date = $parts[0] + ' ' + $parts[1].SubString(0,8)
$information.Product = ($_.Line -split 'following update: ')[-1]
$information
} | Out-File parsedUpdate.log
My output looks like this
What I would love to do next is to
Get rid of the line that labels the Properties and the line below it as well as I would send the output to EventLog soon.
Select only the lines that are no older than a specific date.
So how would I go about rejecting these two lines? Regarding the date problem I would love the exclude lines older than a specific date which I specify.
I have read that that Select-String has an -Exclude <String> property.
Would it be smart (and of course possible) to use this Directive to Exclude lines with a specific date and how would I do that - lets say for example, to reject any line older than a week from now?
thanks in advance.
Andrew
The timestamps on the actual log entries are in string sortable format, so you can do your date filtering early, before object creation:
$Start = (get-date).AddDays(-7).ToString('yyyy-MM-dd')
Select-String -Path $env:windir\WindowsUpdate.log -Pattern 'successfully installed' |
Where {$_.line -gt $Start} |
All you have to do for the (2) part of your question is add a filter to your result set, since you've already got objects with the Date property. The filter clause will look like Where-Object { $_.Date -ge "2/6/2015" } just replace with the date you are interested in.
# find all lines with "successfully installed" no older than 2/6/2015:
Select-String -Path $env:windir\WindowsUpdate.log -Pattern 'successfully installed' |
ForEach-Object {
$information = $_ | Select-Object -Property Date, Product
$parts = $_.Line -split '\t'
[DateTime]$information.Date = $parts[0] + ' ' + $parts[1].SubString(0,8)
$information.Product = ($_.Line -split 'following update: ')[-1]
$information
} | Where-Object { $_.Date -ge "2/6/2015" } | Out-File parsedUpdate.log
I find something interesting when I try to read text files from a folder:
$files = Get-ChildrenItem "C:\MyFolder" -Recursive | ?{$_.Extension -like '.txt'}
foreach ($file in $files) {
[string]fileFullName = $file.FullName
$content = Get-Content -Path $fileName
....
}
I encountered some exceptions if file names contains [ and ] chars, for example, a[1].txt.
I guess that every thing is object in PS. Therefore, as for my understanding, [..] in file names maybe treated as index access. Is there any way to deal with files with brackets?
You want -LiteralPath:
$files = Get-ChildItem "C:\MyFolder" -Recurse | ? { $_.Extension -like '.txt' }
foreach ($file in $files) {
[string]$fileFullName = $file.FullName
$content = Get-Content -LiteralPath $fileFullName
$content
}
From detailed help () you willsee:
-LiteralPath
Specifies the path to an item. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are
interpreted as wildcards. If the path includes escape characters,
enclose it in single quotation marks. Single quotation marks tell
Windows PowerShell not to interpret any characters as escape
sequences.
I have a csv document with multiple headers like:
"Date","RQ","PM","SME","Activity","Status code"
"2/2/12","6886","D_WV","John Smith","Recent","2004"
and a text document that is just a list of status codes, one per line.
I am trying to figure out how to remove all lines from the CSV that contain the status codes from the text file.
So far I have tried using:
$m = gc textfile.txt
Select-String data.csv -Pattern $m -NotMatch
However that leaves me with extra data such as
data.csv:1"Date","RQ","PM","SME","Activity","Status code"
data.csv:2"2/2/12","6886","D_WV","John Smith","Recent","2004"
I have also tried:
gc data.csv | ? { $_ -notlike $m }
That uses the proper formatting but does not want to remove any of the values. Any help is much appreciated.
Those matchinfo objects from select-string can be confusing.
Does this do what you need?
$m = gc textfile.txt
select-string data.csv -pattern $m -notmatch |
select -expand line
I'd suggest a different approach to avoid false positives:
$m = Get-Content textfile.txt
Import-Csv data.csv `
| ? { $m -notcontains $_."Status code" } `
| Export-Csv output.csv -NoTypeInformation