I have multiple folders with these names:
ABC_03_00_016_0
ABC_03_00_016_1
ABC_03_00_016_2
ABC_03_00_016_3
ABC_03_00_016_4
ABC_03_00_016_5
What I want to do is to retain the folder with largest number in the end of folder name, i.e. ABC_03_00_016_5 in above case using PowerShell or batch commands.
How to get the folder with greatest number?
Maybe this could be done more elegant, but it's probably working as you want. I'm stripping the last digits, converting & comparing them to then determine the highest one. As you can see, order does not matter:
$items =
"ABC_03_00_016_0",
"ABC_03_00_016_100",
"ABC_03_00_016_99"
[int]$highestNumberTillNow = 0
$highestitem = ""
foreach ($item in $items){
[int]$number = $item.substring($item.LastIndexOf("_")+1,$item.length-$item.LastIndexOf("_")-1)
if ($number -gt $highestNumberTillNow){
$highestNumberTillNow = $number
$highestitem = $item
}
}
write-host $highestitem
You can use this:
#echo off
setlocal enabledelayedexpansion
pushd "%~dp0"
for /f "tokens=4 delims=_" %%a in ('dir ABC_03_016_* /ad /b') do (
for /f "tokens=* delims= " %%b in ('dir ABC_03_016_* /ad /b') do (
set dir[%%a]=%%b
)
)
set dc=0
:loop
set /a dc=dc+1
if defined dir[%dc%] goto loop
goto break
:break
set /a dc=dc-1
echo The folder is !dir[%dc%]!
pause >nul
Assuming you could have more folders with a similar name in the root path like
ABC_03_00_016_0
ABC_03_00_016_1
ABC_03_00_016_2
ABC_03_00_016_3
ABC_03_00_016_4
ABC_03_00_016_5
DEF_03_00_016_0
DEF_03_00_016_1
DEF_03_00_016_10
Using PowerShell you can use something like below.
This will return the folder object(s) with the highest number at the end of the name:
$lastFolder = Get-ChildItem -Path 'D:\test' -Directory | Where-Object { $_.Name -match '(.+)_(\d+)$' } |
Group-Object -Property #{Expression={ $matches[1] }} | ForEach-Object {
$_.Group | Sort-Object -Property #{Expression={ [int]$matches[2] }} | Select-Object -Last 1
}
# for demo, just output the FullName property of the folders found
$lastFolder.FullName
Output:
D:\test\ABC_03_00_016_5
D:\test\DEF_03_00_016_10
Regex details:
( Match the regular expression below and capture its match into backreference number 1
. Match any single character that is not a line break character
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
_ Match the character “_” literally
( Match the regular expression below and capture its match into backreference number 2
\d Match a single digit 0..9
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
$ Assert position at the end of the string (or before the line break at the end of the string, if any)
If you're wanting to remove all of the directories except for the one ending with the largest number, then I'd suggest PowerShell too:
Get-ChildItem -Path 'C:\Users\Naqqash\Desktop' -Filter '*_*_*_*_*' -Directory |
Where-Object { $_.Name -Match '(.+)_(\d+)$' } |
Sort-Object -Property { [Int]$($_.Name).Split('_')[-1] } |
Select-Object -SkipLast 1 |
Remove-Item
Please remember to adjust the path on line 1 to that holding your directories.
The example above requires PowerShell v5.0
The first method can be used only if all folder names have the same length, i.e. leading zeros are used to make sure that all numbers in all folder names have same number of digits.
#echo off
set "LastFolder="
for /F "eol=| delims=" %%I in ('dir "%~dp0ABC_03_00_016_*" /AD /B /O-N 2^>nul') do set "LastFolder=%%I" & goto HaveFolder
echo Found no folder matching pattern ABC_03_00_016_* in "%~dp0".
goto :EOF
:HaveFolder
echo Last folder according to sorted folder names is: %LastFolder%
The task to get folder name with greatest last number is more difficult on number of digits differs on last number.
#echo off
set "LastFolder="
setlocal EnableExtensions EnableDelayedExpansion
set "FolderNumber=-1"
for /F "eol=| delims=" %%I in ('dir "%~dp0ABC_03_00_016_*" /AD /B 2^>nul') do (
for /F "eol=| tokens=5 delims=_" %%J in ("%%I") do (
if %%J GTR !FolderNumber! (
set "LastFolder=%%I"
set "FolderNumber=%%J"
)
)
)
endlocal & set "LastFolder=%LastFolder%"
if not defined LastFolder (
echo Found no folder matching pattern ABC_03_00_016_* in "%~dp0".
) else (
echo Last folder according to last number in name is: %LastFolder%
)
Note: The last number in folder name should have never leading zeros on using the second code above. A number with one or more leading 0 is interpreted as octal number which means 08, 09, 18, 19, etc. are invalid octal numbers and are interpreted for that reason with value 0 by command IF on making the integer comparison. There would be additional code necessary above the IF condition to first remove all leading 0 from number string before doing the integer comparison.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /? ... explains %~dp0 (drive and path of batch file ending with a backslash).
dir /?
echo /?
endlocal /?
for /?
if /?
set /?
setlocal /?
Read the Microsoft article about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
Related
I need to add a progressive number of fixed length at the beginning of each row in a txt file. For example:
0001 aaaaaaaaaaa
0002 bbbbbbbbbb
...
0010 gggggggggg
I created a .bat file to run a PowerShell which should solve the problem:
#echo off &setlocal
set "path=C:\Users..."
set "filein=%~1"
set "fileout=%filein%_out"
setlocal EnableDelayedExpansion
call %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -Command "& {(Get-Content %path%\%filein%.txt) |ForEach-Object {$_.Insert(0,($id++).PadLeft(10,'0'))} |Set-Content %path%\%fileout%.txt}"
But it doesn't work. Probably there's some syntax error.
($id++).PadLeft(10,'0') fails, because ($id++) is of type [int], not [string], and [int] has no .PadLeft() method.
Simply converting ($id++) to a string is enough:
($id++).ToString().PadLeft(10,'0')
Also note that your sample output has a space between the padded number and the content of the line, so you'd have to use:
$_.Insert(0, ($id++).ToString().PadLeft(10,'0') + ' ')
As an aside:
You don't need call in a batch file to call executables (call is only needed for calling other batch files, if you want the call to return).
The PowerShell executable is in the %PATH% by default, so you can invoke it by name only, i.e., powershell.exe.
since you added the [batch-file] tag - here is a pure Batch solution:
#echo off
setlocal enabledelayedexpansion
set count=0
(for /f "delims=" %%A in (input.txt) do (
set /a count+=1
set "index=00000!count!"
echo !index:~-4! %%A
))>Output.txt
Something like this might workout for you -
$id = 1
$files = Get-Content "\\PathToYourFile\YourFile.txt"
foreach ($file in $files)
{
$Padded = $id.ToString("0000000000");
$file.Insert(0, ($Padded));
$id++
}
Use the ToString() method, instead of PadLeft to add progressive number of fixed length zeroes. That is much simpler and hassle-free.
Also, doing the entire operation in PowerShell will be much simpler.
You can also do this in a single line like -
$i = 1
Get-Content "\\PathToYourFile\YourFile.txt" | % { $_.Insert(0, ($i.ToString("0000000000"))); $i++ } | Set-Content ".\NewFileout.txt"
Here is a pure batch file solution, which does not ignore empty lines and is safe against all characters, even exclamantion marks (!):
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set /A "IDX=0"
> "output.txt" (
for /F "delims=" %%L in ('findstr /N "^" "input.txt"') do (
set /A "IDX+=0"
set "LINE=%%L"
setlocal EnableDelayedExpansion
set "IDX=0000!IDX!"
echo !IDX:~-4! !LINE:*:=!
endlocal
)
)
endlocal
exit /B
How can I change some character (#,%,&,$) in the filename of multiple files in one folder and his sub-folders?
Ravi Thapliyal answer how to do that with PowerShell but just for the files in a specific folder (Replace or delete certain characters from filenames of all files in a folder).
I need to generalize that for all files in all folders in the selected one.
Your own answer will only change one char, here is a solution with an array RegEx in one go, remove the chars you want to keep from $replace.
[char[]]$replace = '!##$%^&*(){}[]":;,<>/|\+=`~ '''
$regex = ($replace | % {[regex]::Escape($_)}) -join '|'
Get-ChildItem -recurse |
ForEach {
if ($_.Name -match $RegEx){
Ren $_.Fullname -NewName $($_.Name -replace $RegEx, '_') -whatif
}
}
If the output looks ok, remove the -whatif
Edit removed -File option from Get-ChildItem as it requires a recent Powershell version and wasn't necessary.
Edit2 I regularly state that Rename-Item accepts piped input, so here is a more straight forward version:
[char[]]$replace = '!##$%^&*(){}[]":;,<>/|\+=`~ '''
$regex = ($replace | % {[regex]::Escape($_)}) -join '|'
Get-ChildItem -recurse |
Where-Object { $_.Name -match $RegEx} |
Rename-Item -NewName {$_.Name -replace $RegEx, '_'} -whatif
I found this answer from Dustin Malone:
Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace(" ", "_") }
It gives an error but do the trick.
The task can also be accomplished by a Windows cmd script (batch-file) -- however, there are some limitations, unless appropriate work-arounds are implemented.
The following script replaces #, %, &, $, ( and ) in file names. You can add more characters except ^, !, = and ~, which cannot be processed (an if query lets the replacement be skipped in order to avoid syntax errors). If you provide characters with a code greater than 127 = 0x7F, you may probably need to switch the code page adequately (see the chcp command). Note that the script does not rename any files but only displays them, until you remove the upper-case ECHO command:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_ROOT=D:\path\to\root\dir" & rem /* (assign `%~1` here instead for the script to
rem accept the root dir. as command line argument) */
set _CHAR="#" "%%" "&" "$" "(" ")" & rem // (a `%` sign needs to be doubled!)
set "_REPL=_" & rem // (replacement character or string; this may also be empty)
if not defined _ROOT set "_ROOT=."
for /R "%_ROOT%" %%F in ("*.*") do (
set "FILE=%%~F"
set "NAME=%%~nxF"
setlocal EnableDelayedExpansion
for %%C in (!_CHAR!) do (
if not "%%~C"=="^" if not "%%~C"=="!" if not "%%~C"=="=" if not "%%~C"=="~" (
set "NAME=!NAME:%%~C=%_REPL%!"
)
)
ECHO ren "!FILE!" "!NAME!"
endlocal
)
endlocal
exit /B
To replace also the characters ^ and !, the script needs to be extended a bit:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_ROOT=D:\path\to\root\dir" & rem /* (assign `%~1` here instead for the script to
rem accept the root dir. as command line argument) */
set _CHAR="#" "%%" "&" "$" "(" ")" "^" "!" & rem // (a `%` sign needs to be doubled!)
set "_REPL=_" & rem // (replacement character or string; this may also be empty)
if not defined _ROOT set "_ROOT=."
for /R "%_ROOT%" %%F in ("*.*") do (
set "FILE=%%~F"
set "NAME=%%~nxF"
setlocal EnableDelayedExpansion
for %%C in (!_CHAR!) do (
if "%%~C"=="^" (
set "NAME=!NAME:^=^^!"
call set "NAME=%%NAME:^=%_REPL%%%"
) else if "%%~C"=="!" (
call set "NAME=%%NAME:^!=%_REPL%%%"
) else if not "%%~C"=="=" if not "%%~C"=="~" (
set "NAME=!NAME:%%~C=%_REPL%!"
)
)
ECHO ren "!FILE!" "!NAME!"
endlocal
)
endlocal
exit /B
To replace also the characters = and ~, the script needs to be extended much more:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_ROOT=D:\path\to\root\dir" & rem /* (assign `%~1` here instead for the script to
rem accept the root dir. as command line argument) */
set _CHAR="#" "%%" "&" "$" "(" ")" "^" "!" "=" "~" & rem // (a `%` sign needs to be doubled!)
set "_REPL=_" & rem // (replacement character or string; this may also be empty)
set "$LEN="
if not defined _ROOT set "_ROOT=."
for /R "%_ROOT%" %%F in ("*.*") do (
set "FILE=%%~F"
set "NAME=%%~nxF"
setlocal EnableDelayedExpansion
for %%C in (!_CHAR!) do (
if "%%~C"=="^" (
set "NAME=!NAME:^=^^!"
call set "NAME=%%NAME:^=%_REPL%%%"
) else if "%%~C"=="!" (
call set "NAME=%%NAME:^!=%_REPL%%%"
) else if "%%~C"=="~" (
call :FAST NAME NAME "%%~C" "%_REPL%"
) else if "%%~C"=="=" (
call :SLOW NAME NAME "%%~C" "%_REPL%"
) else (
set "NAME=!NAME:%%~C=%_REPL%!"
)
)
ECHO ren "!FILE!" "!NAME!"
endlocal
)
endlocal
exit /B
:FAST rtn_string ref_string val_char val_repl
rem // This works for `~` and `*`, but NOT for `=`!
setlocal DisableDelayedExpansion
set "STR="
set "CHR=%~3"
if not defined CHR goto :FQUIT
setlocal EnableDelayedExpansion
set "CHR=!CHR:~,1!"
set "STR=!%~2!"
:FLOOP
if defined STR (
set "END=!STR:*%~3=!"
if not "!END!"=="!STR!" (
for /F "eol=%CHR% delims=%CHR%" %%L in ("!STR!") do (
for /F "delims=" %%K in (^""!END!"^") do (
endlocal
set "STR=%%L%~4%%~K"
setlocal EnableDelayedExpansion
)
)
goto :FLOOP
)
)
:FQUIT
for /F "delims=" %%K in (^""!STR!"^") do (
endlocal
set "STR=%%~K"
)
endlocal & set "%~1=%STR%"
exit /B
:SLOW rtn_string ref_string val_char val_repl
rem // This works even for `=`.
setlocal DisableDelayedExpansion
set "STR="
set "CHR=%~3"
set "RPL=%~4"
if not defined CHR goto :SQUIT
if not defined $LEN call :LEN $LEN RPL
setlocal EnableDelayedExpansion
set "CHR=!CHR:~,1!"
set "STR=!%~2!"
set /A "IDX=0"
:SLOOP
set /A "NXT=IDX+1"
if defined STR (
set "POS=!STR:~%IDX%,1!"
if defined POS (
if "!POS!"=="!CHR!" (
set "STR=!STR:~,%IDX%!!RPL!!STR:~%NXT%!"
set /A "NXT=IDX+$LEN"
)
set /A "IDX=NXT"
goto :SLOOP
)
)
:SQUIT
for /F "delims=" %%K in (^""!STR!"^") do (
endlocal
set "STR=%%~K"
set "$LEN=%$LEN%"
)
endlocal & set "%~1=%STR%" & set "$LEN=%$LEN%"
exit /B
:LEN rtn_length ref_string
setlocal EnableDelayedExpansion
set "STR=!%~2!"
if not defined STR (set /A LEN=0) else (set /A LEN=1)
for %%L in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if defined STR (
set "INT=!STR:~%%L!"
if not "!INT!"=="" set /A LEN+=%%L & set "STR=!INT!"
)
)
endlocal & set "%~1=%LEN%"
exit /B
I have semicolon delimited CSV file. Some numerical values are stored with decimal point, for other data manipulation I need to use numbers with decimal comma. This should run for each file in the same folder on any Win machine. Any ideas?
I have tried PowerShell successfully on single file using this script
(Get-Content VER_ZdnSort201608-20160908210028original.csv) | ForEach-Object { $_ -replace "\.", "," } | VER_ZdnSort201608-20160908210028new.csv
But I can't seem to get it work with multiple files, also without replacing content without creating new files.
The data looks like this:
520100;2016-08-31;3197.90;N0401
520200;2016-08-31;6406.66;N0401
520430;2016-08-31;536.40;N0401
520800;2016-08-31;1547.70;N0401
...
Output should be like this:
520100;2016-08-31;3197,90;N0401
520200;2016-08-31;6406,66;N0401
520430;2016-08-31;536,40;N0401
520800;2016-08-31;1547,70;N0401
...
The following will search in a given folder for .csv files. It will then replace any . with , in all .csv files found, overwriting the new text to the same file.
Get-ChildItem -Path C:\Folder -Filter '*.csv' | ForEach-Object {
(Get-Content $_.FullName).Replace('.',',') | Out-File $_.FullName
}
The following script constitutes a pure batch-file solution:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
for %%F in (%*) do (
for /F delims^=^ eol^= %%L in ('
type "%%~F" ^& ^> "%%~F" rem/
') do (
set "LINE=%%L"
setlocal EnableDelayedExpansion
>> "%%~F" echo(!LINE:.=,!
endlocal
)
)
endlocal
exit /B
Provide the paths to your CSV files as command line arguments. Supposing the script is named convert-decimal-point.bat and your CSV files are located in D:\Data, use this command line:
convert-decimal-point.bat "D:\Data\*.csv"
Here is a comprehensive solution that does not blindly replace every . by , but checks each field whether it truly contains a fractional number (an optional sign +/-, followed by any number of decimal digits, followed by ., followed by any number of decimal digits; for example 1.2, -.73, +12.584) or an exponential number (a fractional number, followed by E/e, followed by a sign +/-, followed by one or more decimal digits; for example, 1.2E-02, -.73e+5). This is the batch-file code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_SEARCH=." & rem // (decimal point to search for)
set "_REPLAC=," & rem // (decimal point for replacing)
set "_SEPCHR=;" & rem // (field separator character)
rem // Predefine global variables here:
set "$HEADER=" & rem // (set to something to ignore first line)
for %%F in (%*) do (
for /F delims^=^ eol^= %%L in ('
type "%%~F" ^& ^> "%%~F" rem/
') do (
set "COLL=%_SEPCHR%" & set "LINE=%%L"
setlocal EnableDelayedExpansion
set "LINE=!LINE:"=""!^"
if "!LINE:**=!"=="!LINE!" (
if "!LINE:?=!"=="!LINE!" (
for %%I in ("!LINE:%_SEPCHR%=" "!") do (
endlocal
set "ITEM=%%~I"
call :PROCESS ITEM ITEM
setlocal EnableDelayedExpansion
for /F "delims=" %%C in (^""!COLL!!ITEM!%_SEPCHR%"^") do (
endlocal
set "COLL=%%~C"
setlocal EnableDelayedExpansion
)
)
) else set "COLL=%_SEPCHR%!LINE!%_SEPCHR%"
) else set "COLL=%_SEPCHR%!LINE!%_SEPCHR%"
set "COLL=!COLL:""="!^"
>> "%%~F" echo(!COLL:~1,-1!
endlocal
set "$HEADER="
)
)
endlocal
exit /B
:PROCESS rtn_string ref_string
setlocal EnableDelayedExpansion
set "#RET=%~1"
set "STR=!%~2!"
if not defined $HEADER (
if defined STR (
if "!STR:%_REPLAC%=!"=="!STR!" (
set "CHK=!STR:*%_SEARCH%=!%_SEARCH%"
set "CHK=!CHK:*%_SEARCH%=!"
if not defined CHK (
rem // Adapt regular expressions as needed:
(echo("!STR!" | > nul findstr /R ^
/C:"^\"[0-9]*\%_SEARCH%[0-9]*\" $" ^
/C:"^\"[+-][0-9]*\%_SEARCH%[0-9]*\" $" ^
/C:"^\"[0-9]*\%_SEARCH%[0-9]*[Ee][+-][0-9][0-9]*\" $" ^
/C:"^\"[+-][0-9]*\%_SEARCH%[0-9]*[Ee][+-][0-9][0-9]*\" $" ^
) && (
set "STR=!STR:%_SEARCH%=%_REPLAC%!"
)
)
)
)
)
for /F "delims=" %%S in (^""!STR!"^") do (
endlocal
set "%#RET%=%%~S"
)
exit /B
you can use this command :
$file = Get-Content c:\somewhere\file.csv |Out-String
$file.Replace(".",",") |Out-File c:\somewhere\file.csv
I would like to search & replace the end of each line in my file.txt and delete the char before.
In other words, I have a redundant comma at end of each line, and it disturbs me when passing the data to Excel.
I can't delete all commas, since most of them are valuable. I just need to delete those at end of each line, since they make a blank cell.
I don't mind using a PowerShell gc command.
This is the simplest way to "delete the last char of each line" using a Batch file:
#echo off
setlocal EnableDelayedExpansion
(for /F "delims=" %%a in (file.txt) do (
set "line=%%a"
echo(!line:~0,-1!
)) > output.txt
This Batch file have a series of limitations: it removes empty lines and lines that start with semicolon, and remove exclamation marks from the lines. Each restriction can be fixed introducing a modification that eventually ends in a code similar to aschipfl's answer, but this code may be enough for your needs.
Here is a PowerShell script that will take file in.txt as input, remove the last character from each line, and output them to out.txt:
Get-Content "in.txt" | % { $_.Substring(0, ($_.Length - 1)) } | Out-File "out.txt"
Adding a simple test to check you are only deleting commas:
Get-Content "in.txt" | % {
if($_.Substring(($_.Length - 1), 1) -eq ",") {
$_.Substring(0, ($_.Length - 1))
} else {
$_
}
} | Out-File "out.txt"
Here is a pure batch-file solution:
The following code snippet removes the last character from each line in file.txt if it is , and writes the result into file_new.txt:
#echo off
setlocal EnableExtensions
> "file_new.txt" (
for /F usebackq^ delims^=^ eol^= %%L in ("file.txt") do (
setlocal DisableDelayedExpansion
set "LINE=%%L"
setlocal EnableDelayedExpansion
if "!LINE:~-1!"=="," (
echo(!LINE:~,-1!
) else (
echo(!LINE!
)
endlocal
endlocal
)
)
endlocal
The toggling of delayed environment variable expansion (see setlocal /? and set /? for help) is required to avoid trouble with some special characters.
The above approach removes empty lines from the file as for /F ignores them. To avoid this, use the following script:
#echo off
setlocal EnableExtensions
> "file_new.txt" (
for /F delims^=^ eol^= %%L in ('findstr /N /R "^" "file.txt"') do (
setlocal DisableDelayedExpansion
set "LINE=%%L"
setlocal EnableDelayedExpansion
set "LINE=!LINE:*:=!"
if "!LINE:~-1!"=="," (
echo(!LINE:~,-1!
) else (
echo(!LINE!
)
endlocal
endlocal
)
)
endlocal
This uses the fact that findstr /N /R "^" returns every line (even empty ones) of the given file and prefixes it with a line number plus :. Therefore no line appears to be empty to for /F. The line set "LINE=!LINE:*:=!" is inserted to remove that prefix (everything up to the first :) from each line prior to outputting.
I'm new to PowerShell, but I would like to use it, because there isn't a easy way to get the length of a string in Windows batch.
I need to write a piece of code in PowerShell that go through each line in a .txt file and determine the character length of that line. If the character length is over 250 then....etc.
The ....etc part is not important at the moment :)
In Windows batch I would write it like this:
FOR /F %%A IN ("C:\TestFile.txt") DO (
SET LINE=%%A
If LINE > 250 characters then ( ' This line is made up
....etc
)
How can I do it?
The following will do what you want:
$data = Get-Content "C:\TestFile.txt"
foreach($line in $data)
{
if ($line.Length -gt 250) {
Write-Host "A match"
}
}
Try this:
:: Not fully tested:
for /f "delims=" %%s in (C:\TestFile.txt) do (
set "x=%%s" & set /A y+=1
setlocal enabledelayedexpansion
for /f "skip=1 delims=:" %%i in ('"(set x&echo()|findstr /o ".*""') do set/a n=%%i-4
if !n! gtr 250 echo Line !y! Length !n!
endlocal
)
Was looking for this today and found an elegant solution here: https://softwarerecs.stackexchange.com/questions/38934/finding-the-longest-line-of-a-document/38936
GC "c:\folder\file.txt" | Measure -Property length -Maximum | Select Maximum
GC "c:\folder\file.txt" | Sort -Property length | Select -last 1
Important: credit goes to Pimp Juice IT from the link above, I'm just copy/pasting : )