macOS で Powershell - rehabilitation 編 -1 : スクリプトファイルの起動
macOS での Powershell core について記事を書こうと思っていたけど、風邪でヘタってしまった。
まだ本調子ではないのと、Powershell を使わなくなって2年以上経過してしまったので、今回からしばらくは軽いネタ。
Powershell のスクリプトファイルの実行方法は…
- Powershell(pwsh)の中から .file path で起動
- bash から pwsh -File
で起動 - スクリプトファイルに shebang を埋め込んで、実行権限付与で起動
の3通りがある(他にもあるかもしれないけど、今ちょっと思いつかない)。
1. と2. の場合、Windows では予め実行権限(Executionpolicy)の設定を確認する必要があるのだけど Powershell core は Executionpolicy が Unrestrikted 固定で変更できないため無視でき、スクリプトファイルには単にスクリプトを記載するだけで済む。
script を pipe で set-content に渡している。
set-content は Windows 版 Powershell では alias が sc だったけど、bash のコマンドとぶつかるので Powershell core ではこの alias は使えないっぽい。
PS /Users/hoge> "Write-Host 'Hello World'" | set-content develop/hello.ps1 PS /Users/hoge>
1. Powershell(pwsh)の中から .file path で呼び出す
PS /Users/hoge> ./develop/hello.ps1 Hello World PS /Users/hoge>
2. shell(bash)から pwsh に続けて -FIle オプションで呼び出す
MacTheKnife:~ hoge$ pwsh -FILE develop/hello.ps1 Hello World MacTheKnife:~ hoge$
3. の場合、スクリプトファイルに shebang を埋め込む。
shebang を埋め込む都合で script が2行になったので、here-string を pipe で set-content に渡している。
PS /Users/hoge> @" #!/usr/local/bin/pwsh -File Write-Host 'test!!' "@ | set-content develop/test.ps1 PS /Users/hoge>
shell(bash)からスクリプトファイルに実効権限を付与し、スクリプトファイルを呼ぶ。
MacTheKnife:~ hoge$ chmod +x Develop/test.ps1 MacTheKnife:~ hoge$ Develop/test.ps1 test!! MacTheKnife:~ hoge$