Linux あれこれ

Linux 関連(一部 Windows11 )の備忘録です。

「Windows11」(22H2) と「Ubuntu」で、「PowerShell」を使う〈H165-2〉

登録日: 2023-03-05 更新日: 2023-04-01

こちらの「Linux あれこれ」は「Linux」メインで投稿してますが、「Windows11」で「Linux」を使う機能に興味があり、投稿しました。

-

前回 の作業で、「Windows11」(22H2) の標準シェルが「Windows PowerShell 5.1」であることを知りました。その機能強化版である「PowerShell 7」をインストール。

また、「PowerShell 7」はマルチプラットフォーム版ということなので、「Xbuntu 22.04.1 LTS」(Ubuntu) にもインストールしました。

-

「今さら、「Windows」のCUI コマンドを覚えても…」と思っていましたが、サーバーやクラウドの世界では、Windows 関連の開発環境での「業務の効率化」では避けて通れないようです。色々と勉強することが多いですね。

その備忘録です。

-

-

使用したPC は、USB 3.0 ポートのある「Windows 11」のノートPC です。メモリ 12GB、SSD 1TB に増設しています。

UEFI 立ち上げ」のPC です。

-

(注)リンクを戻るときはブラウザの左上の「←」をクリック

-

-


目次

-

参考:

1. 「Windows PowerShell 5.1」について:

2. 「Windows PowerShell 5.1」のエイリアス:

3. 「PowerShell」のコマンドレット:

4. 管理者権限で「Windows PowerShell 5.1」を起動:

-

5. 「Windows PowerShell 7」について:

6. 「Windows11」に「PowerShell 7」をインストール:

7. 「PowerShell 7」のエイリアス:

8. 管理者権限で「PowerShell 7」を起動:

9. 「Windows11」にて、「PowerShell 7」をバージョンアップ:

10. 「PowerShell 7」のヘルプをダウンロード:

11. 「Windows11」の「PowerShell 7」で、シェルスクリプトを使う:

-

12. 「Linux」に「PowerShell 7」をインストール:

13. 「Linux」の「PowerShell 7」で、シェルスクリプトを使う:

-

14. 開発環境の「Windows PowerShell ISE」:

15. 「コマンドプロンプト」について:

16. 「Windows 11」の「システム要件」である「TPM」を「Windows PowerShell」で確認:

-

17. 「ls」(Get-ChildItem) コマンドのヘルプ:

-

「まとめ へ」

「目次詳細 へ」

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - -

「Windows11」(22H2) を起動:

-

立ち上げた「Windows11」の画面:

「Windows10」から「Windows11」にアップグレードしたので、デスクトップに以前使っていたアプリのアイコン(ショートカット)と「壁紙」が残っています。

-

Windows PowerShell 5.1」を起動:

→「Windows11」の標準のシェルです。

デスクトップの空きで右クリック →「ターミナルを開く」、
もしくは、パネルの「Windows」ボタンを右クリック→「ターミナル」で起動できます。

-

PowerShell 7.3.2」を起動 :

→追加でインストールしました。「Windows PowerShell 5.1」と共存できます。その機能強化版です。

他のOS にも提供しているクロスプラットホーム版だからか、アプリ名に「Windows」が付きません。

Windows」メニューや、タスクバーに置いた黒い「端末」アイコンで起動できます。

-

上記と同じ「ls」コマンドを実行していますが、カラー化されています。

ちなみに、「ls」はコマンドレットの「Get-ChildItem」のエイリアスです。Linux の「bash」のコマンドに似た機能のコマンドレットには、使いやすいようにエイリアス(gci、ls、dir)が準備されています。

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - --

1.「Windows PowerShell 5.1」について:

-

「Windows11」(22H2) の標準の「ターミナル」(シェル)として、プリインストールされています。

→すでに「PowerShell 7」に移行しており、「Windows PowerShell 5.1」は改修のみの対応です。

-

1).「Windows PowerShell 5.1」の起動:

-

(1). デスクトップの空きで右クリック→「ターミナルを開く」

-

(2). パネルの「Windows」ボタンを右クリック→「ターミナル」

-

2).「Windows PowerShell 5.1」の起動画面:

下記の紹介メッセージが表示されます:

PowerShell を最新にアップデート
https://aka.ms/PSWindows

→サイトでは「PowerShell 7」のインストールが推奨されています。

-

プロンプト表示:
PS C:\Users\user >

→「user」はユーザ名で、任意です。

-


3).「Windows PowerShell 5.1」の詳細:

-

(1). インストール場所:
$env:WINDIR\System32\WindowsPowerShell\v1.0

-

(2). 実行ファイル:
powershell.exe

-

(3). モジュールの格納場所:
PS C:\Users\user> $env:PSModulePath -split (';')
C:\Users\<user>\Documents\WindowsPowerShell\Modules
C:\Program Files\WindowsPowerShell\Modules
C:\WINDOWS\System32\WindowsPowerShell\v1.0\Modules

→コマンドの補完機能を使うと入力が楽です。

「$env:psm」Tab →「 $env:PSModulePath」Enter

$env:PSModulePath「スペース」「-sp」Tab→「 $env:PSModulePath -split」

-

(4). バージョンを確認:
PS C:\Users\user> $PSVersionTable
:
Name                           Value
----                           -----
PSVersion                      5.1.22621.963
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.22621.963
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

→コマンドの補完機能を使うと入力が楽です:

「$PSV」Tab →「$PSVersionTable」Enter

-

(5). バージョンを確認2:
PS C:\Users\user> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      22621  963

→コマンドの入力履歴、や 補完機能を使うと入力が楽です:

「↑」→「$PSVersionTable」

もしくは、

「$PSV」Tab →「$PSVersionTable」

$PSVersionTable「.psv」Tab →「$PSVersionTable.PSVersion」Enter

-

(6). バージョンを確認3:
PS C:\Users\user> Get-Host
:
Name             : ConsoleHost
Version          : 5.1.22621.963
InstanceId       : cba832d6-7ac0-426f-8371-5d75ca7efc6f
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : ja-JP
CurrentUICulture : ja-JP
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

→コマンドの補完機能を使うと入力が楽です。補完だけでなく、小文字で入力しても大文字にしてくれます:

「get-ho」Tab →「Get-Host」Enter

別に小文字の入力でもコマンドは有効ですが、見やすくしたり、記録として残すときは便利です。

-

(7).「.Net Framework」のバージョン確認:
PS C:\Users\user> Get-Item ‘HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full’
:
Name Property
—- ——–
Full CBS : 1
Install : 1
InstallPath : C:\Windows\Microsoft.NET\Framework64\v4.0.30319\
Release : 528040
Servicing : 0
TargetVersion : 4.0.0
Version : 4.8.03752

→コマンドの補完機能を使うと入力が楽です。補完だけでなく、小文字で入力しても大文字にしてくれます:

「get-it」Tab →「Get-Item」

-

(8).「Windows」のバージョンを確認1:
PS C:\Users\user> Get-WmiObject Win32_OperatingSystem
:
SystemDirectory : C:\WINDOWS\system32
Organization    :
BuildNumber     : 22621
RegisteredUser  :
SerialNumber    : xxxxx-xxxxx-xxxxx-xxOEM
Version         : 10.0.22621

→コマンドの補完機能を使うと入力が楽です。補完だけでなく、小文字で入力しても大文字にしてくれます:

「get-wm」Tab →「Get-WmiObject」

-

(9).「Windows」のバージョンを確認2:
PS C:\Users\user> cmd /c ver
:
Microsoft Windows [Version 10.0.22621.1265]

「cmd」はコマンドプロンプトのコマンドを実行する命令です。
「/c」を付けるとコマンド終了後に「PowerShell」に戻ります。

-


4).「Windows PowerShell 5.1」のエイリアスを表示:

