検出PowerShell関数の入力がリダイレクトされている


1

対話型である可能性がある、または直接データをパイプ処理する可能性がある、PowerShellから呼び出すサブプロセスがあります。例えば:

# This is interactive:
& c:\python27\python.exe

# This takes redirected input:
echo hi | & c:\python27\python.exe -c "print repr(raw_input())"

そのようなプロセスへの呼び出しをラップするために使用できる関数を作成したいです。私がすることができます:

function python() {
    & c:\python27\python.exe @args
}

# This starts an interactive prompt:
python

# The piped data disappears and the process still reads from the console:
echo hi | python -c "print repr(raw_input())"

または私はこれを行うことができます:

function python() {
    $input | & c:\python27\python.exe @args
}

# This doesn't accept interactive input:
python

# The piped data is passed through to the sub-process as intended:
echo hi | python -c "print repr(raw_input())"

両方のケースを処理する関数を書く方法を私は理解することができません。パイプラインなしで呼び出された場合は標準入力から読み込むサブプロセスを起動し、パイプライン入力で呼び出された場合はサブプロセスの標準入力に渡します。これはできますか?

回答:


2

の値を確認できます $MyInvocation.ExpectingInput あなたの関数がパイプライン入力を期待しているか、それがpipelineの最初の要素であるかを調べる式。

function python {
    if($MyInvocation.ExpectingInput){
        $input | & c:\python27\python.exe @args
    }else{
        & c:\python27\python.exe @args
    }
}

1

関数にパラメータを定義してください。それはあなたのデータを保持します。それからパラメータが供給されているかどうかを確認し、それに応じて動作します。あなたは方法のためにいくらかの微調整をしなければならないかもしれません PowerShellがデータを外部プログラムに渡す方法 しかし、基本的な考え方は成り立ちます。

ベアボーンの例:

使用法:

'foo', '', 'bar' | Invoke-Python

ここに配列を渡します。 Invoke-Python 関数。

結果:

  • 'foo'はPythonにパイプされます
  • それから、関数は空のパラメータに出会い、対話型pythonを起動します
  • 対話型pythonを終了した後、この関数はpythonに 'bar'をパイプで送ります。

Invoke-Python 関数:

function Invoke-Python
{
    [CmdletBinding()]
    Param
    (
        # This parameter will catch your input data
        [Parameter(ValueFromPipeline = $true)]
        [string]$InputObject
    )

    # This block runs when pipeline is initialized.
    # It doesn't have access to the parameters,
    # they are not yet parsed at this time.
    Begin
    {
        # Set path to the python
        $PythonPath = 'c:\python27\python.exe'
    }

    # This block runs for each pipeline item
    Process
    {
        # Check, is there anything passed in the InputObject parameter
        if($InputObject)
        {
            Write-Host 'We have some data, let''s pipe it into the python'
            $InputObject | & $PythonPath @('-c', 'print repr(raw_input())')
        }
        else
        {
            Write-Host 'No data, let''s just launch interactive python'
            & $PythonPath
        }
    }
}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.