0
0

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 3 years have passed since last update.

PowerShell インターフェースもどき実装

Posted at

PowerShell を実装していて Java のインターフェース的なことをやりたいなと思い実装してみる。
型安全ではないけれど処理の重複は防ぐことができそう。。。
もっと良い方法ありそうだけど簡易的にはできた。。。

例えで処理を try / catch してエラー時の処理を統一してみる。
他にも仕組みを変えればいろいろできる。

# 処理実行クラス
# 処理を try /catch して実行、エラー処理を catch に書く
class Main {
    [int] $exitErrorCode;
    ExitCode([int]$_exitErrorCode) {
        $this.exitErrorCode = $_exitErrorCode;
    }

    [int] main([Object]$run) {
        try {
            $run.run();
            return 0;
        } catch {
            Write-Host "Error";
            Write-Host "共通的なエラー処理を描くかんじ";
            return $this.exitErrorCode;
        }
    }
}

# 処理クラス エラー
class RunError {
    [void] run() {
        Write-Host "Error 発生 ないパスで Move-Item";
        Move-Item aaaa\bbbb\cccc\dddd eeeee;
    }
}

# 処理クラス 通常
class RunNormal {
    [void] run() {
        Write-Host "Error 発生なし";
        Write-Host "実際にやりたい処理を描くかんじ"
    }
}

############# 上で作ったクラスを使って以下の感じで実行
$ErrorActionPreference = "Stop"
$MainClass = New-Object Main(99);

$RunErrorClass = New-Object RunError;
$RunNormalClass = New-Object RunNormal;

$MainClass.main($RunErrorClass);
$MainClass.main($RunNormalClass);

0
0
5

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?