LoginSignup
1
1

More than 5 years have passed since last update.

Powershellで試し打ちしたコマンドの結果を、改めて変数に代入するのが面倒だなー

Posted at

とか、思っていたんですが、... | sv hogeで十分でした。

詳しく

試しにコマンドを打った後、
その結果を改めて変数に代入するの面倒だなーとか思ってたんですよ。

> 1..4 | %{2 * $_}
2
4
6
8
> $x = 1..4 | %{2 * $_}

だから、良い感じのリダイレクトがないかなーとか妄想してたんですよ。

> 1..4 | %{2 * $_} >= $x
> $x
2
4
6
8

色々調べてたら次のように書けるらしいんですよ。

> 1..4 | %{2 * $_} | Set-Variable x
> $x 
2
4
6
8

しかも Alias があって、もっと短く書けるらしいんですよ。

> 1..4 | %{2 * $_} | sv x
> $x 
2
4
6
8

便利なんですよ。

おまけ

function Out-Variable
{
  Param(
    [Parameter(Mandatory = $true)]
    [String] $Name, 

    [Parameter(ValueFromPipeline = $true)]
    $Value,

    [ValidateSet("+", "-", "*", "/", "%")]
    [String] $Operation
  )

  Begin {$array = @()}

  Process {$array += ,$Value}

  End
  {
    $x = (Get-Variable -Name $Name -Scope 1).Value

    Switch ($Operation)
    {
      "+"
      {
        if ($x -is $array.GetType())
        {
          Set-Variable -Name $Name -Value ($x + $array) -Scope 1
        }

        else
        {
          Set-Variable -Name $Name -Value ($array | %{$x + $_}) -Scope 1
        }
      }

      "-" {Set-Variable -Name $Name -Value ($array | %{$x - $_}) -Scope 1}

      "*" {Set-Variable -Name $Name -Value ($array | %{$x * $_}) -Scope 1}

      "/" {Set-Variable -Name $Name -Value ($array | %{$x / $_}) -Scope 1}

      "%" {Set-Variable -Name $Name -Value ($array | %{$x % $_}) -Scope 1}

      default {Set-Variable -Name $Name -Value $array -Scope 1}
    }
  }
}
1
1
0

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
1
1