I am trying to implement the code at this highly rated page https://blogs.technet.microsoft.com/gbordier/2009/05/05/powershell-and-writing-files-how-fast-can-you-write-to-a-file/ using "Method 4."
When I run the code below, it does appear to take a few seconds, but no t.txt file appears to be created. What am I missing?
PS L:\users\lit\t> Get-Content .\ttt.ps1
$s = "some text"
$stream = [System.IO.StreamWriter] "t.txt"
1..10000 | % {
$stream.WriteLine($s)
}
$stream.close()
PS L:\users\lit\t> $PSVersionTable["PSVersion"]
Major Minor Build Revision
----- ----- ----- --------
5 0 10586 117
Many thanks to #Ansgar Wiechers. The only way I could place the file into the correct directory was to produce a full path from a root. Since I wanted to put it into the current directory, (Get-Location).Path provided the directory path to which I appended the file name.
Without specifying the full path, System.IO.StreamWriter wanted to put the file into my home directory.
PS C:\Users\lit\t\booo> Get-Content .\ttt.ps1
[cmdletbinding()]
Param()
$FullPath = Join-Path (Get-Location).Path "t.txt"
Write-Verbose $FullPath
$stream = [System.IO.StreamWriter] $FullPath
Write-Verbose $stream.BaseStream.Name
1..10 | % { $stream.WriteLine($_) }
$stream.close()
PS C:\Users\lit\t\booo> .\ttt.ps1 -Verbose
VERBOSE: C:\Users\lit\t\booo\t.txt
VERBOSE: C:\Users\lit\t\booo\t.txt
PS C:\Users\lit\t\booo> Get-ChildItem
Directory: C:\Users\lit\t\booo
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 1/11/2017 5:22 PM 31 t.txt
-a---- 1/11/2017 5:21 PM 251 ttt.ps1
Related
I have a csv file with extension and description.
I want to import that file and use it as the filter parameter in a gci command.
But I get no results.
I expect to get a list of the jpg files but get no results.
$extensions=Import-CSV -Path c:\scripts\Media-extension-foto.csv
#$extensions=Import-CSV -Path c:\scripts\Media-extension-foto.csv -header extension
$extensions.extension
$src = "c:\scripts\"
#gci c:\scripts\ -Include $Extensions.extension #-Force -recurse
#gci c:\scripts\ -filter $Extensions.extension #-Force -recurse
gci c:\scripts\|where{$_ -like $extensions.extension}`
my csv file looks like this (just made a small file for testing)
extension,"description"
*.JPEG,JPEG Image
*.JPF,JPEG 2000 Image
*.JPG,JPEG Image
*.JPG_LARGE,Twitter Large JPEG Image
There are jpg files in that folder :
Directory: C:\Scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 23/11/2022 11:02 509592 nieuw9754560_02-10.jpg
-a--- 23/11/2022 11:02 576486 nieuw9754560_02-15.jpg
-a--- 23/11/2022 11:02 641802 nieuw9754560_02-20.jpg
-a--- 23/11/2022 11:01 705702 nieuw9754560_02-25.jpg
-a--- 23/11/2022 11:01 763249 nieuw9754560_02-30.jpg
I've just tested this - I think all you're missing is changing the $_ to $_.Extension for the Get-ChildItem, on the last line.
Hope that helps.
Doesn't directly fix the code but here's another way of getting the result using foreach to iterate through each extension in the array:
foreach($e in $extensions.extension) {
gci c:\scripts\ | where {$_ -like $e}
}
Basically, I want to input 7 digits and get second line in the log file as an output.
This is my first time attempting anything in powershell btw
Get-Content -Path C:\Users\Einar\Desktop\log* -filter *1234567.log.txt | Select -First 2 | Select -last 1
I have a folder with log files, that all end with (random7digits).log.txt, and I want to output only the second line by inputting a set of 7 digits.
Any help is appreciated :)
In very basic form, this achieves what you want. You can save this is a .ps1 and save it on your desktop. If you right click and Run with PowerShell, then the console will close after immediately returning. Either call the script from a pre-existing console session, or add a pause or something at the end.
I recommend you expand upon it as a learning exercise with some of these ideas:
Check whether the file exists and provide sensible error handling or message to the user
Check if the file contains your 'ideal' content, or even two lines at all, and provide sensible error handling or message to the user
Perhaps add another parameter, with a default value to your desktop, in case you ever need to run it with logs elsewhere on disk
param(
[Parameter(Mandatory)]
[int]$Digit
)
Get-ChildItem -Path <path_containing_files> -File -Filter *$Digit.log.txt | ForEach-Object {
Get-Content -Path $_ | Select-Object -Index 1
}
function Get-Logline
function Get-Loglines{
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, HelpMessage='Enter Path to Log Folder:' )]
[string]$Path,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, HelpMessage='Enter string to filter for: *(string).log.txt')]
[int]$filename,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, HelpMessage='Enter line number to read back:')]
[int]$linenumber
)
process{
$lookdepth = $linenumber - 1
Get-ChildItem -Path $Path -File -Filter ('*{0}.log.txt' -f $filename) -force -Verbose |`
ForEach-Object{
Get-Content $_ -Verbose |`
Select-Object -Skip $lookdepth -First 1 -Verbose
}
}
}
Test Case
C:\> Get-Loglines
cmdlet Get-Loglines at command pipeline position 1
Supply values for the following parameters:
(Type !? for Help.)
Path: C:\Downloads\Newfolder
filename: 666666
linenumber: 2
line 2
Example Data
C:\Downloads\Newfolder [master +39 ~0 -0 !]> Get-ChildItem
Directory: C:\Downloads\Newfolder
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 4/21/2022 2:37 PM 38 ab123456.log.txt
-a---- 4/21/2022 2:37 PM 38 ab666666.log.txt
-a---- 4/21/2022 2:37 PM 38 ab666667.log.txt
-a---- 4/21/2022 2:37 PM 38 acb666666.log.txt
C:\Downloads\Newfolder> Get-Content .\ab666666.log.txt
line 1
line 2
line 3
line 4
line 5
I want to bulk rename the files in my folder, and all of them have the format of FilenameYeara\b.pdf, for example, TestData2001a.pdf, File2015b.pdf. I want to rename all of them to something like [Yeara\b]Filename, such as [2001a]TestData. The problem is that I don't know how can I split my filename into two parts (actually three if we count the extension, .pdf part), such that I put that second part as the first part of the file name.
Get-ChildItem | Rename-Item {$_.name -replace ‘current’, ’old’ }
How can I achieve this?
This does the regex match "anything, four digits, one character, .pdf" and replaces it with those items in the new ordering.
PS D:\t> gci | ren -newname { $_ -replace '(.*)(\d{4})(.)\.pdf', '[$2$3]$1.pdf' }
Directory: D:\t
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 13/05/2016 02:54 0 File2015b.pdf
-a--- 13/05/2016 02:53 0 TestData2001a.pdf
becomes
Directory: D:\t
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 13/05/2016 02:53 0 [2001a]TestData.pdf
-a--- 13/05/2016 02:54 0 [2015b]File.pdf
(Maybe try it with -Whatif before running for real)
This should get you started
$Matches.Clear()
Get-Item | % {
$_.BaseName -match "(\D+)([0-9]{4}[ab])"
Rename-Item -Path $_.FullName -NewName "$($Matches[2])$($Matches[1])$($_.Extension)"
}
If I have this:
Get-ChildItem -Path $BACKUP_REG_PATH >> $TOT_LOG_FILE
I will get a fine list in my log file like this:
Directory: C:\WS\BACKUP\xxxx-Reg
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2016-05-17 11:04 494018 xxxxxx_REGISTRY_EVENTLOG__2016-05-17__11_04_38.reg
-a--- 2016-05-17 11:08 494018 xxxxxx_REGISTRY_EVENTLOG__2016-05-17__11_08_59.reg
-a--- 2016-05-17 11:10 494018 xxxxx_REGISTRY_EVENTLOG__2016-05-17__11_10_31.reg
I want to do this for NLog instead but I don't know how to get a nice list as above.
If I do this:
$regtxt=Get-ChildItem -Path $BACKUP_REG_PATH
$LOGGER.Trace("$regtxt");
I only get a long list on the same row with the Name column.
Any ideas how to solve this?
I don't know NLog but the Trace method probably output the trace in a single line. You could iterate over each item using the Foreach-Object cmdlet and write a trace:
Get-ChildItem -Path $BACKUP_REG_PATH | Foreach-Object {
$LOGGER.Trace($_);
}
Note: This will not output the name column, you may have to trace this yourself.
To solve this, you could pipe the output to the Out-String cmdlet which will give you a single string. You then have to split the string by [System.Environment]::NewLine to get an array to iterate over it:
((Get-ChildItem | select -first 4 | Out-String) -split [System.Environment]::NewLine) |
ForEach-Object {
$LOGGER.Trace($_);
}
I would like to change the creation date of the files that I generate with this script :
$clientname = Read-Host "Enter the client name"
$path = Read-Host "Enter the complete path of .bak files"
$time = "01-00-00"
$space = " "
for ($i = 0; $i -lt 7;$i++)
{
$date = (Get-Date).AddDays(-1-$i).ToString('yyyy-MM-dd')
New-Item -ItemType file $path$clientname$space$date$space$time.bak
}
So it gives me theses files :
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 16/08/2013 16:55 0 client 2013-08-15 01-00-00.bak
-a--- 16/08/2013 16:55 0 client 2013-08-14 01-00-00.bak
-a--- 16/08/2013 16:55 0 client 2013-08-13 01-00-00.bak
-a--- 16/08/2013 16:55 0 client 2013-08-12 01-00-00.bak
-a--- 16/08/2013 16:55 0 client 2013-08-11 01-00-00.bak
-a--- 16/08/2013 16:55 0 client 2013-08-10 01-00-00.bak
-a--- 16/08/2013 16:55 0 client 2013-08-09 01-00-00.bak
I want to modify the LastWriteTime property of each files, I want it to be the same as the date in the file name.
Example for this file "client 2013-08-15 01-00-00.bak" the LastWriteTime will be "15/08/2013 01:00"
I'm stuck and I do not how can we do that
Thank you
Not tested, but try this in your loop after you call New-Item:
$file = Get-ChildItem $path$clientname$space$date$space$time.bak
$file.LastWriteTime = (Get-Date).AddDays(-1-$i)
If you want to see a full listing of things you can do with FileInfo objects, try calling $file | gm in your powershell console. You could also view the docs on MSDN.
for ($i=0; $i -lt 7;$i++)
{
$date = (Get-Date).AddDays(-1-$i)
$filedate = $date.ToString('yyyy-MM-dd')
$file = New-Item -ItemType File $path$clientname$space$filedate$space$time.bak
$file.LastWriteTime = $date
}