マイクロソフト系技術情報 Wiki」は、「Open棟梁Project」,「OSSコンソーシアム .NET開発基盤部会」によって運営されています。

目次

概要

PS1ファイルの作成と実行について。

実行ポリシー

の様にして実行できる。

実行ポリシーを変更

Set-ExecutionPolicy?

実行できます。

メンテナンスや運用作業で.ps1を使用する場合は、
通常時にどの実行ポリシーにしておくか、検討ください。

PowerShell -Command - 構文でスクリプトを読み込ませる

batファイル

ps_test.bat

@( echo $arg1 = "%~1"
   echo $arg2 = "%~2"
   type ps_test.ps1 ) | powershell -command -

ps1ファイル

ps_test.ps1

function main() {
 $a = ($arg1 + $arg2)
 $b = ([int]$arg1 + [int]$arg2)
 write-output "string : $arg1 + $arg2 = $a"
 write-output "integer : $arg1 + $arg2 = $b"
}

$err=0
$ErrorActionPreference = "stop"
try {
  $log = main
} catch [Exception] {
  $err=1
  $log = $_
}

write-output $log
exit $err

実行例

これを実行すると、echo の2つが ps_test.ps1 の先頭に挿入されて、
PowerShellコマンドプロンプトに手入力して逐次実行することになります。

ps_test 1 2

string : 1 + 2 = 12
integer : 1 + 2 = 3

標準入力を手入力の代わりに使用してしまうため、
スクリプトのなかでキー打鍵待ちのようなことは難しくなります。

PowerShellコマンドプロンプトの中に貼り付ける

しかありません。

変数のスコープ

スクリプト

実行例

 E:\temp>powershell
 Windows PowerShell
 Copyright (C) 2009 Microsoft Corporation. All rights reserved.
 
 PS E:\temp> Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

 PS E:\temp> .\ps_scope1.ps1
 before      : g1=0 s1=0 v1=0 v2=
 start test1 : g1=0 s1=0 v1=0 v2=
 end test1   : g1=1 s1=1 v1=1 v2=1
 after       : g1=1 s1=1 v1=0 v2=

 PS E:\temp> write-host "g1=$global:g1 s1=$script:s1 v1=$v1 v2=$v2"
 g1=1 s1= v1= v2=

 PS E:\temp>

解説

引数

ps1スクリプトへの引数

の様に -引数名 として使用できます。

参考


Tags: :シェル, :インフラストラクチャ, :Windows


トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS