Windows Powershell 初心者 一覧

今までコマンドプロンプトで逃げてたけど、やっとPowershell本気でやらないとなという事でまとめはじめてます。 いつもの様に、1ページである程度使えるようにまとめていきます。

基本コマンド一覧

pwd
whoami   # ユーザー名の大文字小文字は区別されず同じになる
cd
dir
dir -File
dir -Directory
Get-ChildItem -File    # dir -Fileと同じ
Get-ChildItem -Path . -Recurse | Where-Object { $_.Extension -eq ".rc" -or $_.Extension -eq ".txt" }
Get-ChildItem -Directory    # dir -Directoryと同じ
mkdir
Get-Acl .\example_directory | Format-List   #ディレクトリのアクセス権限表示
Get-Acl "." | Select-Object -ExpandProperty Owner

Get-Help Get-Process             # コマンドのヘルプを表示
Get-PSDrive                      # df同様ドライブの空き容量確認

$env:WX_DIR = "C:\path\to\wxWidgets"
echo $env:WX_DIR
コマンドレット説明
Get-Helpコマンドレットやスクリプトのヘルプ情報を表示します。
Get-Command使用可能なコマンドレット、エイリアス、関数の一覧を表示します。
Get-Process実行中のプロセスの情報を表示します。
Stop-Process指定したプロセスを停止します。
Get-Serviceシステム上のサービスの状態を表示します。
Start-Service指定したサービスを開始します。
Stop-Service指定したサービスを停止します。
Get-EventLogイベントログの情報を表示します。
Get-ChildItem指定したディレクトリ内のファイルとフォルダーを表示します(dirのエイリアス)。
Copy-Itemファイルやフォルダーをコピーします。
Copy-Item -Path “C:\Path\To\SourceDirectory\*” -Destination “C:\Path\To\DestinationDirectory” -Recurse
Move-Itemファイルやフォルダーを移動します。
Move-Item -Path "C:\Path\To\SourceDirectory\*" -Destination "C:\Path\To\DestinationDirectory" -Recurse
Remove-Itemファイルやフォルダーを削除します。
Remove-Item -Path “C:\Path\To\Directory\*” -Recurse -Force
New-Item新しいファイルやフォルダーを作成します。
Set-Locationカレントディレクトリを変更します(cdのエイリアス)。
Get-Contentファイルの内容を表示します。
Set-Contentファイルに内容を書き込みます。
Add-Content既存のファイルに内容を追加します。
Clear-Hostコンソールの画面をクリアします。
Get-Variable現在のセッションで使用されている変数の一覧を表示します。
Set-Variable新しい変数を作成または既存の変数の値を変更します。
Remove-Variable変数を削除します。
Invoke-Expression文字列として指定されたコマンドを実行します。
Start-Process新しいプロセスを開始します。
Get-Help about_*PowerShellのトピックに関するヘルプを表示します。

-Recurse: 再帰的な操作。 その下のディレクトリやファイル全てに適用させる。 Linuxでは-Rや-rと同じ。

便利なエイリアス

PowerShellには、コマンドレットの短縮形として使用できるエイリアスがいくつかあります。以下はその一部です。

エイリアス対応するコマンドレット
lsGet-ChildItem
dirGet-ChildItem
catGet-Content
echoWrite-Output
rmRemove-Item
cpCopy-Item
mvMove-Item
gciGet-ChildItem
gpsGet-Process
slsSelect-String

Owner変更方法

未検証

$newOwner = "DOMAIN\NewOwner"  # 新しい所有者のユーザー名
$acl = Get-Acl "C:\Path\To\Your\FileOrDirectory"
$acl.SetOwner([System.Security.Principal.NTAccount]$newOwner)
Set-Acl "C:\Path\To\Your\FileOrDirectory" $acl

Powershell起動時実行ファイル

  • C:\Users\<user_name>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1が実行されるファイル。 PowerShellスクリプトまたはps1ファイルと呼びます。
  • Ctrl+Cで停止
$PROFILE     # これでパスとファイル名を確認
             # 最初は存在しないので以下で作成する

if (!(Test-Path -Path $PROFILE)) {
    New-Item -ItemType File -Path $PROFILE -Force
}
            #  これでファイルが出来るので以下で編集する
notepad $PROFILE
            # 編集完了して保存したら以下実行して$PROFILEを再読み込みする(権限を設定する必要あり。後述。)
. $PROFILE

以下を書込めば、ddirがディレクトリだけ表示するコマンドになる。

Function ddir {
    param(
        [string]$Path = ".",
        [System.Management.Automation.SwitchParameter]$Recurse
    )

    if ($Recurse) {
        Get-ChildItem -Path $Path -Directory -Recurse
    }
    else {
        Get-ChildItem -Path $Path -Directory
    }
}

killマクロ

マクロの引数指定もMandatoryのtrue、false設定方法も。

Function kill{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$arg0,

        [Parameter(Mandatory = $false, Position = 1)]
        [string]$arg2
    )
    if($arg0 -eq "-9"){
        Stop-Process -Id $arg1 -Force
    }else{
        Stop-Process -Id $arg0
    }
}

権限設定