PS C:\Users\user> Get-Alias
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           % -> ForEach-Object
Alias           ? -> Where-Object
Alias           ac -> Add-Content
Alias           asnp -> Add-PSSnapin
Alias           cat -> Get-Content
Alias           cd -> Set-Location
Alias           CFS -> ConvertFrom-String                          3.1.0.0    Microsoft.PowerShell.Utility
Alias           chdir -> Set-Location
Alias           clc -> Clear-Content
Alias           clear -> Clear-Host
Alias           clhy -> Clear-History
Alias           cli -> Clear-Item
Alias           clp -> Clear-ItemProperty
Alias           cls -> Clear-Host
Alias           clv -> Clear-Variable
Alias           cnsn -> Connect-PSSession
Alias           compare -> Compare-Object
Alias           copy -> Copy-Item
Alias           cp -> Copy-Item
Alias           cpi -> Copy-Item
Alias           cpp -> Copy-ItemProperty
Alias           curl -> Invoke-WebRequest
Alias           cvpa -> Convert-Path
Alias           dbp -> Disable-PSBreakpoint
Alias           del -> Remove-Item
Alias           diff -> Compare-Object
Alias           dir -> Get-ChildItem
Alias           dnsn -> Disconnect-PSSession
Alias           ebp -> Enable-PSBreakpoint
Alias           echo -> Write-Output
Alias           epal -> Export-Alias
Alias           epcsv -> Export-Csv
Alias           epsn -> Export-PSSession
Alias           erase -> Remove-Item
Alias           etsn -> Enter-PSSession
Alias           exsn -> Exit-PSSession
Alias           fc -> Format-Custom
Alias           fhx -> Format-Hex                                  3.1.0.0    Microsoft.PowerShell.Utility
Alias           fl -> Format-List
Alias           foreach -> ForEach-Object
Alias           ft -> Format-Table
Alias           fw -> Format-Wide
Alias           gal -> Get-Alias
Alias           gbp -> Get-PSBreakpoint
Alias           gc -> Get-Content
Alias           gci -> Get-ChildItem
Alias           gcm -> Get-Command
Alias           gcs -> Get-PSCallStack
Alias           gdr -> Get-PSDrive
Alias           ghy -> Get-History
Alias           gi -> Get-Item
Alias           gjb -> Get-Job
Alias           gl -> Get-Location
Alias           gm -> Get-Member
Alias           gmo -> Get-Module
Alias           gp -> Get-ItemProperty
Alias           gps -> Get-Process
Alias           gpv -> Get-ItemPropertyValue
Alias           group -> Group-Object
Alias           gsn -> Get-PSSession
Alias           gsnp -> Get-PSSnapin
Alias           gsv -> Get-Service
Alias           gu -> Get-Unique
Alias           gv -> Get-Variable
Alias           gwmi -> Get-WmiObject
Alias           h -> Get-History
Alias           history -> Get-History
Alias           icm -> Invoke-Command
Alias           iex -> Invoke-Expression
Alias           ihy -> Invoke-History
Alias           ii -> Invoke-Item
Alias           ipal -> Import-Alias
Alias           ipcsv -> Import-Csv
Alias           ipmo -> Import-Module
Alias           ipsn -> Import-PSSession
Alias           irm -> Invoke-RestMethod
Alias           ise -> powershell_ise.exe
Alias           iwmi -> Invoke-WMIMethod
Alias           iwr -> Invoke-WebRequest
Alias           kill -> Stop-Process
Alias           lp -> Out-Printer
Alias           ls -> Get-ChildItem
Alias           man -> help
Alias           md -> mkdir
Alias           measure -> Measure-Object
Alias           mi -> Move-Item
Alias           mount -> New-PSDrive
Alias           move -> Move-Item
Alias           mp -> Move-ItemProperty
Alias           mv -> Move-Item
Alias           nal -> New-Alias
Alias           ndr -> New-PSDrive
Alias           ni -> New-Item
Alias           nmo -> New-Module
Alias           npssc -> New-PSSessionConfigurationFile
Alias           nsn -> New-PSSession
Alias           nv -> New-Variable
Alias           ogv -> Out-GridView
Alias           oh -> Out-Host
Alias           popd -> Pop-Location
Alias           ps -> Get-Process
Alias           pushd -> Push-Location
Alias           pwd -> Get-Location
Alias           r -> Invoke-History
Alias           rbp -> Remove-PSBreakpoint
Alias           rcjb -> Receive-Job
Alias           rcsn -> Receive-PSSession
Alias           rd -> Remove-Item
Alias           rdr -> Remove-PSDrive
Alias           ren -> Rename-Item
Alias           ri -> Remove-Item
Alias           rjb -> Remove-Job
Alias           rm -> Remove-Item
Alias           rmdir -> Remove-Item
Alias           rmo -> Remove-Module
Alias           rni -> Rename-Item
Alias           rnp -> Rename-ItemProperty
Alias           rp -> Remove-ItemProperty
Alias           rsn -> Remove-PSSession
Alias           rsnp -> Remove-PSSnapin
Alias           rujb -> Resume-Job
Alias           rv -> Remove-Variable
Alias           rvpa -> Resolve-Path
Alias           rwmi -> Remove-WMIObject
Alias           sajb -> Start-Job
Alias           sal -> Set-Alias
Alias           saps -> Start-Process
Alias           sasv -> Start-Service
Alias           sbp -> Set-PSBreakpoint
Alias           sc -> Set-Content
Alias           select -> Select-Object
Alias           set -> Set-Variable
Alias           shcm -> Show-Command
Alias           si -> Set-Item
Alias           sl -> Set-Location
Alias           sleep -> Start-Sleep
Alias           sls -> Select-String
Alias           sort -> Sort-Object
Alias           sp -> Set-ItemProperty
Alias           spjb -> Stop-Job
Alias           spps -> Stop-Process
Alias           spsv -> Stop-Service
Alias           start -> Start-Process
Alias           sujb -> Suspend-Job
Alias           sv -> Set-Variable
Alias           swmi -> Set-WMIInstance
Alias           tee -> Tee-Object
Alias           trcm -> Trace-Command
Alias           type -> Get-Content
Alias           wget -> Invoke-WebRequest
Alias           where -> Where-Object
Alias           wjb -> Wait-Job
Alias           write -> Write-Output

→コマンドの補完機能を使うと入力が楽です。補完だけでなく、小文字で入力しても大文字にしてくれます:

「get-al」Tab →「Get-Alias」Enter

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ---

2. 管理者権限で「Windows PowerShell 5.1」を起動する場合:

-

管理者権限でないと使えない「コマンドレット」があります。

例えば、「Get-Tpm」コマンドレットは、「管理者権限」でないと実行できません。

-

参考:

PowerShellを管理者権限に昇格して実行

-


1). 管理者権限で「Windows PowerShell」を起動 1:

-

(1). 「Windows PowerShell」を起動:

デスクトップの空きで右クリック→「ターミナルを開く」

Windows PowerShell」が起動:

PS C:\Users\user\Desktop >

-

(2). 下記のコマンドを入力:
PS C:\Users\user\Desktop > Start-Process powershell -verb runas

→実行を許可 「はい」

-

(3). 別のウィンドウで管理者権限の「Windows PowerShell」が開きました:
PS C:\Windows\system32 >

→プロンプトが違うことに注目。

-


2). 管理者権限で「Windows PowerShell」を起動 2:

-

Windows メニューにある「PowerShell」を右クリック→「管理者として実行」:
PS C:\Windows\system32 >

→プロンプトが違うことに注目。

-


3). 「Windows11」の場合、「Windows」ボタンを右クリック →ターミナル(管理者):

Windows PowerShell」が起動:

PS C:\Users\user >

→プロンプトは変わりませんが、ウィンドウのタブが「管理者: Windows PowerShell」に変化

「デスクトップ」で開いていないので、プロンプトは、ユーザの「ホーム」を指しています。
ちなみに、「user」はユーザ名で、任意です。

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----

3. 「Windows 11」の「システム要件」である「TPM」を「Windows PowerShell」で確認してみる:

-

Windows 11」の「システム要件」のひとつに「TPM 2.0」があります。

アップグレードしたい PC の「TPM」のバージョンを「Windows PowerShell」を使って確認しました:

-

参考:

Windows 11で必須になった「TPM 2.0」って何?TPMの役割や確認方法を紹介

-

TPM (Trusted Platform Module) は、デバイス上でセキュリティ機能を提供するために、 暗号化で利用する「鍵」(証明書)を、金庫?とは別の安全な場所(TPM)で管理するための仕組みです。

TPM には、「1.2」と「2.0」のバージョンが存在します。

-


1). 「tpm.msc」コマンドによる GUI 表示で「TPM」を確認:

-

(1). 「Windows PowerShell」を起動して、「tpm.msc」を入力:
PS C:\Users\user > tpm.msc
(2). もしくは、Windows + R →「コマンドを指定して実行」で、「tpm.msc」を入力:
tpm.msc

-

→「TPM」が実装されているかが GUI で表示:
仕様バージョン: 1.2

-

2). 管理者権限で起動した「PowerShell」にて、「Get-Tpm」コマンドで「TPM」を確認:

PS C:\Windows\system32 > Get-Tpm

もしくは、

コマンドを小文字で:

PS C:\Windows\system32 > get-tpm

-

→「TPM」を含んだ一覧が表示され、その中には下記の文字が含まれていました:
TPM 1.2 ではサポートされていません

-


3). 注意:

