Use PowerShell to determine length of a line in a text file - powershell

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 : )

Related

How to get the folder name with highest number in folder name?

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.

Padleft function with a sequence number in PowerShell

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

Remove folders from txt file in windows cmd

I have file with thousand lines like this.
x:/folder/folder/PN.xxx
y:/folder/PN.xxx
...
I need to make script for change this (for using in excel):
x;file.xxx
y;file.yyy
Best result for me is something this:
x;PN;x:/folder/folder/
y;PN;y:/folder/
I try to use easiest way in cmd:
D:\>powershell -Command "(gc serverPN.txt) -replace 'xxx', ';' | Out-File myFile.txt"
But I dont know, what is needet to write in XXX, when i want remove everything between /*/. Something like this can be close:"\\[\D]*\\'".
Thanks for help.
Supposing the lines are stored in text_file.txt, for a batch-file solution you need a for /F loop and the ~ modifiers for loop variable expansion (see also for /? for details):
for /F "usebackq delims=" %%L in ("text_file.txt") do (
echo(%%~dL;%%~nxL;%%~dpL
)
This reaults in the following output with respect to the sample data in your question:
x:;PN.xxx;x:/folder/folder/
y:;PN.xxx;y:/folder/
If you want the pure file name without extension in the output, replace %%~nxL by %%~nL.
In PowerShell try:
gc "serverPN.txt" | % {
get-item $_ | %{
"$($_.PSDrive);$($_.Name);$($_.Directory)" | Out-File "myFile.txt" -Append
}
}
This should be your requested regular expression: :.*/ and you can replace it with a ;:
powershell -Command "(gc serverPN.txt) -replace ':.*/', ';' | Out-File myFile.txt"
$test = 'C:/test1/test2/test3/test4/testfile.xls'
$newfile =$test.Substring(0,2) + ';' + $test.Substring($test.LastIndexOf('/')+1,($test.Length-$test.LastIndexOf('/')-1))
Output :
C:;testfile.xls
While it is not the beloved PowerShell, cmd could also produce the "best result".
C:>TYPE fi2.bat
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "usebackq tokens=*" %%f IN (`TYPE fi2.txt`) DO (
SET DRIVE=%%~df
SET DRIVE=!DRIVE:~0,1!
SET FILENAME=%%~nf
SET DIRNAME=%%~pf
SET DIRNAME=!DIRNAME:\=/!
ECHO !DRIVE!;!FILENAME!;%%~df!DIRNAME!
)
EXIT /B 0
C:>CALL fi2.bat
x;PN;x:/folder/folder/
y;PN;y:/folder/