PS C:\Users\USER_NAME> . $PROFILE
. : このシステムではスクリプトの実行が無効になっているため、ファイル C:\Users\9033113\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 を
読み込むことができません。詳細については、「about_Execution_Policies」(https://go.microsoft.com/fwlink/?LinkID=135170) を参照してください。
発生場所 行:1 文字:3
+ . $PROFILE
+   ~~~~~~~~
    + CategoryInfo          : セキュリティ エラー: (: ) []、PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess
PS C:\Users\USER_NAME> dir $PROFILE


    ディレクトリ: C:\Users\9033113\Documents\WindowsPowerShell


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        2025/02/13     13:46            281 Microsoft.PowerShell_profile.ps1


PS C:\Users\USER_NAME> Get-ExecutionPolicy -List

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine       Undefined


PS C:\Users\USER_NAME> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
PS C:\Users\USER_NAME> Get-ExecutionPolicy -List

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser    RemoteSigned
 LocalMachine       Undefined


PS C:\Users\9033113> . $PROFILE
PS C:\Users\9033113> ddir


    ディレクトリ: C:\Users\9033113


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        2025/01/10     13:09                .cert
d-----        2024/06/07     15:05                .ipython
d-----        2024/07/29     16:23                .jupyter
d-----        2024/06/07     15:20                .keras
d-----        2023/02/14     11:40                .ms-ad
d-----        2025/01/10     13:32                .pyenv
d-----        2025/01/17     11:04                .ssh

実行可能ファイル

  • Windowsの場合は、exe、bat, ps1が実行可能ファイルだそうです。 
  • msiファイルはmsiexe.exeファイルを呼び出しているんだそうです。 ショートカットと同じかな。
    • msiファイルにはアプリに必要なファイル、レジストリ設定、インストール手順などを記述するファイル。

特定文字を含んだプロセス表示

  • 簡単表示
Get-Process *Hello* | Select-Object Id, ProcessName

   Id ProcessName
   -- -----------
28156 wxHelloWorld
  • 詳細表示
  • したの2行の意味は同じ。 Where-Objectはもっと複雑な検索時に使用する。
Get-Process | Where-Object { $_.Name -like "*Hello*" } | Format-List *
Get-Process *Hello* | Format-List *

Name                       : wxHelloWorld
Id                         : 28156
PriorityClass              : Normal
FileVersion                :
HandleCount                : 208
WorkingSet                 : 23355392
PagedMemorySize            : 10571776
PrivateMemorySize          : 10571776
VirtualMemorySize          : 212340736
TotalProcessorTime         : 00:00:00.0156250
SI                         : 1
Handles                    : 208
VM                         : 4507308032
WS                         : 23355392
PM                         : 10571776
NPM                        : 23720
Path                       : C:\Users\9033113\Documents\project\wxHelloWorld\build\wxHelloWorld.exe
Company                    :
CPU                        : 0.015625
ProductVersion             :
Description                :
Product                    :
__NounName                 : Process
BasePriority               : 8
ExitCode                   :
HasExited                  : False
ExitTime                   :
Handle                     : 3088
SafeHandle                 : Microsoft.Win32.SafeHandles.SafeProcessHandle
MachineName                : .
MainWindowHandle           : 2493886
MainWindowTitle            : Hello World
MainModule                 : System.Diagnostics.ProcessModule (wxHelloWorld.exe)
MaxWorkingSet              : 1413120
MinWorkingSet              : 204800
Modules                    : {System.Diagnostics.ProcessModule (wxHelloWorld.exe), System.Diagnostics.ProcessModule (ntdll.dll), System.Diagnostics.P
                             rocessModule (KERNEL32.DLL), System.Diagnostics.ProcessModule (KERNELBASE.dll)...}
NonpagedSystemMemorySize   : 23720
NonpagedSystemMemorySize64 : 23720
PagedMemorySize64          : 10571776
PagedSystemMemorySize      : 302624
PagedSystemMemorySize64    : 302624
PeakPagedMemorySize        : 10813440
PeakPagedMemorySize64      : 10813440
PeakWorkingSet             : 23416832
PeakWorkingSet64           : 23416832
PeakVirtualMemorySize      : 316284928
PeakVirtualMemorySize64    : 4611252224
PriorityBoostEnabled       : True
PrivateMemorySize64        : 10571776
PrivilegedProcessorTime    : 00:00:00.0156250
ProcessName                : wxHelloWorld
ProcessorAffinity          : 4095
Responding                 : True
SessionId                  : 1
StartInfo                  : System.Diagnostics.ProcessStartInfo
StartTime                  : 2025/02/28 15:36:13
SynchronizingObject        :
Threads                    : {25860, 30668, 28588, 8008...}
UserProcessorTime          : 00:00:00
VirtualMemorySize64        : 4507308032
EnableRaisingEvents        : False
StandardInput              :
StandardOutput             :
StandardError              :
WorkingSet64               : 23355392
Site                       :
Container                  :

Where-Objectを使うと柔軟な検索ができる。

Get-Process | Where-Object { $_.Name -like "*Hello*" -and $_.CPU -gt 50 }

コマンドプロンプトでPowershellコマンド実行

powershell -Command ” “で” “内にPowershellコマンドを入れる

powershell -Command "Get-Process *Hello* | Select-Object Id, ProcessName"

コメント