LoginSignup
18
19

More than 5 years have passed since last update.

PowerShellでのプロファイル (.bashrcのようなもの)

Last updated at Posted at 2015-08-04

発想

PowerShellで.bashrcとか.bash_profileとか.zshrcみたいなことをしたい。
この操作を行うとエイリアスの設定やそのほかの毎度の設定を楽に行うことができるようになります。

今回は例としてエイリアスの作成とシェル関数を定義してみます。

準備

まず作成したプロファイルを実行するために管理者権限のシェルから以下のコマンドを実行し、制限モードを解きます。

> Set-ExecutionPolicy Unrestricted

これを実行しないとセキュリティ上の問題でプロファイルが実行されません。

プロファイルの場所

あとは用途に合わせてプロファイルの場所を選ぶだけです。

すべてのユーザーのすべてのシェル向けのプロファイル

%windir%\system32\WindowsPowerShell\v1.0\profile.ps1

すべてのユーザーのMicrosoft.PowerShellシェル向けのプロファイル

%windir%\system32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1

指定したユーザーのすべてのシェル向けのプロファイル

%UserProfile%\Documents\WindowsPowerShell\profile.ps1

指定したユーザーのMicrosoft.PowerShellシェル向けのプロファイル($profile)

%UserProfile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

なかったらディレクトリとファイルを自分で作成してください。
あとはバリバリ書くだけです。

例: エイリアスを作成してみる

エイリアスを作成する場合はコマンドラインから以下のようにするとラクです。

> notepad $profile

llでGet-ChildItemが実行されるように設定してみます。

$profile
Set-Alias ll Get-ChildItem

以下のようになれば成功です。

> ll


    ディレクトリ: C:\Users\***


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-r---       2015/08/04      1:45                3D Objects
d-r---       2015/08/02      9:44                Contacts
...

例: 関数を作成してみる

今度は関数を作成してみます。

> notepad $profile
$profile
function wc([switch] $l, [switch] $w, [switch] $c, $file = (throw "ファイルを指定してください")) {
    $content = Get-Content $file
    $is_not_defined = $l -eq $false -and $w -eq $false -and $c -eq $false
    if ($l -eq $true -or $is_not_defined) {
        ($content | Measure-Object -Line).Lines;
    }
    if ($w -eq $true -or $is_not_defined) {
        ($content | Measure-Object -Word).Words;
    }
    if ($c -eq $true -or $is_not_defined) {
        ($content | Measure-Object -Character).Characters;
    }
}

以下のようになれば成功です。

> Get-Content file
a b cd
> wc file
1
3
6

(このwcの例ではパイプラインには対応していません)

18
19
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
18
19