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?

PowerShellでのエイリアスの設定方法(bashコマンドの拡充)

Posted at

対象者

  • WindowsのPowerShellのコマンドを簡易的にbashコマンドを拡充したい方
  • エイリアス(別名)設定のため、完全にはbashコマンドと一致せず、細かい動作が異なる点に留意すること

概要

  • PowerShellでは、ある程度bashのコマンドにエイリアスが設定されているが、未設定のコマンドは別途設定する必要がある
  • 本ページでは、PowerShellでのエイリアスの設定方法を記載する
    • 例として、lsの色付けとtouchを記載

設定方法

  • 以下のフォルダにPowerShellのプロファイル「Microsoft.PowerShell_profile.ps1」を作成する。フォルダがない場合は、フォルダも作成する。

    • フォルダ: %USERPROFILE%\Documents\WindowsPowerShell
      • {%USERPROFILE%}は、「C:\Users{ユーザー名}」を表す環境変数
    • ファイル名:Microsoft.PowerShell_profile.ps1
  • 作成したファイル内に登録したいコマンドを以下の書式で記載。参照:エイリアスの作成(引数が複数ある場合)【BashとPowerShellの比較】

    • 引数がない場合
      set-alias ls myls
      
    • 引数がある場合
      function {省略形}
      {
          対象のコマンド
      }
      
      (例)
      function touch
      { 
        New-Item $args
      }
      
  • PowerShellを新規起動し、設定したコマンドを実行できるかを確認する。起動時に以下のエラーが表示される場合は、実行ポリシーの設定変更をする

    • エラーメッセージ: このスクリプトは現在のシステムでは実行できません。スクリプトの実行および実行ポリシーの設定の詳細については、「about_Execution_Policies」を参照してください
    • 対応方法: PowerShellを管理者として実行し、以下のコマンドで設定する。ポリシー名はabout_Execution_Policiesを参照のこと
    • 【注意】実行ポリシーの設定変更に関しては、セキュリティ上問題ないかを確認の上で実行ください
      Set-ExecutionPolicy -ExecutionPolicy {ポリシー名}
      (例)
      Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
      

設定ファイルの例

rm alias:ls -force
set-alias ls myls

filter lsColor{
    if($_.mode[0] -eq "d"){
        Write-Host $_.name -ForeGroundColor Blue
    }
    elseif($_.get_Extension() -eq ".exe"){
        Write-Host $_.name -ForeGroundColor Green
    }
    else{
        Write-Host $_.name
    }
}

function myls{
    $c = "Get-ChildItem " + $args
    Invoke-Expression $c | lsColor
}

function touch {
    if ($args) {
        New-Item $args
    }
    else {
        echo "No arguments!"
    }
}

補足

参照サイト

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