Converting a text file with one column to multiple column [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a file with data in one column format. I need to use this file as an input file and the output file should be in a multi column format. I need help with a script that will do the conversion. It does not matter PowerShell or batch.
Input file content:input.txt
store1:
apple
orange
peach
THE END
store2:
Tree
Park
Pond
Bird
THE END
store3:
Building
Road
peach
store
Grocery
THE END
The output file should be:
store1:,store2:,store3:
apple, Tree, Building
orange, Park, Road
peach, Pond, peach
, Bird, store
, , Grocery
i know this is a gimmie, but i took it as a learning opportunity for myself, and since i have the code maybe someone else can learn from it
$text = gc C:\temp\input.txt
$groups = ($text | out-string) -split 'the end' | ? {$_ -notmatch '^(?:\s+)?$'}
$columns = $groups | % {$_.trim().split("`n")[0]}
$rows = $groups | % {$_.trim().Split("`n").count - 2} | sort -desc | select -f 1
$result = 0..$rows | % {
$row = $_
$obj = New-Object psobject
0..$($columns.Count-1) | % {
$column = $columns[$_]
$store = $groups[$_].trim().split("`n")
$item = $store[$row+1]
$obj | Add-Member -MemberType NoteProperty -Name $column.trim() -Value $(if ($item) {$item.trim()})
}
$obj
}
$result | epcsv C:\temp\input.csv -NoTypeInformation
Here is a pure batch-file solution:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Define global settings here:
set "INFILE=input.txt"
set "OUTFILE=output.txt"
set "HEAD=^store[1-9][0-9]*:$"
set "FOOT=^THE END$"
set "DELIM=,"
set /A "COL=0, ROW=0, MAX=0"
for /F "delims=" %%L in ('
findstr /N /R "^" "%INFILE%"
') do (
set "LINE=%%L"
setlocal EnableDelayedExpansion
set "LINE=!LINE:*:=!"
if defined HEAD (
if !COL! EQU 0 set /A "ROW=-1"
cmd /V /C "echo^(!LINE!"| > nul findstr /R /C:"%HEAD%" ^
&& if !ROW! LSS 0 set /A "COL+=1, ROW=0"
if defined FOOT (
cmd /V /C "echo^(!LINE!"| > nul findstr /R /C:"%FOOT%" ^
&& set /A "ROW=-1" || if !COL! GTR 0 if !ROW! GEQ 0 set /A "ROW+=1"
) else (
if !COL! GTR 0 set /A "ROW+=1"
)
) else (
if defined FOOT (
if !ROW! EQU 0 set /A "COL+=1"
cmd /V /C "echo^(!LINE!"| > nul findstr /R /C:"%FOOT%" ^
&& set /A "ROW=0" || set /A "ROW+=1"
) else (
if !COL! EQU 0 set /A "COL=1"
if defined LINE (
set /A "ROW+=1"
) else (
if !ROW! GTR 0 set /A "COL+=1"
set /A "ROW=0"
)
)
)
if !MAX! LSS !ROW! set /A "MAX=!ROW!"
for /F "tokens=1-3 delims=;" %%I in ("!COL!;!ROW!;!MAX!") do (
endlocal
if %%I GTR 0 if %%J GTR 0 (
set "COLLECT[%%I_%%J]=%%L"
)
set /A "COL=%%I, ROW=%%J, MAX=%%K"
)
)
setlocal EnableDelayedExpansion
> "%OUTFILE%" (
for /L %%J in (1,1,%MAX%) do (
set "LINE="
for /L %%I in (1,1,%COL%) do (
if %%I GTR 1 set "LINE=!LINE!!DELIM!"
if defined COLLECT[%%I_%%J] (
set "LINE=!LINE!!COLLECT[%%I_%%J]:*:=!"
)
)
echo(!LINE!
)
)
endlocal
endlocal
exit /B
Basically this script collects the data in an array-like variable COLLECT[COL_ROW], where COL and ROW denote the column and row indexes, respectively. The code consists of two loops, where the first one walks through the given input file and assigns the line texts to the related array elements. The predefined header and footer strings (or, if both are not provided, any empty lines) control determination of the applicable COL and ROW indexes. MAX holds the greatest row index ROW, because the blocks of data might be of different size, for later padding. The second loop enumerates the collected data array, builds a line of text per each column and writes them to the specified output file.
The code section at the beginning marked with a remark rem defines the global settings of the script, like the input file (INFILE), the output file (OUTFILE), the header and the footer (HEAD and FOOT, respectively; both findstr-compatible regular expressions; either or both of them can be empty) and the delimiter (DELIM).
This approach has got 4 modes:
both header and footer are non-empty:
data is collected beginning at the first header string;
another header appearing after a footer starts a new data column;
everything between a footer and the next header is ignored;
a header appearing after another one and before a footer is treated as a normal field;
header texts are included in the returned data, footer texts are not;
empty lines are kept, meaning they result in an empty field;
header is non-empty but footer is empty:
data is collected beginning at the first header string;
another header starts a new data column;
header texts are included in the returned data;
empty lines are kept, meaning they result in an empty field;
footer is non-empty but header is empty:
data is collected beginning at the very first line;
a footer starts a new data column;
footer texts are not included in the returned data;
empty lines are kept, meaning they result in an empty field;
both header and footer are empty:
data is collected beginning at the first non-empty line;
a block of one or more consecutive empty lines starts a new data column;
empty lines are not included in the returned data;
Note:
Although the question lacks of information and attempts of or research by the poster, I decided to answer it, because the task at hand is a quite interesting challenge being solved with a batch-file.
EDIT: The code below is a solution from user Aacini (not from aschipfl) posted here after the original poster of this answer give me his kindly permission. I was forced to do this because the question is closed and I really wanted to post my code!
#echo off
setlocal EnableDelayedExpansion
rem Initialize data for first store
set /A max=0, lines=0, store=0
for /F "delims=" %%a in (input.txt) do (
if "%%a" neq "THE END" (
rem Process the next line of this store
set /A lines+=1
for %%l in (!lines!) do (
if not defined line[%%l] (
rem This store have more lines than previous ones: initialize new line
for /L %%i in (1,1,!store!) do set "line[%%l]=!line[%%l]! ,"
)
rem Append new data to this line
set "line[%%l]=!line[%%l]!%%a,"
)
) else (
rem This store ends: get the maximum number of lines
if !lines! gtr !max! (
set "max=!lines!"
) else (
rem Enlarge the additional lines of previous stores, if any
set /A lines+=1
for /L %%i in (!lines!,1,!max!) do set "line[%%i]=!line[%%i]! ,"
)
rem Pass to next store
set /A lines=0, store+=1
)
)
rem Output all result lines
(for /L %%i in (1,1,%max%) do echo !line[%%i]:~0,-1!) > output.txt
Output:
store1:,store2:,store3:
apple, Tree, Building
orange, Park, Road
peach, Pond, peach
, Bird, store
, , Grocery
You can pipe a text file into this PowerShell script. It uses PowerShell's dialect of CSV (which includes quote chars).
Begin {
# corresponds to (untransposed) records
$records = #()
# the current record
$this_record = #()
# maximum fields of any (untransposed) record
$max_fields = 0
}
Process {
If ($_ -eq "THE END") {
# Append the record to the array.
$records += ,$this_record
# Count the maximum number of fields (this will be the number of
# records when the data is transposed).
If ($this_record.Length -gt $max_fields) {
$max_fields = $this_record.Length
}
$this_record = #()
} ElseIf ($_.Trim() -eq "") {
# Ignore blank lines.
} Else {
# Append the field to the current record.
$this_record += $_
}
}
End {
# Transpose the fields
$objects = #()
For ($col=0; $col -lt $max_fields; $col+=1) {
# ConvertTo-CSV gets object properties. It doesn't implicitly
# operate on arrays the way we'd prefer.
$obj = New-Object PSCustomObject
For ($row=0; $row -lt $records.Length; $row+=1) {
# Create property names that sort lexically (zero-padded numbers).
$obj | Add-Member -MemberType NoteProperty `
-Name ("{00000}" -f $row) `
-Value $records[$row][$col]
}
$objects += $obj
}
# Convert to CSV, throw away the header
$objects | ConvertTo-CSV -NoTypeInformation | Select-Object -Skip 1
}
E.g. PowerShell -NoProfile -ExecutionPolicy Bypass -File xpose.ps1 < input.txt produces:
"store1:","store2:","store3:"
"apple","Tree","Building"
"orange","Park","Road"
"peach","Pond","peach"
,"Bird","store"
,,"Grocery"
Here's some code to help you out. Study this!
appendcolumn.bat
#echo off
set i=1
for /f "tokens=*" %%x in ('more') do (
call :app !i! %%x
set /a i += 1
)
exit /b
:app
set line%1=!line%1!,%2
exit /b

Get date and time on the same line

I can use date /t and time /t to get the date and time, but it doesn't display it next to each other. I wanted to make it do that and display like this:
Current Date & Time
-------------------
11/27/2013 10:43:05 AM
Try the following (PowerShell):
Get-Date -Format G
27.11.2013 17:10:23
The format is defined with the system's regional settings, so for me this is what I get, but if you're regional date/time format is what you want, it should show up like you want.
(Get-Date).ToString()
would probably also work.
UPDATE:
"Date and time is: $((Get-Date).ToString())"
In PowerShell this is trivial:
(Get-Date).ToString('MM/dd/yyyy hh:mm:ss tt')
In cmd it's somewhat complicated:
rem Get the date and time in a locale-agnostic way
for /f %%x in ('wmic path win32_localtime get /format:list ^| findstr "="') do set %%x
rem Leading zeroes for everything that could be only one digit
set Month=0%Month%
set Day=0%Day%
rem Hours need special attention if one wants 12-hour time (who wants that?)
if %Hour% GEQ 12 (set AMPM=PM) else (set AMPM=AM)
set /a Hour=Hour %% 12
if %Hour%==0 (set Hour=12)
set Hour=0%Hour%
set Minute=0%Minute%
set Second=0%Second%
set Month=%Month:~-2%
set Day=%Day:~-2%
set Hour=%Hour:~-2%
set Minute=%Minute:~-2%
set Second=%Second:~-2%
rem Now you can just create your output string
echo %Month%/%Day%/%Year% %Hour%:%Minute%:%Second% %AMPM%
Note that lots of code is wasted on supporting that weird date and time format. And leading zeroes if necessary. Note also that this code works regardless of the user's regional and language settings. It does not depend on the user's date format, for example (which for me is ISO 8601 anyway).
I am no wizard with cmd.exe, but this works. There may be an easier way!
#echo off
setlocal enableextensions
for /f "tokens=*" %%a in ('date /t') do (
set d=%%a
)
for /f "tokens=*" %%a in ('time /t') do (
set t=%%a
)
REM Add those puppies together
set "dt=%d% %t%"
echo %dt%
27/11/2013 16:04
For CMD, Why not the simple:
C:\temp\test>ECHO %DATE% %TIME%
Mon 06/24/2019 18:00:17.63
If you want to strip off the Day at the beginning, here's a condensed version of what Joey did, using substrings.
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set timestamp=%dt:~0,4%/%dt:~4,2%/%dt:~6,2% %dt:~8,2%:%dt:~10,2%:%dt:~12,2%
ECHO %timestamp%
2019/06/24 17:56:43
2019/06/24 17:56:43
You can use as well the .NET DateTime in powershell:
Write-Host "Current datetime is $([System.Datetime]::Now.ToString("dd/MM/yy HH:mm:ss"))"
thank you all i was looking for inline date and time column string.
#date time sample
Select-Object #{ l='DateTime'; e={ (Get-Date).tostring("yyyyMMddHHmm")} }
here is the full script below. for remote query
do {
$MHEdate = (Get-Date).tostring("yyyyMMddHHmmss") # example output 20161122.
$OutputDir = "C:\tools\pshell\LOG\"
$logoname = 'getcoonections-filter-' + $MHEdate1 + '.csv'
$OutputFile1 = Join-Path $OutputDir $logoname
Invoke-Command -ComputerName ServerName {
#output to csv
get-nettcpconnection | select local*,remote*,state,#{Name="Process";Expression={(Get-Process -Id $_.OwningProcess).ProcessName}},#{Name="ProcessID";Expression={(Get-Process -Id $_.OwningProcess).Id}}| Where-Object {($_.RemoteAddress -notcontains '0.0.0.0') -and ($_.RemoteAddress -notcontains '127.0.0.1') -and ($_.RemoteAddress -notcontains '::') -and ($_.RemoteAddress -notcontains '::1')} #|Where-Object{ $_.remoteaddress -Contains '168.135.115.248'}
# start-sleep -Seconds 15
}| Select-Object #{ l='DateTime'; e={ (Get-Date).tostring("yyyyMMddHHmm")} },PSComputerName,LocalAddress,LocalPort,RemoteAddress,RemotePort,State,Process,ProcessID | Export-Csv -Path $OutputFile1 -NoTypeInformation -Append
#Import-Csv $OutputFile1 |Out-GridView
write-host -ForegroundColor Green $Time "query output file is ---> " $OutputFile1
Start-Sleep 120
}until($infinity)