リンク

スクリプトの実行許可

起動設定

  • 「プロファイル」に設定を記述しておくことで、起動時にモジュール登録等を自動的に行える。
  • プロファイルの場所の確認
    > $profile
  • プロファイルの再適用
    > . $profile
  • サンプル Microsoft.PowerShell_profile.ps1

    • Windows

      function prompt() {
        $env:USERNAME + "@" + $env:COMPUTERNAME + " " + (Split-Path (Get-Location) -Leaf) + "> "
      }
      
      $currentDir = Split-Path $MyInvocation.MyCommand.Path
      Import-Module (Join-Path $currentDir "Get-NetworkStatistics.psm1")
      
    • Linux ~/.config/powershell/Microsoft.PowerShell_profile.ps1 powershell function prompt() { $env:LOGNAME + '@' + (hostname -s) + ' ' + (Split-Path (Get-Location) -Leaf) + '> ' }
  • Windows PowerShell プロファイル

TCP/UDP ポートを使用しているプロセスをリストアップ

  • checkUsingPort.zip

    # TCP/UDP ポートを使用しているプロセスをリストアップする。
    # Get-NetTCPConnection 不使用
    
    $running_proc = @{}
    foreach( $proc in Get-Process ){
    	$running_proc[ $proc.Id ] = $proc.ProcessName
    }
    
    $re = "^\s*(?<proto>\S+)\s+(?<lhost>\S+):(?<lport>[^:\s]+)\s+"
    $re += "(?<rhost>\S+):(?<rport>[^:\s]+)\s+(?<stat>\S*)\s+(?<pid>\d+)$"
    $regex = [regex] $re
    
    $using_ports = @{}
    $ports = netstat -ao | Select-String "TCP|UDP"
    foreach( $line in $ports ){
    	$m = $regex.Matches( $line )
    	if ( $m[0].Success ){
    		$id = 0
    		[void][int]::TryParse( $m[0].Groups["pid"].Value, [ref]$id )
    		$name = $running_proc[ $id ] + " (PID: " + $id + ")"
    		if ( ! $using_ports[ $name ] ){
    			$using_ports[ $name ] = @{}
    		}
    		$port = $m[0].Groups["proto"].Value + "/" + $m[0].Groups["lport"].Value
    		$using_ports[ $name ][ $port ] = $m[0].Groups["stat"].Value
    	}
    }
    
    foreach( $name in ( $using_ports.Keys | sort ) ){
    	write-host "${name}"
    	foreach( $port in ( $using_ports[ $name ].Keys | sort ) ){
    		$status = $using_ports[ $name ][ $port ]
    		write-host "`t${port}`t${status}"
    	}
    }
    
    # EOF
  • Get-NetworkStatistics (or 'netstat' for PowerShell) - xcud

    • 予めモジュールとして登録しておいて使う。
      > Import-Module Get-NetworkStatistics.psm1
      > Get-NetworkStatistics | Format-Table
      > Get-NetworkStatistics  | Sort-Object ProcessName | Format-Table
  • TCPView for Windows
  • Get-Netstat 1,1 @ PowerShell Code Repository

管理者権限の確認

#Requires -RunAsAdministrator
$identity = [Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
If (-not $identity.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
  Write-Warning '管理者権限がありません。管理者として再実行してください。'
  Break
}
Write-Host '管理者です。'

システム情報の表示

IP アドレスの表示

Get-NetIPAddress |
  Sort-Object -Property InterfaceAlias, AddressFamily, IPAddress |
  Format-Table -Property InterfaceIndex, InterfaceAlias, AddressFamily, IPAddress

イベントログ

  • イベントログを記録するには事前にイベントソースを登録しておく必要がある。
  • 登録済みのイベントソースを全てリストアップ。(Application, 管理者権限不要)
    Get-ChildItem HKLM:\SYSTEM\CurrentControlSet\Services\EventLog\Application |
      Select-Object PSChildName
  • 登録済みのイベントソースで「v」から始まる名前のものをリストアップ。
    Get-ChildItem HKLM:\SYSTEM\CurrentControlSet\Services\EventLog\Application |
      ?{ $_.PSChildName.ToLower().StartsWith("v")} |
      Select-Object PSChildName
  • 新規イベントソース登録 (要管理者権限)
    New-EventLog -Source "MyApp1" -LogName "Application"
  • イベントソース削除 (要管理者権限)

    Remove-EventLog -Source "MyApp1"
  • New-EventLog

  • Remove-EventLog

レジストリ読み書き

タスクスケジューラーの操作

既存タスクの有効化/無効化

# タスク有効化/無効化
#Requires -RunAsAdministrator

# 指定パス内の全タスクを有効化
$taskPath = '\Test1\'
Get-ScheduledTask -TaskPath $taskPath |
  ForEach-Object { Enable-ScheduledTask -TaskPath $_.TaskPath -TaskName $_.TaskName } |
  Format-Table -AutoSize

# 指定タスクを無効化
@(
  @('\Test1\', 'テスト_コピー'),
  @('\Test1\', 'テスト_バックアップ')
) | ForEach-Object { Disable-ScheduledTask -TaskPath $_[0] -TaskName $_[1] } |
  Format-Table -AutoSize

ファイアウォールの操作

SSH-Agent サービスの有効化

# Make sure you're running as an Administrator
Set-Service ssh-agent -StartupType Automatic
Start-Service ssh-agent
Get-Service ssh-agent

多重起動防止

$mutex = New-Object System.Threading.Mutex($false, "Global\myAppName")
$hasHandle = $true
try {
  $hasHandle = $mutex.WaitOne(0, $false)
  if (-not $hasHandle) {
    Write-Warning "Already running."
    exit
  }
  # 本来の処理
}
finally {
  if ($hasHandle) {
    $mutex.ReleaseMutex()
  }
  $mutex.Close()
}

IME再起動

  • 日本語入力が効かなくなった場合、IMEの再起動を試してみる。
  • 要管理者権限。PowerShell は 管理者として実行 で起動すること。
  • ctfmon.exe のプロセス ID が変わっていれば再起動されている。
    Get-Process ctfmon
    Get-Process ctfmon | ForEach-Object { Stop-Process -Id $_.id }
    Get-Process ctfmon

PowerShell Core のインストール