Getting stdin into a Powershell stream

The following script works well when the file name is specified on the command line.

tail.bat
@echo off
set "COUNT=%1"
set "COUNT=%COUNT:-=%"
set "FILENAME=%~2"
powershell "Get-Content %FILENAME% -Last %COUNT%"

However, I need to be able to pass text to Get-Contentfrom within stdin. I would like to write the following to get the last three Subversion tags assigned to the project. What can I do to make the source code Get-Contentstandard?

svn ls svn://ahost/arepo/aproject/tags | call tail.bat -3

NB. I am not allowed to install any useful tools, such as tailoutside. This must be done using programs already available on the machine.

Update:

@ mklement0 provided an answer. After that, I added code to use the default COUNT value of 10 if not specified. This corresponds to the UNIX / Linux path.

@echo off

SET "COUNT=%~1"
IF "%COUNT:~0,1%" == "-" (
    SET "COUNT=%COUNT:~1%"
    SHIFT
) ELSE (
    SET "COUNT=10"
)
SET "FILENAME=%~1"

if "%FILENAME%" == "" (
    powershell -noprofile -command "$Input | Select-Object -Last %COUNT%"
) else (
    powershell -noprofile -command "Get-Content \"%FILENAME%\" -Last %COUNT%"
)

EXIT /B
+4
1

tail.bat :

@echo off

set "COUNT=%1"
set "COUNT=%COUNT:-=%"
set "FILENAME=%~2"

if "%FILENAME%"=="" (
  powershell -noprofile -command "$Input | Select-Object -Last %COUNT%"
) else (
  powershell -noprofile -command "Get-Content \"%FILENAME%\" -Last %COUNT%"
)

PowerShell stdin $Input, , .

:

C:> (echo one & echo two & echo three) | tail.bat -2
two
three

:

  • PowerShell , .

  • , , $Input , stdin, , ( ) , , , , Select-Object .

  • , PowerShell Get-Content (, , , -Raw); Get-Content tail, -Tail ( -Last), , .

  • CAVEAT: PowerShell :

    • - ASCII- ( 0 127), .

    • - . .


/

  • , PowerShell (. ), ; , , OEM (, DOS "CP437" - ), PS [Console]::OutputEncoding.

    • , , , , , OEM-, , .

    • , , ( ) ( chcp), ad-hoc script , , .
      , UTF-8 65001 - , TT (TrueType).

  • , , , , , ( OEM, PS [Console]::InputEncoding; : ):

    • ASCII ( )
    • UTF-16 LE ( , PowerShell Unicode, - )
  • , -Encoding <enc> Get-Content ( Windows ), stdin ( $Input) .

    • , , UTF-8 ( , [Console]::OutputEncoding):
      powershell -noprofile -command "$Input | % { [text.encoding]::utf8.GetString([Console]::InputEncoding.GetBytes($_)) } | Select-Object -Last %COUNT%"
+6

Source: https://habr.com/ru/post/1649585/


All Articles