「マイクロソフト系技術情報 Wiki」は、「Open棟梁Project」,「OSSコンソーシアム .NET開発基盤部会」によって運営されています。
PS1ファイルの作成と実行について。
の様にして実行できる。
Set-ExecutionPolicy RemoteSigned
実行できます。
Set-ExecutionPolicy Restricted
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
メンテナンスや運用作業で.ps1を使用する場合は、
通常時にどの実行ポリシーにしておくか、検討ください。
ps_test.bat
@( echo $arg1 = "%~1" echo $arg2 = "%~2" type ps_test.ps1 ) | powershell -command -
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
標準入力を手入力の代わりに使用してしまうため、
スクリプトのなかでキー打鍵待ちのようなことは難しくなります。
しかありません。
$global:g1 = "0" $script:s1 = "0" $v1 = "0" write-host "before : g1=$global:g1 s1=$script:s1 v1=$v1 v2=$v2" function test1 { write-host "start test1 : g1=$global:g1 s1=$script:s1 v1=$v1 v2=$v2" $global:g1 = "1" $script:s1 = "1" $v1 = "1" $v2 = "1" write-host "end test1 : g1=$global:g1 s1=$script:s1 v1=$v1 v2=$v2" } test1 write-host "after : g1=$global:g1 s1=$script:s1 v1=$v1 v2=$v2"
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スクリプトへの引数
param ( [string]$filename, [int]$count = 5 )
powersehll .\test.ps1 -filename c:\temp\testt.txt -count 2
の様に -引数名 として使用できます。
param ( [Parameter(Mandatory=$True)] [string]$filename, [int]$count = 5 )
Tags: :シェル, :インフラストラクチャ, :Windows