Windows 11」の導入のときに、CPU 交換なども考えている場合で、 「BitLocker」などを使っていたら、あらかじめ解除してから CPU を交換しないと(CPU に TPM がある場合があるので)起動できなくなる可能性があります。

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - -----

4.「PowerShell」のコマンド(コマンドレット)について:

-

参考:

Linux(Bash)とWindows(PowerShell)のコマンド対応表

-

1).「PowerShell」の命令は、「コマンドレット」(Cmdlet) と呼ばれます:

-

2). コマンドレットは「動詞-名詞」という名前の付け方がしてあります:

→初めてでも意味がわかりやすいのが利点です。

例えば、「Get-Command」と入力するとコマンド一覧を取得できます。

-

3).「PowerShell」の「コマンドレット」は、「Uinux」コマンドと対応したエイリアスがあります:

MacOSLinux に慣れた人でも使いやすいようにしてあります。

-

4).「PowerShell」を使えば、Windows ユーザだけでなく、MacOSLinux のユーザでも利用できます

→使い方を工夫すれば、日々の業務をより効率的にできます。

-

5). すべて小文字にしても、コマンドは通ります:

-

6). 一部を大文字にすることで、短縮形のエイリアスがわかりやすくなっています:

「Get-Command」の短縮系は「gcm」です。

-

7). 主なコマンドレットにはエイリアスが定義されています:

Linux コマンド PowerShell コマンドレット 短縮形 機能
./ Start-Process プロセスの起動(アプリの起動)
alias Set-Alias sal エイリアスの作成
alias Get-Alias gal エイリアスの詳細の表示
cat Get-Content gc ファイルの内容を表示
cd Set-Location カレントディレクトリを変更
chmod icacls ファイル権限の変更
chown takeown ファイル所有者の変更
cp Copy-Item cpi ファイルやフォルダのコピー
date Get-Date 現在の日付を表示
df Get-PSDrive ストレージ容量の確認
dir Get-ChildItem gci ファイルの確認
echo Write-Output 標準出力に表示
grep Select-String sls ファイル内の文字列検索
history Get-History ghy 履歴
ls Get-ChildItem gci ファイルの確認
man Get-Help コマンドのマニュアルを表示
mkdir New-Item フォルダの作成
mv Move-Item ファイルの移動
ping Test-Connection ネットワークの疎通確認
ps Get-Process プロセスの表示
rm Remove-Item フォルダやファイルの削除
- Restart-Computer 「Windows11」の再起動
- Stop-Computer 「Windows11」の電源オフ
sleep Start-Sleep タイマー遅延
sort Sort-Object ソート
start Start-Process プロセスの起動(アプリの起動)
touch New-Item ni ファイル新規作成
uniq Get-Unique gu 重複している行を削除
wget Invoke-WebRequest URLからファイルのダウンロード
which Get-Command gcm コマンドの場所を表示
zip Compress-Archive 圧縮

→コマンドが長いので、「Tab」キーで補完して使うと良いです。

-

8). 便利なコマンドレット:

「Copy-Item -Path コピー元のパス -Destination コピー先のパス」:ファイルやフォルダを別のディレクトリにコピー

「Remove-Item -Path フォルダ -Recurse」:フォルダとその中にあるファイルをすべて削除

「Send-MailMessage」:メールを送信

-

9). エイリアスの情報を表示:

PS C:\Users\user> Get-Alias

-

10). コマンドレットでの、パラメータの与え方は、例えば「ls --help」ではなく、「ls -help」のように「-」がひとつです。

また、「ls -h」や「ls -?」も有効です。

-

11). Get-Help にて、「-Online」を付けると、ブラウザで、[コマンド] のヘルプを表示できます:

Get-Help [コマンド] -Online

-

例えば、

PS C:\Users\user> Get-Help Get-ChildItem -Online

ブラウザで表示:

-

12). それ以外に、「https://docs.microsoft.com/ja-jp/powershell/」を検索:

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----- -

5.「PowerShell 7」について:

-

1). 使用するにはインストールが必要です。

-

2).「PowerShell 7」は、「Windows PowerShell 5.1」と共存できます。

-

3). 「PowerShell 7」は、「Windows PowerShell 5.1」の後継で、機能が強化されています。

-

4). 「クロスプラットフォーム版」で、「Windows」だけでなく、「MacOS」や「Linux」にも提供されています。

→サポートされている「Linux ディストリビューション」は限られています。

-


5).「PowerShell 7」の詳細:

-

(1). インストール場所:
$env:ProgramFiles\PowerShell\7

-

(2). 実行ファイル:
pwsh.exe

-

(3). モジュールの格納場所:
PS C:\Users\user> $Env:PSModulePath -split (';')
C:\Users\user\Documents\PowerShell\Modules
C:\Program Files\PowerShell\Modules
c:\program files\powershell\7\Modules
C:\Program Files\WindowsPowerShell\Modules
C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules

PowerShell 7 では、モジュールが自動読み込みされるので、 Windows PowerShell のパスと PowerShell 7 のパスが含まれて表示されます。

-

(4). バージョン確認:
PS C:\Users\user> $PSVersionTable.PSVersion

Major  Minor  Patch  PreReleaseLabel BuildLabel
-----  -----  -----  --------------- ----------
7      3      2

→コマンドの補完機能を使うと入力が楽です。

「$PSV」Tab →「$PSVersionTable」

$PSVersionTable「.psv」Tab →「$PSVersionTable.PSVersion」Enter

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----- --

5-1.「Windows11」に「PowerShell 7」をインストール:

-

1). 「PowerShell 7」は、「Windows PowerShell 5.1」の機能強化版です。

-

2). 「Windows PowerShell 5.1」と「PowerShell 7」は共存できます。

-

3).「Windows PowerShell 5.1」の起動時に、最新の「PowerShell 7」のオススメ表示があります:

Windows PowerShell 5.1」の起動時:

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

新機能と改善のために最新の PowerShell をインストールしてください! https://aka.ms/PSWindows

PS C:\Users\user>

紹介のサイト「https://aka.ms/PSWindows」を開くと:

→「Windows PowerShell 5.1 から PowerShell 7 への移行 」のドキュメントが開きました:

-

4). 「PowerShell 7」のインストールのやり方は 3つ:

-

(1). 「winget」(Windows のパッケージ管理ツール)を使ってのインストール(推奨)

→「winget」は「Windows」のパッケージ管理ツールです。

-

(2). MSI パッケージを使用して PowerShell を展開する

MSI パッケージの展開は、「管理者権限」が必要です。

-

(3). ZIP パッケージを使用して PowerShell を展開する

→ZIP パッケージの展開は、「任意のユーザ」が展開できます。

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----- ---

5-2.「Windows11」にて、winget で「PowerShell 7」をインストール:

-

「winget」は「Windows」のパッケージ管理ツールです。

-

「winget」は、Windows クライアントに PowerShell をインストールする場合に推奨される方法 です。

-


1). winget で「Powershell」を検索:

Windows」ボタンを右クリック→「ターミナル」→「Windows PowerShell」が起動:

-

PS C:\Users\user> winget search Microsoft.PowerShell
'msstore' ソースでは、使用する前に次の契約を表示する必要があります。
Terms of Transaction: https://aka.ms/microsoft-store-terms-of-transaction
ソースが正常に機能するには、現在のマシンの 2 文字の地理的リージョンをバックエンド サービスに送信する必要があります (例: "US")。

すべてのソース契約条件に同意しますか?
[Y] はい  [N] いいえ:

→「Y」

名前       ID                           バージョン ソース
----------------------------------------------------------
PowerShell Microsoft.PowerShell         7.3.2.0    winget
PowerShell Microsoft.PowerShell.Preview 7.4.1.0    winget

-


2). winget でインストール:

winget によって Microsoft Store (MSIX) パッケージがインストールされます。

Windows の [スタート] メニューにショートカットが作成されます。

パッケージは、既定で $env:ProgramFiles\PowerShell\<version> にインストールされます。
PowerShell は、スタート メニューまたは $env:ProgramFiles\PowerShell\<version>\pwsh.exe から起動できます。

-


3). winget で「Powershell 7」の安定版をインストール:

PS C:\Users\user> winget install --id Microsoft.Powershell --source winget
見つかりました PowerShell [Microsoft.PowerShell] バージョン 7.3.2.0
このアプリケーションは所有者からライセンス供与されます。
Microsoft はサードパーティのパッケージに対して責任を負わず、ライセンスも付与しません。
ダウンロード中 https://github.com/PowerShell/PowerShell/releases/download/v7.3.2/PowerShell-7.3.2-win-x64.msi
  ██████████████████████████████   100 MB /  100 MB
インストーラーハッシュが正常に検証されました
パッケージのインストールを開始しています...
インストールが完了しました

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----- ----

