PowerShell その他
実行ポリシー
PowerShell ISE で実行できていたスクリプトをファイルに保存してファイルを実行するときにPowerShellの実行許可がないため実行できないことがあります。その場合、管理者権限で以下の
コマンドを実行することで実行できるようになります。
#実行ポリシーの確認。Restrictedの場合、ファイルの実行はできない
Get-ExecutionPolicy
#実行ポリシーの変更。ファイルの実行を許可
Set-ExecutionPolicy RemoteSigned
バージョン情報
$PSVersionTableでバージョン情報を取得できます。
$PSVersionTable
実行イメージ
PSVersionがPowershellのバージョン。
CLRVersionが.NET Frameworkの実行環境(CLR)のバージョン。
環境変数
$env:で環境変数を取得できます。
$fullPath = Join-Path $env:TEMP "tmp.txt"
Write-Output $fullPath
スリープ
#3秒スリープ
Start-Sleep 3
#3秒スリープ
sleep 3
#3秒スリープ
Start-Sleep -s 3
#3ミリ秒スリープ
Start-Sleep -m 3
コンピュータのシャットダウン、再起動
シャットダウン
Stop-Computer -Force
再起動
Restart-Computer -Force
ゴミ箱を空にする
ゴミ箱を空にする
Clear-RecycleBin -Force
ダイアログ
# ダイアログを使用するためには、 System.Windows.Forms を使用すると宣言
Add-Type -Assembly System.Windows.Forms
# 単純なメッセージダイアログ
[System.Windows.Forms.MessageBox]::Show("Hello World")
# 確認ダイアログ
$ret = [System.Windows.Forms.MessageBox]::Show("内容", "タイトル", "YesNo")
if ($ret -eq 'Yes') {
echo 'はいが押された'
}
echo $ret
YesNo の部分は以下が指定できます。
指定できるもの |
---|
OK |
OKCancel |
AbortRetryIgnore |
YesNoCancel |
YesNo |
RetryCancel |
起動オプション
PowerShellで書いたスクリプトファイルを実行するときの起動オプションを取得するには$argsを使用します。test.ps1
echo ("引数の数:" + $args.Length)
foreach($arg in $args){
$str = [string]$arg
echo ("引数:" +$str)
}
(出力結果)
※ ./test.ps1 a b を実行したときの結果
引数の数:2
引数:a
引数:b
プロセス取得
# 実行プロセスのコマンドライン取得
Get-CimInstance -ClassName Win32_Process | Select-Object ProcessId, Name, CommandLine
# 実行プロセスのウィンドウタイトル取得
Get-Process | where {$_.MainWindowTitle -ne ''} | Select-Object Id, MainWindowTitle
ポート確認
Pingでポートも確認できないか探していたところPowerShellで Test-NetConnection というコマンドがありました。
Test-NetConnection 接続先 -port ポート番号
実行すると以下のような結果が得られます。
PS C:\Work> Test-NetConnection localhost -port 8080
警告: TCP connect to (::1 : 8080) failed
警告: TCP connect to (127.0.0.1 : 8080) failed
ComputerName : localhost
RemoteAddress : ::1
RemotePort : 8080
InterfaceAlias : Loopback Pseudo-Interface 1
SourceAddress : ::1
PingSucceeded : True
PingReplyDetails (RTT) : 0 ms
TcpTestSucceeded : False
PingSucceededがPingの確認結果、TcpTestSucceededがポートの確認結果になります。
イベントログ削除
管理者権限で実行する必要があります。指定ログ削除
Clear-EventLog -LogName "ログ名"
全ログ削除
Get-EventLog -List | foreach{ Clear-EventLog -LogName $_.Log }
タイプの取得
$ary = @()
$map = @{}
$ary.GetType()
$map.GetType()
タイプを確認するには、.GetType()を実行します。上記の結果は以下になります。
$ary.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
$map.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
ページのトップへ戻る