Powershell script to run multiple input text files - powershell

I'm trying to remove spaces from input text file through PowerShell script.
I have hundreds if thousands of text files where I have to remove the spaces. I wrote the code to remove spaces. It is working fine for one text file but I want to execute more than one file .
gc C:\test\3.txt | where {$_ -ne ""} > C:\test\out.txt
In the above example I have more input files like 4.txt , 5.txt , 6.txt etc. I want to execute all the files in one shot and remove the spaces and write the 4out.txt, 5out.txt, 6out.txt, etc. to another folder.

It should just be a case of looping through your files and running the same line you already have.
Add some try-catch if you'd like to be safe.
$InputFiles = Get-ChildItem 'C:\test\'
$OutputPath = 'C:\test\out\'
ForEach($File in $InputFiles) {
Get-Content $File |
Where-Object {$_ -ne ''} |
Out-File (Join-Path -Path $OutputPath -ChildPath $File.Name)
}

Related

How to change a character in multiple .txt-files and save/ overwrite the existing file in Powershell

i'm really new to Powershell (2 days) and i am not good yet. :(
My Question ist:
How to change a character in multiple .txt-files and save/ overwrite the existing file in Powershell
My goal is to Copy multiple RAW-Files in a new folder, change the file-name from .tsv to .txt and at least change one character in these files from % to percent.
What i've got so far:
The first two steps are working, but i'm losing my mind with the third step (the replacement).
Copy-Item -Path "C:\Users\user\Desktop\RAW\*.tsv" -Destination "C:\Users\user\Desktop\TXT" -Recurse
Set-Location "C:\Users\User\Desktop\TXT"
Get-ChildItem *.tsv | Rename-Item -NewName { $_.Name -replace '.tsv','.txt' }
This works fine for me and now i am not able to get further ...
I am able to replace the "%" in one specific file, and save it in a new file, but this doesn't work for a batch processing with changing file-names.
$file = "A.txt"
Get-Content $file | Foreach {$_ -replace "%", "percent"} | Set-Content A_1.txt
It would be perfect, if "$file = "A.txt"" would be "all the files in this path with .txt" and
"Set-Content A_1.txt" would be "overwrite the existing file".
I hope someone will help me, thank you! <3 <3 <3
You already have some of the solution in your first code snippet, you need to iterate over the files again to perform the replace and save.
$txtFiles = Get-ChildItem -Name *.txt
ForEach ($file in $txtFiles) {
(Get-Content $file) | ForEach-Object {
$_ -replace '%','percent'
} | Set-Content $file
}
The first line adds all the text files to an array, the foreach loop iterates over the files of the array and grabs the content of the file and unloads it - that's the reason for the parenthesis, the Foreach-Object then iterates over the content of the file and saves it to the same file name as before.
If you skip the parentheses around Get-Content $file the file would still be loaded into memory and you would get an error message about not being able to save the file.

How do I delete a line from a text file in powershell?

Suddenly I have the urge to finally get into powershell. Right now I have a way to import a text file, create a text file, and add to a file, but is there a way to delete elements from a file? For example if I have a text file:
test.txt
Quick
Brown
Fox
I can import the file with
$textFile = Get-Content -Path ".\test.txt"
and I can print each element and add them to a new file with
foreach($line in $textFile)
{
Write-Host $line
Add-Content -Path ".\output.txt" -Value $line
}
But how can I delete or remove an element (a line) from the test.txt file? I googled for a solution but I only get results for conditions in which someone wants to delete a blank line, deleting the entire file, or how to do it in C#. I thought it would be as intuitive as the previous commands..
Thanks for the feedback!
Take this thread as an example, it deletes lines by reserving lines which doesn't contains specific content.
You can do the same thing by reserving the line you don't want to delete.
Get-Content .\text.txt | Where-Object {$_ -notmatch 'the-word-in-specific-line'} | Set-Content out.txt
So, if you want to delete the line containing the string Brown:
Get-Content .\test.txt | Where-Object {$_ -notmatch 'Brown'} | Set-Content out.txt

Delete first n lines in file (.zip file with many "strange" symbols)

