Skip to content

Instantly share code, notes, and snippets.

@ytez
Last active May 24, 2022 07:42
Show Gist options
  • Save ytez/c16b209bcc169dc1086ba3fcc218ce6e to your computer and use it in GitHub Desktop.
Save ytez/c16b209bcc169dc1086ba3fcc218ce6e to your computer and use it in GitHub Desktop.
[PowerShell] Exit コードの範囲は?

[PowerShell] Exit コードの範囲は?

実験環境

Windows 10 Pro 21H2 (OS Build 19044.1566)

PS C:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.19041.1320
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.1320
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

PS C:\> Write-Host ( ".NET Framework: {0}" -f (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full').Version )
.NET Framework: 4.8.04084

実験用スクリプト構成

下記2ファイルを同一フォルダ階層に配置し、ps_exit_test.bat を実行

  • ps_exit_test.bat

    @echo off
    PowerShell.exe -NoProfile -ExecutionPolicy RemoteSigned -File %~dpn0.ps1 %*
    echo ERRORLEVEL=%ERRORLEVEL%
    pause
  • ps_exit_test.ps1

    # ここをいろいろ変えてみる

PS1 をいろいろ変えて実験

何も書かない

ERRORLEVEL=0

Exit 0

ERRORLEVEL=0

Exit 1

ERRORLEVEL=1

Exit 65535

ERRORLEVEL=65535

Exit 2147483647 ( 2^31 - 1 )

最大値は 2^32 - 1 らしい

ERRORLEVEL=2147483647

Exit 2147483648 ( 2^31 )

超えると 0 になる

ERRORLEVEL=0

Exit 2147483653 ( 2^31 + 5 )

それ以上大きくしても 0 にしかならない

ERRORLEVEL=0

Exit -2147483648 ( -(2^31) )

最小値は -(2^32) らしい。取りうる値は Int32 ?

ERRORLEVEL=-2147483648

Exit -2147483649 ( -(2^31 + 1) )

ERRORLEVEL=0

Exit -2147483653 ( -(2^31 + 5) )

ERRORLEVEL=0

[Environment]::Exit(1)

ERRORLEVEL=1

[Environment]::Exit(-2147483649)

Cannot convert argument "exitCode", with value: "-2147483649", for "Exit" to type "System.Int32": "Cannot convert
value "-2147483649" to type "System.Int32". Error: "Value was either too large or too small for an Int32.""
…

ERRORLEVEL=0

[Environment]::Exit(2147483648)

Cannot convert argument "exitCode", with value: "2147483648", for "Exit" to type "System.Int32": "Cannot convert value
"2147483648" to type "System.Int32". Error: "Value was either too large or too small for an Int32.""
…

ERRORLEVEL=0

まとめ

exitCode は Int32 の範囲で指定する

@ytez
Copy link
Author

ytez commented May 24, 2022

$ Write-Host ( ".NET Framework: {0}" -f (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full').Version )

.NET Framework: 4.8.04084

「.NET Framework のバージョン教えてください」と聞く代わりに実行してもらっているやつ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment