0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowerShell と git clone の標準エラー出力で失敗したこと

Posted at

現象

PowerShell で以下のように $ErrorActionPreference = 'Stop' した状態で git clone すると、

test1.ps1
$ErrorActionPreference = 'Stop'

$Git = New-Module -AsCustomObject -ScriptBlock {
    function Clone {
        & git @('clone', 'C:/foo/test.git', 'C:/foo/test_git')
    }
}

$Git.Clone()

Write-Host 'bar'

以下のようにエラーで止まる。リポジトリはクローンできている。

コマンドプロンプトから実行
C:\foo>powershell -ExecutionPolicy RemoteSigned -File .\test1.ps1
"0" 個の引数を指定して "Clone" を呼び出し中に例外が発生しました: "ユーザー設定変
数 "ErrorActionPreference" または共通パラメーターが Stop に設定されているため、
実行中のコマンドが停止しました。Cloning into 'test_git'... "
発生場所 C:\foo\test1.ps1:9 文字:1
+ $Git.Clone()
+ ~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordE
   xception
    + FullyQualifiedErrorId : ScriptMethodRuntimeException 

対処

ググッて、

  • git clone は標準エラー出力にメッセージを出力する。
  • PowerShell は外部コマンドの実行の中で標準エラー出力があるとエラーを発生させる。
  • $ErrorActionPreference = 'Stop' なので止まる。

と理解。

対策として以下のように git clone--quiet, -q オプションを付けてメッセージを出力させない方法を採用。

$ErrorActionPreference = 'Stop'

$Git = New-Module -AsCustomObject -ScriptBlock {
    function Clone {
        & git @('clone', '-q', 'C:/foo/test.git', 'C:/foo/test_git')
    }
}

$Git.Clone()

Write-Host 'bar'

https://git-scm.com/docs/git-clone から --quiet, -q オプションについて引用。

--quiet
-q
Operate quietly. Progress is not reported to the standard error stream.

よくわからないこと

New-Module -AsCustomObject でない場合はエラーが出ない?

test.cmd
echo foo 1>&2
test2.ps1
$ErrorActionPreference = 'Stop'

& .\test.cmd # エラー出ない

New-Module -ScriptBlock {
    function Foo {
        & .\test.cmd
    }
}

Foo # エラー出ない

$Bar = New-Module -AsCustomObject -ScriptBlock {
    function Foo {
        & .\test.cmd
    }
}

$Bar.Foo() # エラー出る
コマンドプロンプトから実行
C:\foo>powershell -ExecutionPolicy RemoteSigned -File .\test2.ps1

C:\foo>echo foo  1>&2
foo

ModuleType Version    Name ExportedCommands
---------- -------    ---- ----------------
Script     0.0        __DynamicModule_cfb38636-5538-4e... Foo

C:\foo>echo foo  1>&2
foo
"0" 個の引数を指定して "Foo" を呼び出し中に例外が発生しました: "ユーザー設定変
数 "ErrorActionPreference" または共通パラメーターが Stop に設定されているため、
実行中のコマンドが停止しました。foo "
発生場所 C:\foo\test2.ps1:22 文字:1
+ $Bar.Foo()
+ ~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordE
   xception
    + FullyQualifiedErrorId : ScriptMethodRuntimeException
0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?