This powershell code delete first 4 lines in file
(gc "old.zip" | select -Skip 4) | sc "new.zip"
But old.zip file has Unix (LF) line endings
And this code also converts file line endings to Windows (CR LF)
How to delete first 4 lines without converting ?
Because of the presence of many "strange" symbols in .zip, other ways to remove the first n lines in a .zip file do not work. For example, more than +4 "old.zip"> "new.zip" in cmd does not work, etc.
Through powershell something like it is removed but also not without problems.
Do you know other ways to remove the first n lines in a .zip file ?
somthing like this?
$PathZipFile="c:\temp\File_1.zip"
$NewPathZipFile="c:\temp\NewFile_1.zip"
#create temporary directory name
$TemporyDir=[System.IO.Path]::Combine("c:\temp", [System.IO.Path]::GetRandomFileName())
#extract archive into temporary directory
Expand-Archive "c:\temp\File_1.zip" -DestinationPath $TemporyDir
#loop file for remove 4 first lines for every files and compress in new archive
Get-ChildItem $TemporyDir -file | %{
(Get-Content $_.FullName | select -Skip 4) | Set-Content -Path $_.FullName;
Compress-Archive $_.FullName $NewPathZipFile -Update
}
Remove-Item $TemporyDir -Recurse -Force
PowerShell:
(gc "old.txt" | select -Skip 4 | Out-String) -replace "`r`n", "`n" | Out-File "new.txt"
C#:
File.WriteAllText("new.txt", string.Join("\n", File.ReadLines("old.txt").Skip(4)));

Renaming multiple files in Windows

I have a folder containing multiple .txt files which have been created by another program. However the program outputs each file with "-Module" in the
filename. eg
filename-Module.txt
filename1-Module.txt
filename2-Module.txt
I would like to know if there's a script or command (Powershell/cmd) that I can run which will iterate over each file and remove the "-Module" from each filename so I simply end up with
filename.txt
filename1.txt
filename2.txt
I have tried using cmd from the directory, with the following:
rename *-Module.txt *txt
This resulted in no change.
You can use get-childitem and pipe it into rename-item.
get-childitem -path 'c:\folderwherefilesarelocated' -recurse |
rename-item -newname {$_.Name -replace "-module", ""}
Relatively straightforward:
Get-ChildItem ComputerName\TestLocation\testfolder -filter "*-module*" | Rename-Item -NewName {$_.name -replace '-module', ''}
Get the items in the folder, look for filenames with "-module" in them, and then replace the "-module" text with an empty string. You can also append a -whatif to see the output before performing this action.

Powershell replace special characters string in all files in directory path

I'm trying to create a 'find and replace' script for the website our company just acquired. Right now, I just want to use it to replace their address and phone number with
ours, but I'll likely need to customize it in the future to replace or update other stuffs.
So far, what I got is:
(Get-Content C:\Scripts\Test.txt) |
Foreach-Object {$_ -replace "\*", "#"} |
Set-Content C:\Scripts\Test.txt
which I got from The Scripting Guy :P
However, I need help customizing it. What I need it to do is:
Do it for all files in a directory and all sub-directories, not just one file. The website as far as I can tell is a collection of *.php files
Handle special characters that appear in some addresses, like copyrights (©) pipes (|) commas (,) and periods (.)
Here's the exact string I'm trying to replace (as it appears in the .php's):
<p>©Copyright 2012 GSS | 48009 Fremont Blvd., Fremont, CA 94538 USA</p>
Since this could be the first tool in my powershell toolbox, any explaining of what you're adding or changing would greatly help me understand what's going on.
Bonus points:
Any way to log which files were 'find-and-replace'ed?
My suggestion would be to use a ForEach loop. I don't see the need for a function in this case, just have the code in your ForEach loop. I would define a string to search for, and a string to replace with. When you perform the replace make sure that it is escaped. Something along these lines:
$TxtToFind = "<p>©Copyright 2012 GSS | 48009 Fremont Blvd., Fremont, CA 94538 USA</p>"
$UpdatedTxt = "<p>©Copyright 2014 | 1234 Somenew St., Houston, TX 77045 USA</p>"
$Logfile = "C:\Temp\FileUpdate.log"
ForEach($File in (GCI C:\WebRoot\ -Recurse)){
If($File|Select-String $TxtToFind -SimpleMatch -Quiet){
"Updating lines in $($File.FullName)" |Out-File $Logfile -append
$File|Select-String $TxtToFind -SimpleMatch -AllMatches|Select -ExpandProperty LineNumber -Unique|Out-File $Logfile -append
(GC $File.FullName) | %{$_ -replace [RegEx]::Escape($TxtToFind),$UpdatedTxt} | Set-Content $File.Fullname
}
}
You can leverage regular expression to find/replace the string you desire and the following script will iterate over all the php files within the provided folder recursively.
function ParseFile($file){
#Add logic to parse the file
Write-Host $file.FullName
}
$files = Get-ChildItem -recurse C:\Path -Filter *.php
foreach ($file in $files) {
ParseFile $file
}