LoginSignup
2
2

More than 5 years have passed since last update.

PowerShellで「.」でメソッドチェーンせずに「|」でメソッドをつなぎたい!

Last updated at Posted at 2018-11-24

やりたいこと

以下のようにすれば、https://example.com のHTTPのBody部分が取れます。

(Invoke-WebRequest -Uri https://example.com).Content

ですが()をつけずに|でパイプしたいときがあります。理想としては、以下みたいな感じにしたいです。

理想
# 注意:これは理想です
Invoke-WebRequest -Uri https://example.com | <何らかの記法>.Content

方法

追記(2018-11-24):
@KyoPeeee さんにコメントで教わった方法のほうが短くてタイプしやすいので、先に書かせていただきます。

Invoke-WebRequest -Uri https://example.com | % Content

以下のようにつなげていくことも可能ですね。

Invoke-WebRequest -Uri https://example.com | % Content | % Length

追記おわり


コマンド | %{$_.プロパティ}で行けそうです。
具体例は、以下のとおりです。

Invoke-WebRequest -Uri https://example.com | %{$_.Content}    

参考:PowerShell で 関数実行結果の型をパイプラインの先に伝搬する - tech.guitarrapc.cóm

出力
<!doctype html>                                                                                                        <html>                                                                                                                 <head>                                                                                                                     <title>Example Domain</title>                                                                                      

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;

    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 50px;
        background-color: #fff;
        border-radius: 1em;
    }
    a:link, a:visited {
        color: #38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        body {
            background-color: #fff;
        }
        div {
            width: auto;
            margin: 0 auto;
            border-radius: 0;
            padding: 1em;
        }
    }
    </style>    
</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is established to be used for illustrative examples in documents. You may use this
    domain in examples without prior coordination or asking for permission.</p>
    <p><a href="http://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2