4
7

More than 3 years have passed since last update.

PowerShellで躓いた点をまとめてみた。

Last updated at Posted at 2019-11-25

導入

Windowsユーザしかいないプロジェクトで簡単な効率化・自動化ツールを作るのに、環境構築が不要で配布が容易だというズボラな理由でPowerShellを採用することが増えてきています。
PowerShellでシコシコ書く中で筆者が躓いた点(どれも初歩的な部分のみですが・・)をここに纏め、自分が見返すため/同じところで躓く方のために役立つことができれば幸いです。

前提

  • Windows 10 Enterprise
  • PowerShell 5.1

躓いた点一覧

PowerShell実行ポリシーを掻い潜る

  • 実行用batを用意し一時実行ポリシーを適用してPowerShellを起動する。

    @echo off
    powershell -NoProfile -ExecutionPolicy Unrestricted .\hoge.ps1
    exit
    

文字列などの変数のNullまたは空文字を確認する

  • .NET的にStringのIsNullOrEmptyを使う
   PS > $foo = "bar"
   PS > [String]::IsNullOrEmpty($foo)
   False
  • 変数をboolにキャストする( IF文の条件式は単純に変数を入れる)
   function CheckNullOrEmpty($param){
    #変数を入れるだけ
    if($param){
        "param is not null or empty"
    }else{
        "param is null or empty"
    }
   }

   $StringNull = $null
   $stringEmpty = ""
   $stringNotEmpty = "something"
   $intNotEmpty = 100

   CheckNullOrEmpty $stringNull     #->param is null or empty
   CheckNullOrEmpty $stringEmpty        #->param is null or empty
   CheckNullOrEmpty $stringNotEmpty #->param is not null or empty
   CheckNullOrEmpty $intNotEmpty        #->param is not null or empty

PowerShellでのClass定義分離

PowerShellでClassを使っていると定義ごとに物理的分離したくなる...

  • base Classをpsm1(モジュール)化する

    class BaseClass {
        [string] hoge(){
            return "This is Base Class !!"
        }
    }
    
  • psm1 をusing moduleで読み込む
    ※ using module はコメントを除くスクリプトの先頭に書かなくてはならない制限があるため注意

    # include base class
    using module ".\base.psm1"
    
    class SubClass : BaseClass {
        [string] pyo(){
            return "This is Sub Class !!"
        }
    }
    
  • ps1 は . で読み込む

    # include class
    . ".\sub.ps1"
    
    $TestObject = New-Object SubClass
    
    $TestObject.hoge()
    

参考

Windowsにまつわるe.t.c.
http://www.vwnet.jp/Windows/etc.asp#PowerShell

あとがき

躓き次第(悲しい書き方ですが・・・)随時アップデート予定です。
誤り、もっとスマートなやり方等あれば指摘いただけると幸いです。

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