0
4

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のベストプラクティス

Last updated at Posted at 2022-05-03

PowerShellで開発したので、個人的なベストプラクティス

Version

cmd
>powershell

\> $PSVersionTable

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

構成

batファイルからps1ファイルをキックして、
ps1ファイルでpsm1(module)を読み込む

※batファイルだとWindowsでダブルクリックで実行できる

関係図
bat → ps1 (1:1)
ps1 → psm1 (1:N)
psm1 → psm1 (1:N)

ディレクトリ構成

:batはディレクトリ直下
bat1.bat
bat2.bat

Config: const格納用
    Config.psm1

Module: ps1(モジュール)格納用
    module1.psm1
    module2.psm1

Ps: ps1ファイル格納用
    ps1.ps1
    ps2.ps1

※ディレクトリ名はお好みで

const

$env変数につっこむ

Config¥Config.psm1
# ディレクトリのセパレータ文字列
$env:DIRECTORY_SEPARATOR_CHAR = [string]([IO.Path]::DirectorySeparatorChar)

# configディレクトリ
$env:CONFIG_LOCATION = $PSScriptRoot + $env:DIRECTORY_SEPARATOR_CHAR

# rootディレクトリ
$env:ROOT_LOCATION = $env:CONFIG_LOCATION + '..' + $env:DIRECTORY_SEPARATOR_CHAR

# moduleディレクトリ
$env:MODULE_LOCATION = $env:ROOT_LOCATION + 'module' + $env:DIRECTORY_SEPARATOR_CHAR

$PSScriptRoot
スクリプトの親ディレクトリが格納されている特殊変数

利用方法

¥Ps¥ps1.ps1
using module '../config/App.psm1'

Moduleファイルの読み込み

Export-ModuleMemberImport-Moduleを利用

module側

¥Module¥module1.psm1
class Module1
{
    # ...
}

function newModule1() {
    return [Module1]::new()
}

Export-ModuleMember -Function 'newModule1'

利用側

¥Ps¥ps1.ps1
# ... configファイルの読み込み / 引数取得など

$import_module = $env:MODULE_LOCATION + 'Module1.psm1'
Import-Module $import_module -Function 'newModule1'

$module1 = newModule1

PowerShellのクラスにはnamespace的なものがないらしい
class名のバッティング回避のため、Export-ModuleMemberの利用を選択しました

Import-Moduleの構文中に+での文字列連結はできないので、
上記のように文字列連結する場合にはあらかじめ変数に格納しておく必要があります

関数名がバッティングした際の回避方法

Import-Moduleのオプションに-Prefixがあり、こちらを設定することで回避が可能です

$import_module = $env:MODULE_LOCATION + 'Module1.psm1'
Import-Module $import_module -Function 'newModule1' -Prefix 'x'

# xnewModule1 で呼び出し可能

さいごに

公式のドキュメントがしっかりしてますが、
サンプルコードがあまりないので、
トライアンドエラー+検索って感じで開発しました

0
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?