5-3. 管理者権限で、「PowerShell 7」を起動:

-

1). 管理者権限で「Windows PowerShell 5.1」を起動:

Windows」ボタンを右クリック→「ターミナル(管理者)」→「Windows PowerShell」が起動:

PS C:\Users\user> 

→プロンプトは変わりませんが、ウィンドウのタブが「管理者:Windows PowerShell」の表示です。

-

2). 「PowerShell 7」を起動:

PS C:\Users\user> pwsh
:
PowerShell 7.3.2

→プロンプトは変わりませんが、ウィンドウのタブが「Admministrator: 管理者:Windows PowerShell」の表示に変わりました。

-

3). 現在のバージョンを確認:

PS C:\Users\user> pwsh -version
PowerShell 7.3.2

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----- -----

5-4.「Windows11」にて、「PowerShell 7」をバージョンアップ:

-

1). 「PowerShell 7」を起動したところ、新しいバージョンがあるとの通知がありました:

PS C:\Users\user> pwsh
:
PowerShell 7.3.2

   A new PowerShell stable release is available: v7.3.3
   Upgrade now, or check out the release page at:
     https://aka.ms/PowerShell-Release?tag=v7.3.3

→プロンプトは変わりませんが、ウィンドウのタブが「Admministrator: 管理者:Windows PowerShell」の表示に変わりました。

-

2). winget で「Powershell」を検索:

PS C:\Users\user> winget search Microsoft.PowerShell
名前       ID                           バージョン ソース
----------------------------------------------------------
PowerShell Microsoft.PowerShell         7.3.3.0    winget
PowerShell Microsoft.PowerShell.Preview 7.4.1.0    winget

→新しいバージョンがリリースされました。

-

3). winget で「Powershell 7」の新しい安定版をインストール:

PS C:\Users\user> winget install --id Microsoft.Powershell --source winget
既存のパッケージが既にインストールされています。インストールされているパッケージ...をアップグレードしようとしています
見つかりました PowerShell [Microsoft.PowerShell] バージョン 7.3.3.0
このアプリケーションは所有者からライセンス供与されます。
Microsoft はサードパーティのパッケージに対して責任を負わず、ライセンスも付与しません。
ダウンロード中 https://github.com/PowerShell/PowerShell/releases/download/v7.3.3/PowerShell-7.3.3-win-x64.msi
  ██████████████████████████████   101 MB /  101 MB
インストーラーハッシュが正常に検証されました
パッケージのインストールを開始しています...

PS C:\Users\user>

GUI の「Windows インストーラ」(MSI) が起動して、完了しました。

-

4). バージョンの確認:

PS C:\Users\user> pwsh -version
PowerShell 7.3.3

-

5). 使ってみる:

PS C:\Users\user> Get-Alias
Get-Alias: The 'Get-Alias' command was found in the module 'Microsoft.PowerShell.Utility', but the module could not be loaded due to the following error: [Could not load file or assembly 'System.Management.Automation, Version=7.3.3.500, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. 指定されたファイルが見つかりません。]
For more information, run 'Import-Module Microsoft.PowerShell.Utility'.

→モジュールが見つからないみたい。

-

6). モジュールの格納場所を確認:

PS C:\Users\user> $Env:PSModulePath -split (';')
:
C:\Users\user\Documents\PowerShell\Modules
C:\Program Files\PowerShell\Modules
c:\program files\powershell\7\Modules
C:\Users\user\Documents\WindowsPowerShell\Modules
C:\Program Files\WindowsPowerShell\Modules
C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules

-

PS C:\Users\user> ls 'c:\program files\powershell\7\Modules'
    Directory: C:\Program Files\PowerShell\7\Modules

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----       2023/03/05 日     6:33                CimCmdlets
d----       2023/03/05 日     6:33                Microsoft.PowerShell.Archive
d----       2023/03/05 日     6:33                Microsoft.PowerShell.Diagnostics
d----       2023/03/05 日     6:33                Microsoft.PowerShell.Host
d----       2023/03/05 日     6:33                Microsoft.PowerShell.Management
d----       2023/03/05 日     6:33                Microsoft.PowerShell.Security
d----       2023/03/05 日     6:32                Microsoft.PowerShell.Utility
d----       2023/03/05 日     6:33                Microsoft.WSMan.Management
d----       2023/03/05 日     6:33                PackageManagement
d----       2023/03/05 日     6:33                PowerShellGet
d----       2023/03/05 日     6:33                PSDiagnostics
d----       2023/03/05 日     6:33                PSReadLine
d----       2023/03/05 日     6:32                ThreadJob

-

PS C:\Users\user> ls 'c:\program files\powershell\7\Modules\Microsoft.PowerShell.Utility'
    Directory: C:\Program Files\PowerShell\7\Modules\Microsoft.PowerShell.Utility

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---       2023/02/18 土    21:53          16941 Microsoft.PowerShell.Utility.psd1

→モジュールの格納場所に「Microsoft.PowerShell.Utility」はありました。

-

インストール後は、モジュールが認識されないので、再起動が必要みたい。

-

7). ウィンドウを閉じました:

-

8). 再び、管理者権限で「Windows PowerShell」を起動:

Windows」ボタンを右クリック→「ターミナル(管理者)」→「Windows PowerShell」が起動:

-

9). 「PowerShell 7」を起動:

PS C:\Users\user> pwsh
:
PowerShell 7.3.3

-

10). 再度、使ってみる:「PowerShell 7」のエイリアスを表示:

PS C:\Users\user> Get-Alias
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           ? -> Where-Object
Alias           % -> ForEach-Object
Alias           ac -> Add-Content
Alias           cat -> Get-Content
Alias           cd -> Set-Location
Alias           chdir -> Set-Location
Alias           clc -> Clear-Content
Alias           clear -> Clear-Host
Alias           clhy -> Clear-History
Alias           cli -> Clear-Item
Alias           clp -> Clear-ItemProperty
Alias           cls -> Clear-Host
Alias           clv -> Clear-Variable
Alias           cnsn -> Connect-PSSession
Alias           compare -> Compare-Object
Alias           copy -> Copy-Item
Alias           cp -> Copy-Item
Alias           cpi -> Copy-Item
Alias           cpp -> Copy-ItemProperty
Alias           cvpa -> Convert-Path
Alias           dbp -> Disable-PSBreakpoint
Alias           del -> Remove-Item
Alias           diff -> Compare-Object
Alias           dir -> Get-ChildItem
Alias           dnsn -> Disconnect-PSSession
Alias           ebp -> Enable-PSBreakpoint
Alias           echo -> Write-Output
Alias           epal -> Export-Alias
Alias           epcsv -> Export-Csv
Alias           erase -> Remove-Item
Alias           etsn -> Enter-PSSession
Alias           exsn -> Exit-PSSession
Alias           fc -> Format-Custom
Alias           fhx -> Format-Hex                                  7.0.0.0    Microsoft.PowerShell.Utility
Alias           fl -> Format-List
Alias           foreach -> ForEach-Object
Alias           ft -> Format-Table
Alias           fw -> Format-Wide
Alias           gal -> Get-Alias
Alias           gbp -> Get-PSBreakpoint
Alias           gc -> Get-Content
Alias           gcb -> Get-Clipboard                               7.0.0.0    Microsoft.PowerShell.Management
Alias           gci -> Get-ChildItem
Alias           gcm -> Get-Command
Alias           gcs -> Get-PSCallStack
Alias           gdr -> Get-PSDrive
Alias           gerr -> Get-Error
Alias           ghy -> Get-History
Alias           gi -> Get-Item
Alias           gin -> Get-ComputerInfo                            7.0.0.0    Microsoft.PowerShell.Management
Alias           gjb -> Get-Job
Alias           gl -> Get-Location
Alias           gm -> Get-Member
Alias           gmo -> Get-Module
Alias           gp -> Get-ItemProperty
Alias           gps -> Get-Process
Alias           gpv -> Get-ItemPropertyValue
Alias           group -> Group-Object
Alias           gsn -> Get-PSSession
Alias           gsv -> Get-Service
Alias           gtz -> Get-TimeZone                                7.0.0.0    Microsoft.PowerShell.Management
Alias           gu -> Get-Unique
Alias           gv -> Get-Variable
Alias           h -> Get-History
Alias           history -> Get-History
Alias           icm -> Invoke-Command
Alias           iex -> Invoke-Expression
Alias           ihy -> Invoke-History
Alias           ii -> Invoke-Item
Alias           ipal -> Import-Alias
Alias           ipcsv -> Import-Csv
Alias           ipmo -> Import-Module
Alias           irm -> Invoke-RestMethod
Alias           iwr -> Invoke-WebRequest
Alias           kill -> Stop-Process
Alias           ls -> Get-ChildItem
Alias           man -> help
Alias           md -> mkdir
Alias           measure -> Measure-Object
Alias           mi -> Move-Item
Alias           mount -> New-PSDrive
Alias           move -> Move-Item
Alias           mp -> Move-ItemProperty
Alias           mv -> Move-Item
Alias           nal -> New-Alias
Alias           ndr -> New-PSDrive
Alias           ni -> New-Item
Alias           nmo -> New-Module
Alias           nsn -> New-PSSession
Alias           nv -> New-Variable
Alias           ogv -> Out-GridView
Alias           oh -> Out-Host
Alias           popd -> Pop-Location
Alias           ps -> Get-Process
Alias           pushd -> Push-Location
Alias           pwd -> Get-Location
Alias           r -> Invoke-History
Alias           rbp -> Remove-PSBreakpoint
Alias           rcjb -> Receive-Job
Alias           rcsn -> Receive-PSSession
Alias           rd -> Remove-Item
Alias           rdr -> Remove-PSDrive
Alias           ren -> Rename-Item
Alias           ri -> Remove-Item
Alias           rjb -> Remove-Job
Alias           rm -> Remove-Item
Alias           rmdir -> Remove-Item
Alias           rmo -> Remove-Module
Alias           rni -> Rename-Item
Alias           rnp -> Rename-ItemProperty
Alias           rp -> Remove-ItemProperty
Alias           rsn -> Remove-PSSession
Alias           rv -> Remove-Variable
Alias           rvpa -> Resolve-Path
Alias           sajb -> Start-Job
Alias           sal -> Set-Alias
Alias           saps -> Start-Process
Alias           sasv -> Start-Service
Alias           sbp -> Set-PSBreakpoint
Alias           scb -> Set-Clipboard                               7.0.0.0    Microsoft.PowerShell.Management
Alias           select -> Select-Object
Alias           set -> Set-Variable
Alias           shcm -> Show-Command
Alias           si -> Set-Item
Alias           sl -> Set-Location
Alias           sleep -> Start-Sleep
Alias           sls -> Select-String
Alias           sort -> Sort-Object
Alias           sp -> Set-ItemProperty
Alias           spjb -> Stop-Job
Alias           spps -> Stop-Process
Alias           spsv -> Stop-Service
Alias           start -> Start-Process
Alias           stz -> Set-TimeZone                                7.0.0.0    Microsoft.PowerShell.Management
Alias           sv -> Set-Variable
Alias           tee -> Tee-Object
Alias           type -> Get-Content
Alias           where -> Where-Object
Alias           wjb -> Wait-Job
Alias           write -> Write-Output

