can't read inside of txt file with batch file

Viewed 63

after writing IP inside txt using PowerShell, I can't read it with batch file

inside txt file

122.237.121.26
$Line = Invoke-RestMethod -Uri "http://ipinfo.io" | select-object -property ip
($Line  |  Select-String -Pattern "\d{1,3}(\.\d{1,3}){3}" -AllMatches).Matches.Value | Out-File -FilePath C:\src\Newfolder\currentip.txt
For /F UseBackQ^ Delims^=^ EOL^= %%G In ("C:\src\Newfolder\currentip.txt") Do Set "k=%%G"
echo %k%
pause

but if I manually create "currentip.txt" and put ip inside it manually, then run this command

For /F UseBackQ^ Delims^=^ EOL^= %%G In ("C:\src\Newfolder\currentip.txt") Do Set "k=%%G"
echo %k%
pause

I get output, but if I use PowerShell I got this messege

C:\src\Newfolder>For /F UseBackQ Delims= EOL= %G In ("C:\src\Newfolder\currentip.txt") Do Set "k=%G"

C:\src\Newfolder>echo
ECHO is on.

C:\src\Newfolder>pause
Press any key to continue . . .
2 Answers

try

$Line = Invoke-RestMethod -Uri "http://ipinfo.io" | select-object -property ip
($Line  |  Select-String -Pattern "\d{1,3}(\.\d{1,3}){3}" -AllMatches).Matches.Value | Out-File -FilePath C:\fruitlab\temp\currentip.txt -Encoding ascii

add

-Encoding ascii

so it Encoding ps output into ascii as batch reads ascii

It seems to me as if you've made this more complicated than it needs to be. You could try it without a holding text file, which would mean that the encoding of that file will not be a problem. Also I'm not sure what the purpose of using a selection pattern against the returned ip is, as I presume it would always be returned in IPv4 format.

@For /F %%G In ('%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe
 -NoProfile "(Invoke-RestMethod -Uri \"http://ipinfo.io\").ip" 2^>NUL'
) Do @Echo %%G
@Pause
Related