→動作しました。

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----- ----- -

5-5.「PowerShell 7」のヘルプをダウンロード:

-

1). ヘルプを使ってみる:

PS C:\Users\user> ls -?

もしくは、

PS C:\Users\user> Get-Help Get-ChildItem
NAME
    Get-ChildItem

SYNTAX
    Get-ChildItem [[-Path] <string[]>] [[-Filter] <string>] [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-De
    pth <uint>] [-Force] [-Name] [-Attributes {ReadOnly | Hidden | System | Directory | Archive | Device | Normal | Tem
    porary | SparseFile | ReparsePoint | Compressed | Offline | NotContentIndexed | Encrypted | IntegrityStream | NoScr
    ubData}] [-FollowSymlink] [-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [<CommonParameters>]

    Get-ChildItem [[-Filter] <string>] -LiteralPath <string[]> [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [
    -Depth <uint>] [-Force] [-Name] [-Attributes {ReadOnly | Hidden | System | Directory | Archive | Device | Normal |
    Temporary | SparseFile | ReparsePoint | Compressed | Offline | NotContentIndexed | Encrypted | IntegrityStream | No
    ScrubData}] [-FollowSymlink] [-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [<CommonParameters>]


ALIASES
    gci
    ls
    dir


REMARKS
    Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
        -- To download and install Help files for the module that includes this cmdlet, use Update-Help.
        -- To view the Help topic for this cmdlet online, type: "Get-Help Get-ChildItem -Online" or
           go to https://go.microsoft.com/fwlink/?LinkID=2096492.

→最後のメッセージが気になります。

和訳:

備考
「Get-Help」は、このコンピュータでこのコマンドレットの「ヘルプ ファイル」を見つけることができません。
部分的なヘルプのみを表示しています。
-- このコマンドレットを含むモジュールの「ヘルプ ファイルをダウンロードしてインストールする」には「Update-Help」を使用します。
-- このコマンドレットのヘルプ トピックを「オンラインで表示する」には、「Get-Help Get-ChildItem -Online」と入力するか、
「https://go.microsoft.com/fwlink/?LinkID=2096492」に移動します。

-

2). 「Save-Help」の使い方を確認:

PS C:\Users\user> Save-Help -?
:
NAME
    Save-Help

SYNTAX
    Save-Help [-DestinationPath] <string[]> [[-Module] <psmoduleinfo[]>] [[-UICulture] <cultureinfo[]>] [-FullyQualifie
    dModule <ModuleSpecification[]>] [-Credential <pscredential>] [-UseDefaultCredentials] [-Force] [-Scope {CurrentUse
    r | AllUsers}] [<CommonParameters>]

    Save-Help [[-Module] <psmoduleinfo[]>] [[-UICulture] <cultureinfo[]>] -LiteralPath <string[]> [-FullyQualifiedModul
    e <ModuleSpecification[]>] [-Credential <pscredential>] [-UseDefaultCredentials] [-Force] [-Scope {CurrentUser | Al
    lUsers}] [<CommonParameters>]


ALIASES
    None


REMARKS
    Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
        -- To download and install Help files for the module that includes this cmdlet, use Update-Help.
        -- To view the Help topic for this cmdlet online, type: "Get-Help Save-Help -Online" or
           go to https://go.microsoft.com/fwlink/?LinkID=2096794.

→コマンドの説明がなく、コマンドの入力形式しか表示されません。有益なのは、最後の行のURL

-

ブラウザでURLを確認:

抜粋:

「Save-Help」コマンドレットは、PowerShell モジュールの最新のヘルプ ファイルをダウンロードし、指定したディレクトリに保存します。

例えば、ネットワーク環境が整っているPC でダウンロードしておき、ネットワークに接続できないPC に「Update-Help」コマンドレットでインストールできます。

-

保存したヘルプ ファイルをインストールするには、 「Update-Help」コマンドレットを実行します 。 「-SourcePath」パラメータで「ヘルプ ファイルを保存したフォルダ」を指定します。

-

参考: 操作例(管理者権限の PowerShell で実行。動作は未確認)
フォルダ作成:
New-Item -ItemType Directory "C:\SavedHelp"

保存:
Save-Help -UICulture en-US, ja-JP -DestinationPath "C:\SavedHelp"

インストール:
Update-Help -SourcePath "C:\SavedHelp"

-

3). 「Update-Help」の使い方を確認:

PS C:\Users\user> Update-Help -?
:
NAME
    Update-Help

SYNTAX
    Update-Help [[-Module] <string[]>] [[-SourcePath] <string[]>] [[-UICulture] <cultureinfo[]>] [-FullyQualifiedModule
     <ModuleSpecification[]>] [-Recurse] [-Credential <pscredential>] [-UseDefaultCredentials] [-Force] [-Scope {Curren
    tUser | AllUsers}] [-WhatIf] [-Confirm] [<CommonParameters>]

    Update-Help [[-Module] <string[]>] [[-UICulture] <cultureinfo[]>] [-FullyQualifiedModule <ModuleSpecification[]>] [
    -LiteralPath <string[]>] [-Recurse] [-Credential <pscredential>] [-UseDefaultCredentials] [-Force] [-Scope {Current
    User | AllUsers}] [-WhatIf] [-Confirm] [<CommonParameters>]


ALIASES
    None


REMARKS
    Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
        -- To download and install Help files for the module that includes this cmdlet, use Update-Help.
        -- To view the Help topic for this cmdlet online, type: "Get-Help Update-Help -Online" or
           go to https://go.microsoft.com/fwlink/?LinkID=2096805.

→コマンドの説明がなく、コマンドの入力形式しか表示されません。有益なのは、最後の行のURL

-

ブラウザでURLを確認:

抜粋:

PowerShell ヘルプ トピックのローカル コピーは、コマンドの最初のヘルプが要求されたときに、 「Update-Help」の実行に「Y」と応答すると、自動で「Update-Help」コマンドレットによって更新されます。

ヘルプ コンテンツは不定期で更新されるため、 定期的に、管理者として昇格された PowerShell で「Update-Help」コマンドレットを実行して、 ヘルプ トピックの更新を行うのがオススメです。

-

4). ヘルプファイルの更新:

PS C:\Users\user> Update-Help

→いくつかのモジュールのダウンロードが進んで、下記が表示されて終了しました。

Update-Help: Failed to update Help for the module(s) 'ConfigDefenderPerformance, DefenderPerformance, Dism, Get-NetView, Kds, NetQos, PcsvDevice, Pester, PKI, Whea, WindowsUpdate' with UI culture(s) {ja-JP} : One or more errors occurred. (Response status code does not indicate success: 404 (The specified blob does not exist.).).
English-US help content is available and can be installed using: Update-Help -UICulture en-US.

→ヘルプの更新に対応していないモジュールもあるらしく、 何個かが失敗するのはよくあることみたい。

-

5). ヘルプを使ってみる:

PS C:\Users\user> ls -?

もしくは、

PS C:\Users\user> Get-Help Get-ChildItem
NAME
    Get-ChildItem

SYNOPSIS
    Gets the items and child items in one or more specified locations.


SYNTAX
    Get-ChildItem [[-Filter] <System.String>] [-Attributes {Archive | Compressed | Device | Directory | Encrypted | Hid
    den | IntegrityStream | Normal | NoScrubData | NotContentIndexed | Offline | ReadOnly | ReparsePoint | SparseFile |
     System | Temporary}] [-CodeSigningCert] [-Depth <System.UInt32>] [-Directory] [-DnsName <Microsoft.PowerShell.Comm
    ands.DnsNameRepresentation>] [-DocumentEncryptionCert] [-Eku <System.String>] [-Exclude <System.String[]>] [-Expiri
    ngInDays <System.Int32>] [-File] [-FollowSymlink] [-Force] [-Hidden] [-Include <System.String[]>] -LiteralPath <Sys
    tem.String[]> [-Name] [-ReadOnly] [-Recurse] [-SSLServerAuthentication] [-System] [<CommonParameters>]

    Get-ChildItem [[-Path] <System.String[]>] [[-Filter] <System.String>] [-Attributes {Archive | Compressed | Device |
     Directory | Encrypted | Hidden | IntegrityStream | Normal | NoScrubData | NotContentIndexed | Offline | ReadOnly |
     ReparsePoint | SparseFile | System | Temporary}] [-CodeSigningCert] [-Depth <System.UInt32>] [-Directory] [-DnsNam
    e <Microsoft.PowerShell.Commands.DnsNameRepresentation>] [-DocumentEncryptionCert] [-Eku <System.String>] [-Exclude
     <System.String[]>] [-ExpiringInDays <System.Int32>] [-File] [-FollowSymlink] [-Force] [-Hidden] [-Include <System.
    String[]>] [-Name] [-ReadOnly] [-Recurse] [-SSLServerAuthentication] [-System] [<CommonParameters>]


DESCRIPTION
    The `Get-ChildItem` cmdlet gets the items in one or more specified locations. If the item is a container, it gets t
    he items inside the container, known as child items. You can use the Recurse parameter to get items in all child co
    ntainers and use the Depth parameter to limit the number of levels to recurse.

    `Get-ChildItem` doesn't display empty directories. When a `Get-ChildItem` command includes the Depth or Recurse par
    ameters, empty directories aren't included in the output.

    Locations are exposed to `Get-ChildItem` by PowerShell providers. A location can be a file system directory, regist
    ry hive, or a certificate store. Some parameters are only available for a specific provider. For more information,
    see about_Providers (../Microsoft.PowerShell.Core/About/about_Providers.md).


RELATED LINKS
    Online Version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-childitem?view=po
    wershell-7.3&WT.mc_id=ps-gethelp
    about_Certificate_Provider
    about_Providers
    about_Quoting_Rules
    about_Registry_Provider
    ForEach-Object
    Get-Alias
    Get-Item
    Get-Location
    Get-Process
    Get-PSProvider
    Split-Path

REMARKS
    To see the examples, type: "Get-Help Get-ChildItem -Examples"
    For more information, type: "Get-Help Get-ChildItem -Detailed"
    For technical information, type: "Get-Help Get-ChildItem -Full"
    For online help, type: "Get-Help Get-ChildItem -Online"

→ヘルプが更新されました。

-

6).「PowerShell 7」の終了:

PS C:\Users\user> exit

→プロンプトは変わりませんが、ウィンドウのタブが「管理者:Windows PowerShell」の表示に変わりました。

Windows PowerShell」に戻りました。

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----- ----- --

5-6.「Windows」の「PowerShell」で、シェルスクリプトを使う場合:

-

1). 「PowerShell」のバッチファイル(シェルスクリプト)には、「.bat」ではなく、「.ps1」の拡張子が使われます。

-

2). 「Windows」での、シェルスクリプトの例:

-

(1). 作成:

「Notepad++」エディタを起動し、新規ファイルを作成:

↓ 貼付け:

$string = “Hello World!”
Write-Host $string

→「Write-Host」は、「echo」に該当するコマンドレットです。

-

ファイル →名前を付けて保存

「デスクトップ」フォルダに「test.ps1」のファイル名で保存

-

つまり、下記のファイルが作成できました:

C:\Users\user\Desktop\test.ps1
(2). 実行:

「.ps1」ファイル(バッチファイル、シェルスクリプト)を読み込んで実行させる場合は、「-f」オプションを使います:

PS C:\Users\user> pwsh -f Desktop\test.ps1
:
Hello World!

-

3). シェルスクリプト中に記述する場合:

例:

pwsh -NoProfile -ExecutionPolicy Unrestricted C:\Users\user\Desktop\test.ps1

→ファイルは絶対パスで指定します。

スクリプトを実行できるようにポリシーを変更しています。
「-ExecutionPolicy Unrestricted」(無制限)

-

(1). 作成:

「Notepad++」エディタを起動し、新規ファイルを作成:

↓ 貼付け:

pwsh -NoProfile -ExecutionPolicy Unrestricted C:\Users\user\Desktop\test.ps1

-

ファイル →名前を付けて保存

「デスクトップ」フォルダに「test2.ps1」のファイル名で保存

-

つまり、下記のファイルが作成できました:

C:\Users\user\Desktop\test2.ps1
(2). 実行:
PS C:\Users\user> pwsh -f Desktop\test2.ps1
:
Hello World!

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----- ----- ---

6. 参考: 開発環境の「Windows PowerShell ISE」について:

-

「ISE」は、「Integrated Scripting Environment」の略で、「統合スクリプト環境」の、開発用のデバッグ環境です。

-

参考:

Windows PowerShell ISE

開発環境 ISE を使用する

-

1). 「ISE」は、「Windows PowerShell V5.1」までのバージョンで使えます:

→「Windows」のみで使える開発環境です。

-

2). マルチプラットフォーム版の「PowerShell 7」ではサポートされていません:

-

3). 「PowerShell 7」では、「Visual Studio Code」と、「PowerShell 拡張機能 」が使われています

(ひとつの選択肢)

-


4). 操作:

-

(1). 起動:

3つのやり方:

-

(2). 起動された画面:

左側の青部分が「PowerShell」のターミナル画面です。
右側が「コマンドレット」のヘルプが表示。
スクリプトの作成では、左上に編集画面が開きます。

-

(3). 「Windows PowerShell」を使って、最初に不便に感じたこと:

Windows PowerShell」の画面では、コマンドを貼り付けたいとき、右クリックで、コピーや貼り付けのメニューが表示されません。(ちなみに、トラックパッドの右クリックだと、貼り付けの機能が働きます)

「ISE」の画面では、右クリックすると、コピーや貼り付けのメニューが表示されました。

Windows PowerShell」にて、CUI で使えるエディタは無いようです。「ISE」を使うと、外部のエディタからの貼り付けがしやすくなります。

-

(4). その他の操作の補足:

-

複数行の編集:

[コマンド] ペインで現在の行の下に空白行を挿入するには、Shift+Enter キーを押します。

-

選択して実行:

スクリプトの一部を実行するには、実行するテキストを選択して、
[スクリプトの実行] ボタンをクリックするか、F5 キーを押します。

-

状況依存ヘルプ:

Invoke-Item」と入力してから、F1 キーを押します。
ヘルプ ファイルが開き、「Invoke-Item」コマンドレットの記事が表示されます。

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----- ----- ----

7. 「コマンドプロンプト」の画面について:

-

Windows PowerShell」が使われる前から、「Windows」に存在していた、CUI のターミナル環境です。

コマンドは、MS-DOS のコマンドに近く、以前に使っていたバッチファイルが実行できるかも。ただし、それに必要なコマンドがインストールされているかはわかりません。

-

1). 起動:

-

2). 使用例:

C:\Users\user > dir /?

→「dir」コマンド(ls の機能)のヘルプが表示されます。

-

3). 「PowerShell 7」をインストールすると、「Windows ターミナル」で表示され、使い勝手が良くなります:

-

(1). 「コマンドプロンプト」を起動した時、デフォルトでは単なる ターミナル画面です。

-

(2). 「PowerShell 7」をインストールすると、「PowerShell」で使われる、タブ付きの画面に変化します。

-

(3). 最初の「タブ」で「コマンドプロンプト」は表示されており、タブの「+」をクリックすると、新しい「タブ」で「Windows PowerShell 5.1」が開きます。

-

(4). ショートカットキーのガイドを表示:

ターミナルの「タイトルバー」で右クリック →「設定」→「設定」タブが開きます:

左の「操作」をクリック →ショートカットキーの説明を表示

-

(5). ショートカットキーでタブの切り替えができます:

Ctrl + Alt + 1: 「コマンドプロンプト

-

Ctrl + Alt + 2: 「Windows PowerShell 5.1」

-

Ctrl + Alt + 3: 「Windows PowerShell 5.1」

-

(6). 「Windows ターミナル」では、Ctrl+C と、Ctrl + V が使え、便利です。

範囲指定してから、Ctrl+C とすると、Ctrl + V で貼り付けできます。

-

4). 「Windows ターミナル」の「設定」タブにて、各シェルが定義されていました:

→ちなみに、「%SystemRoot%」は通常「C:\Windows」です。

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----- ----- -----

8. Linux (Ubuntu) に「PowerShell 7」をインストール:

-

参考:

Ubuntu への PowerShell のインストール

-

Ubuntu 22.04 の場合のパッケージ:

https://packages.microsoft.com/config/ubuntu/22.04/packages-microsoft-prod.deb

→ダウンロードは下記の手順の「項番 (3).」で行っています。

-

1). インストール:

-

(1). パッケージのリストを更新:
$ sudo apt update

-

(2). 前提条件のパッケージをインストール:
$ sudo apt install -y wget apt-transport-https software-properties-common

-

(3). Microsoft リポジトリの GPG キーをダウンロード:
$ wget -q "https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb"

-

参考:

$ lsb_release -rs
22.04

-

(4). Microsoft リポジトリの GPG キーを登録:
$ sudo dpkg -i packages-microsoft-prod.deb
(5). packages.microsoft.com を追加した後、パッケージの一覧を更新:
$ sudo apt update

-

(6). 「PowerShell」のインストール:
$ sudo apt install -y powershell

-

2). 「PowerShell」の起動:

パッケージがインストールされたら、ターミナルから「pwsh」を実行:

$ pwsh

-

3). 「PowerShell」を更新する場合:

$ sudo apt install powershell

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----- ----- ----- -

8-1.「Linux」の「PowerShell」で、シェルスクリプトを使う場合:

-

1).「PowerShell」にシェルを変更するときは、「pwsh」コマンドを使います:

$ su -
# pwsh
:
PowerShell 7.2.0
Copyright (c) Microsoft Corporation.

https://aka.ms/powershell
Type 'help' to get help.

PS /root> 

-

バージョンの確認:

PS /root> $PSVersionTable
:
Name                           Value
----                           -----
PSVersion                      7.2.0
PSEdition                      Core
GitCommitId                    7.2.0
OS                             Linux 3.10.0-957.48.1.el7.x86_64 #1 SMP Fri Mar 6 14:14:26 EST 2020
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

→「7.2」です。

-

2). シェルを変更せず、直接コマンドを実行するときは、「-c」オプションを使います:

日時の表示:

# pwsh -c "Get-Date"
2021年11月21日日曜日 15:29:19

-

3). 「.ps1」ファイル(バッチファイル、シェルスクリプト)を読み込んで実行させる場合は、「-f」オプションを使います:

「.ps1」ファイルの確認:

# cat test.ps1
Get-Date

-

「.ps1」ファイルの実行:

# pwsh -f test.ps1
:
2021年11月21日日曜日 15:31:37

-

-


- --- - --- - --- - --- - --- - --- - --- - --- - ----- ----- ----- --

9. 追記:「ls」(Get-ChildItem) コマンドのヘルプ:

-

1).「ls」コマンドのヘルプ表示:

PS C:\Users\user> ls -?

もしくは、

PS C:\Users\user> get-help Get-ChildItem

-

名前
    Get-ChildItem

概要
    Gets the items and child items in one or more specified locations.


構文
    Get-ChildItem [[-Filter] <System.String>] [-Attributes {Archive | Compressed | Device | Directory | Encrypted | Hid
    den | IntegrityStream | Normal | NoScrubData | NotContentIndexed | Offline | ReadOnly | ReparsePoint | SparseFile |
     System | Temporary}] [-Depth <System.UInt32>] [-Directory] [-Exclude <System.String[]>] [-File] [-Force] [-Hidden]
     [-Include <System.String[]>] -LiteralPath <System.String[]> [-Name] [-ReadOnly] [-Recurse] [-System] [-UseTransact
    ion] [<CommonParameters>]

    Get-ChildItem [[-Path] <System.String[]>] [[-Filter] <System.String>] [-Attributes {Archive | Compressed | Device |
     Directory | Encrypted | Hidden | IntegrityStream | Normal | NoScrubData | NotContentIndexed | Offline | ReadOnly |
     ReparsePoint | SparseFile | System | Temporary}] [-Depth <System.UInt32>] [-Directory] [-Exclude <System.String[]>
    ] [-File] [-Force] [-Hidden] [-Include <System.String[]>] [-Name] [-ReadOnly] [-Recurse] [-System] [-UseTransaction
    ] [<CommonParameters>]


説明
    The `Get-ChildItem` cmdlet gets the items in one or more specified locations. If the item is a container, it gets t
    he items inside the container, known as child items. You can use the Recurse parameter to get items in all child co
    ntainers and use the Depth parameter to limit the number of levels to recurse.

    `Get-ChildItem` doesn't display empty directories. When a `Get-ChildItem` command includes the Depth or Recurse par
    ameters, empty directories aren't included in the output.

    Locations are exposed to `Get-ChildItem` by PowerShell providers. A location can be a file system directory, regist
    ry hive, or a certificate store. For more information, see about_Providers (../Microsoft.PowerShell.Core/About/abou
    t_Providers.md).


関連するリンク
    Online Version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-childitem?view=po
    wershell-5.1&WT.mc_id=ps-gethelp
    about_Certificate_Provider
    about_Providers
    about_Quoting_Rules
    about_Registry_Provider
    ForEach-Object
    Get-Alias
    Get-Item
    Get-Location
    Get-Process
    Get-PSProvider
    Split-Path

注釈
    例を参照するには、次のように入力してください: "get-help Get-ChildItem -examples".
    詳細を参照するには、次のように入力してください: "get-help Get-ChildItem -detailed".
    技術情報を参照するには、次のように入力してください: "get-help Get-ChildItem -full".
    オンライン ヘルプを参照するには、次のように入力してください: "get-help Get-ChildItem -online"

-


2).「ls」コマンドの「使用例」を表示:

PS C:\Users\user> get-help Get-ChildItem -examples
名前
    Get-ChildItem

概要
    Gets the items and child items in one or more specified locations.

-

例 1: ディレクトリ、を表示:
    --- Example 1: Get child items from a file system directory ---

    Get-ChildItem -Path C:\Test

    Directory: C:\Test

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    d-----        2/15/2019     08:29                Logs
    -a----        2/13/2019     08:55             26 anotherfile.txt
    -a----        2/12/2019     15:40         118014 Command.txt
    -a----         2/1/2019     08:43            183 CreateTestFile.ps1
    -ar---        2/12/2019     14:31             27 ReadOnlyFile.txt

    By default `Get-ChildItem` lists the mode ( Attributes ), LastWriteTime , file size ( Length ), and the Name of the
     item. The letters in the Mode property can be interpreted as follows:

    - `l` (link)

    - `d` (directory)

    - `a` (archive)

    - `r` (read-only)

    - `h` (hidden)

    - `s` (system).


    For more information about the mode flags, see about_Filesystem_Provider (../microsoft.powershell.core/about/about_
    filesystem_provider.md#attributes-flagsexpression).

→モード フラグの詳細は、「../microsoft.powershell.core/about/about_filesystem_provider.md#attributes-flagsexpression」

-

例 2: ディレクトリ表示で、そのうちの「名前」項目を表示:
    -------- Example 2: Get child item names in a directory --------

    Get-ChildItem -Path C:\Test -Name

    Logs
    anotherfile.txt
    Command.txt
    CreateTestFile.ps1
    ReadOnlyFile.txt

-

例 3: 現在のディレクトリとそのサブディレクトリ、を表示:
    Example 3: Get child items in the current directory and subdirectories

    Get-ChildItem -Path C:\Test\*.txt -Recurse -Force

    Directory: C:\Test\Logs\Adirectory

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    -a----        2/12/2019     16:16             20 Afile4.txt
    -a-h--        2/12/2019     15:52             22 hiddenfile.txt
    -a----        2/13/2019     13:26             20 LogFile4.txt

        Directory: C:\Test\Logs\Backup

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    -a----        2/12/2019     16:16             20 ATextFile.txt
    -a----        2/12/2019     15:50             20 LogFile3.txt

        Directory: C:\Test\Logs

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    -a----        2/12/2019     16:16             20 Afile.txt
    -a-h--        2/12/2019     15:52             22 hiddenfile.txt
    -a----        2/13/2019     13:26             20 LogFile1.txt

        Directory: C:\Test

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    -a----        2/13/2019     08:55             26 anotherfile.txt
    -a----        2/12/2019     15:40         118014 Command.txt
    -a-h--        2/12/2019     15:52             22 hiddenfile.txt
    -ar---        2/12/2019     14:31             27 ReadOnlyFile.txt

    The `Get-ChildItem` cmdlet uses the Path parameter to specify `C:\Test\ .txt`. Path * uses the asterisk (` `) wildc
    ard to specify all files with the filename extension `.txt`. The Recurse * parameter searches the Path directory it
    s subdirectories, as shown in the Directory: headings. The Force parameter displays hidden files such as `hiddenfil
    e.txt` that have a mode of h .

-

例 4: Include パラメータを使用して、子アイテムを表示:
    ---- Example 4: Get child items using the Include parameter ----

    # When using the -Include parameter, if you don't include an asterisk in the path
    # the command returns no output.
    Get-ChildItem -Path C:\Test\ -Include *.txt



    Get-ChildItem -Path C:\Test\* -Include *.txt

    Directory: C:\Test

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    -a----        2/13/2019     08:55             26 anotherfile.txt
    -a----        2/12/2019     15:40         118014 Command.txt
    -ar---        2/12/2019     14:31             27 ReadOnlyFile.txt

    The `Get-ChildItem` cmdlet uses the Path parameter to specify the directory C:\Test . The Path parameter includes a
     trailing asterisk (`*`) wildcard to specify the directory's contents. The Include parameter uses an asterisk (`*`)
     wildcard to specify all files with the file name extension .txt .

    When the Include parameter is used, the Path parameter needs a trailing asterisk (`*`) wildcard to specify the dire
    ctory's contents. For example, `-Path C:\Test*`.

    - If the Recurse parameter is added to the command, the trailing asterisk (` `) in the Path *   parameter is option
    al. The Recurse parameter gets items from the Path directory and its   subdirectories. For example, `-Path C:\Test\
     -Recurse -Include *.txt` - If a trailing asterisk (` `) isn't included in the Path * parameter, the command doesn'
    t return   any output and returns to the PowerShell prompt. For example, `-Path C:\Test`.

→「-Include」パラメータは、アスタリスク (*) ワイルドカードを使用して、ファイル名拡張子 .txt を持つすべてのファイルを指定します。なので、「-Include」パラメータを使用する場合、パスにアスタリスクを含めないと、コマンドは出力を返しません。

-

例 5: Exclude パラメータを使用して、子アイテムを表示:
    ---- Example 5: Get child items using the Exclude parameter ----

    Get-ChildItem -Path C:\Test\Logs

    Directory: C:\Test\Logs

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    d-----        2/15/2019     13:21                Adirectory
    d-----        2/15/2019     08:28                AnEmptyDirectory
    d-----        2/15/2019     13:21                Backup
    -a----        2/12/2019     16:16             20 Afile.txt
    -a----        2/13/2019     13:26             20 LogFile1.txt
    -a----        2/12/2019     16:24             23 systemlog1.log

    Get-ChildItem -Path C:\Test\Logs\* -Exclude A*

    Directory: C:\Test\Logs

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    d-----        2/15/2019     13:21                Backup
    -a----        2/13/2019     13:26             20 LogFile1.txt
    -a----        2/12/2019     16:24             23 systemlog1.log

    The `Get-ChildItem` cmdlet uses the Path parameter to specify the directory `C:\Test\Logs`. The Exclude parameter u
    ses the asterisk (`*`) wildcard to specify any files or directories that begin with A or a are excluded from the ou
    tput.

    When the Exclude parameter is used, a trailing asterisk (` `) in the Path * parameter is optional. For example, `-P
    ath C:\Test\Logs` or `-Path C:\Test\Logs*`.

    - If a trailing asterisk (` `) isn't included in the Path * parameter, the contents of the Path parameter are displ
    ayed. The exceptions are filenames or subdirectory names that match   the Exclude parameter's value. - If a trailin
    g asterisk (` `) is included in the Path * parameter, the command recurses into the Path parameter's subdirectories
    . The exceptions are filenames or subdirectory names that match   the Exclude parameter's value. - If the Recurse p
    arameter is added to the command, the recursion output is the same whether or   not the Path parameter includes a t
    railing asterisk (`*`).

→「-Exclude」パラメータは、アスタリスク (*) ワイルドカードを使用して、A または a で始まるすべてのファイルまたはディレクトリを除外して表示します。

-

例 6: レジストリから「レジストリ キー」を表示:
    ---- Example 6: Get the registry keys from a registry hive ----

    Get-ChildItem -Path HKLM:\HARDWARE

    Hive: HKEY_LOCAL_MACHINE\HARDWARE

    Name             Property
    ----             --------
    ACPI
    DESCRIPTION
    DEVICEMAP
    RESOURCEMAP
    UEFI

    Get-ChildItem -Path HKLM:\HARDWARE -Exclude D*

    Hive: HKEY_LOCAL_MACHINE\HARDWARE

    Name                           Property
    ----                           --------
    ACPI
    RESOURCEMAP

    The first command shows the contents of the `HKLM:\HARDWARE` registry key. The Exclude parameter tells `Get-ChildIt
    em` not to return any subkeys that start with `D `. Currently, the Exclude * parameter only works on subkeys, not i
    tem properties.

-

例 7:コード署名機関ですべての証明書を表示:
    - Example 7: Get all certificates with code-signing authority -

    Get-ChildItem -Path Cert:\* -Recurse -CodeSigningCert

    For more information about the Certificate provider and the Cert: drive, see about_Certificate_Provider (../Microso
    ft.PowerShell.Security/About/about_Certificate_Provider.md).

-

例 8: Depth パラメータを使用して、アイテムを表示:
    -------- Example 8: Get items using the Depth parameter --------

    Get-ChildItem -Path C:\Parent -Depth 2

    Directory: C:\Parent

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    d-----        2/14/2019     10:24                SubDir_Level1
    -a----        2/13/2019     08:55             26 file.txt

        Directory: C:\Parent\SubDir_Level1

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    d-----        2/14/2019     10:24                SubDir_Level2
    -a----        2/13/2019     08:55             26 file.txt

        Directory: C:\Parent\SubDir_Level1\SubDir_Level2

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    d-----        2/14/2019     10:22                SubDir_Level3
    -a----        2/13/2019     08:55             26 file.txt

    The `Get-ChildItem` cmdlet uses the Path parameter to specify C:\Parent . The Depth parameter specifies two levels
    of recursion. `Get-ChildItem` displays the contents of the directory specified by the Path parameter and the two le
    vels of subdirectories.

→「-Depth」パラメータは、表示する再帰のレベルを指定します。

-

例 9: ジャンクション ポイントのリンク ターゲットを表示:
    ----- Example 9 - Get the link target for a junction point -----

    PS D:\> New-Item -ItemType Junction -Name tmp -Target $env:TEMP
    PS D:\> Get-ChildItem | select name,*target

    Name     Target
    ----     ------
    tmp      {C:\Users\user1\AppData\Local\Temp}

-

-


まとめ

「Windows11」で、「PowerShell」(Windowsスクリプト実行環境)について学んでみました。

-

今さらの CUI コマンドですが、GUI 操作メインの「Windows」システム関連で、その運用の効率化には「スクリプトで自動化出来る」ことが必須みたい。

-

次回は、いよいよ「Windows11」で「Linux」にトライしますが、 「PowerShell」について知っておくと、「WSL2」を扱うときに役に立つと思います。

-

-

-


-

-

    目次

-

「投稿の先頭 へ」

-

-


-

「この目次 の先頭へ」

「本編の目次 に戻る」

-