|
|
Linux版 ファイル操作関連( Get-ChildItem ) |
H.Kamifuji . |
PowerShell では、コマンドプロンプト ls の機能拡張版のようです。Get-ChildItem コマンドを使用しますが、エイリアスとして dir や ls が設定されています。ls とは、UNIX ユーザなら使いなれていると思われます。 MS-DOS そのものが、UNIX のパクりであったと考えるのは、小生だけだろうか? 1970 年代から携わっておられる方々は、理解できると思います。 以下、使用例を説明します。 やはり、纏もにパクれていないようですね。まあ、パクった開発者も居なくなったし、伝承もされてないようだ! Windows版と同じコマンドのようだが、果たして、纏もに動作するのか確認が大変だ! UNIX系に長けた方は、sh , bash あるいは perl などのスゥリプトを使うでしょう。 |
先ずは、ヘルプを見てみよう。#!/usr/bin/pwsh # PowerShell Basics: Get-Help for Cmdlets # Clear-Host Get-Help Get-ChildItem -full 上記を実行すると下記のような長文が表示されます。 NAME Get-ChildItem SYNTAX Get-ChildItem [[-Path] <string[]>] [[-Filter] <string>] ........... #### 省略 #### ヘルプをファイルに保存するには、下記のようなリダイレクションを使用できるようです。PowerShell でのやり方については、別途説明します。 #!/usr/bin/pwsh # 出力結果をファイルに保存する。 Get-Help Get-ChildItem -full > Get-ChildItem_help_UX.txt 出力ファイルは、 Get-ChildItem_help_UX.txt ( UTF-8 ) です。 |
基本的な事例です。カレントディレクトリ 中のファイルを検索します。#!/usr/bin/pwsh # Basic PowerShell example to find all files # Clear-Host Get-ChildItem * 上記を実行すると、下記のように表示されます。 Directory: /xxxx/PSUX-Support/FindingFiles Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2019/09/02 9:03 images ------ 2019/09/02 7:56 6553 Get-ChildItem_help_UX.txt ------ 2019/09/02 8:48 103 sample00.ps1 ------ 2019/09/02 8:24 127 sample01.ps1 ------ 2019/09/02 9:05 94 sample10.ps1 上記の Mode 列は、UNIX に携わっている方は、見慣れている考えるが、各アイテムの属性が表示されます。 ただし、意味は、UNIX と若干異なっています。下記の6文字で表現されます。非該当部は - で表示されます。
上記のように定義されているようだが、d ディレクトリだけ表示されます。まあ、UNIX 使いの方は ls -l を使うと思います。 |
下記を実行してみます。#!/usr/bin/pwsh # PowerShell example to find Windows files # Clear-Host $Directory = "./" $Files = Get-Childitem $Directory -recurse -Include * -ErrorAction SilentlyContinue $Files 少しコードを説明しておきます。5 行目は、探査開始ディレクトリを $Directory に格納しています。6 行目で Get-ChildItem のパラメータとして利用しています。 -recurse は、再帰的にディレクトリを探査することを指定しています。 -Include * は、正規表現を利用して、ファイルを検索することを指定しています。 -ErrorAction SilentlyContinue は、途中、読めないディレクトリに遭遇したときなどのエラーメッセージを出力しないで続行することを指定しています。 実行結果は、下記です。長文のため冒頭部だけにしました。 Directory: /xxxx/PSUX-Support/FindingFiles Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2019/09/02 9:30 images Directory: /xxxx/PSUX-Support/FindingFiles/images Mode LastWriteTime Length Name ---- ------------- ------ ---- ------ 2016/06/23 16:18 1608 100_Form_01.png ------ 2016/06/23 16:19 2536 100_Form_02.png ------ 2016/06/23 16:19 3981 100_Form_03.png Directory: /xxxx/PSUX-Support/FindingFiles Mode LastWriteTime Length Name ---- ------------- ------ ---- ------ 2019/09/02 7:56 6553 Get-ChildItem_help_UX.txt ------ 2019/09/02 8:48 103 sample00.ps1 ------ 2019/09/02 8:24 127 sample01.ps1 ------ 2019/09/02 9:05 94 sample10.ps1 ------ 2019/09/02 9:42 184 sample20.ps1 |
次の事例を実行してみます。#!/usr/bin/pwsh # PowerShell example to find Windows files # Clear-Host $Directory = "./" $Phrase = "Childitem" $Files = Get-Childitem $Directory -recurse -Include *.txt -ErrorAction SilentlyContinue $Files | Select-String $Phrase -ErrorAction SilentlyContinue | Group-Object filename | Sort-Object count -descending 少しコードを説明しておきます。7 行目までは、前項と同じです。 6 行目には、検索する部分文字列を $Phrase に格納するコードが追加されています。 9 行目の Select-String $Phrase は、部分文字列が存在する行を選択します。-ErrorAction SilentlyContinue は、前項で説明しました。 Group-Object filename は、filename グルーピングして、個数を計測します。 Sort-Object count は、count で並び換えて、出力することを指定しています。-descending は、降順に並び変えることを指定しています。 実行結果は、下記です。長文のため冒頭部だけにしました。 Count Name Group ----- ---- ----- 21 Get-ChildItem_help_s.txt {/xxxx/PSUX-Support/FindingFile… 21 Get-ChildItem_help.txt {/xxxx/PSUX-Support/FindingFile… 4 Get-ChildItem_help_UX.txt {/xxxx/PSUX-Support/FindingFile… #### 省略 #### |
次の事例を実行してみます。#!/usr/bin/pwsh # PowerShell gci example to list .dll in Windows folder # Clear-Host $Files = gci "./" | Where {$_.extension -eq ".txt"} $Files | Format-Table Name, CreationTime, Length -auto 少しコードを説明しておきます。5 行目は、前項と同じく拡張子が .txt のファイルを検索します。gci は、Get-ChildItem のエイリアスです。Where {$_.extension -eq ".txt"} は、拡張子が .txt であるとき検索することを指定します。where の使い方は、別途説明します。 6 行目は、出力結果をテーブルに成形します。メンバーは、Name, CreationTime, Length を指定し、-auto は、表示桁数を自動で選択されることを指定しています。 実行結果は、下記です。 Name CreationTime Length ---- ------------ ------ Get-ChildItem_help_s.txt 2016/06/25 10:17:46 23294 Get-ChildItem_help_UX.txt 2019/09/02 7:56:42 6553 Get-ChildItem_help.txt 2016/06/25 10:16:16 23310 |
次の事例を実行してみます。#!/usr/bin/pwsh # PowerShell gci example to list .dll in ./ folder Write-Host `n "Waiting ...." $Files = gci "./" -Recurse | Where {$_.extension -eq ".txt"} Clear-Host $Files | Format-Table Name, CreationTime, Length -auto 処理内容は、前項と同じです。ただし、5 行目に -Recurse が追加されて、再帰的に多くのファイルを検索できます。 中には、長いファイル名もあり、PowerShell 画面の幅に合わせ拡張されています。 実行結果は、下記です。 Name CreationTime Length ---- ------------ ------ Get-ChildItem_help_s.txt 2016/06/25 10:17:46 23294 Get-ChildItem_help_UX.txt 2019/09/02 7:56:42 6553 Get-ChildItem_help_UXGet-ChildItem_help_UX.txt 2019/09/02 11:01:58 0 Get-ChildItem_help.txt 2016/06/25 10:16:16 23310 次項で、表示桁数を指定して、テーブルに成型するサンプルを説明します。 |
次の事例を実行してみます。#!/usr/bin/pwsh # PowerShell gci example to list .dll in Windows ./ $Files = gci "./" -Recurse | Where {$_.extension -eq ".txt"} Foreach ($Dll in $Files) { "{0,-38} {1,-20} {2,12}" -f $Dll.name, $DLL.CreationTime, $Dll.Length $i++ } Write-Host `n The total number of dlls is: $i 4 行目までは、前項と同じ処理です。 5 行目から 8 行目までは、Foreach 文による反復処理で、テーブルに成形しています。($Dll in $Files) は、$Files から1レコードのデータを $Dll に取り込みます。 6 行目で、桁数指定してテーブルに成形します。[0,-38} は、0番目のメンバーを左詰め 38 桁で、{1,-20} は、1番目のメンバーを左詰め20桁で、{2,12} は、2番目のメンバーを右詰め12桁で、表示することを指定しています。 7 行目では、検索されたファイルの個数を計測しています。 実行結果は、下記です。 Get-ChildItem_help_s.txt 2016/06/25 10:17:46 23294 Get-ChildItem_help_UX.txt 2019/09/02 7:56:42 6553 Get-ChildItem_help_UXGet-ChildItem_help_UX.txt 2019/09/02 11:01:58 0 Get-ChildItem_help.txt 2016/06/25 10:16:16 23310 The total number of .txts is: 4 しかし、指定した桁数に収まらない時には、右側にシフトされるようです。 |
次の事例を実行してみます。#!/usr/bin/pwsh # List ALL files in the /usr $GciFiles = Get-Childitem /usr -Force $GciFiles | Sort-Object | FT Name, Attributes -auto Write-Host "Number of files in the root: " $GciFiles.Count 4 行目の -Force は、 隠し、システム、読取専用などすべてのアイテムを検索することを指定しています。 5 行目は、前項らと同じくテーブルに成形します。 6 行目の $GciFiles.Count には、アイテムの個数が格納されています。 実行結果は、下記です。 Name Attributes ---- ---------- _ww ReadOnly bin ReadOnly, Directory etc ReadOnly, Directory games ReadOnly, Directory include ReadOnly, Directory java ReadOnly, Directory lib ReadOnly, Directory lib64 ReadOnly, Directory libexec ReadOnly, Directory local ReadOnly, Directory sbin ReadOnly, Directory share ReadOnly, Directory src ReadOnly, Directory tmp Directory, ReparsePoint Number of files in the /usr: 14 4 行目の -Force を指定しないと、下記のような結果になります。 Name Attributes ---- ---------- _ww ReadOnly bin ReadOnly, Directory etc ReadOnly, Directory games ReadOnly, Directory include ReadOnly, Directory java ReadOnly, Directory lib ReadOnly, Directory lib64 ReadOnly, Directory libexec ReadOnly, Directory local ReadOnly, Directory sbin ReadOnly, Directory share ReadOnly, Directory src ReadOnly, Directory tmp Directory, ReparsePoint Number of files in the /usr: 14 Windows版では、取り込む Attributes 項目数に差異があったが、Linux版では、差異なしです。やはり、Linux の Attributes を纏もに把握していないようだ! 4 行目の -Force を指定しないと、下記のような結果になります。 |
次の事例を実行してみます。#!/usr/bin/pwsh # PowerShell cmdlet to list JUST the System files in the /usr $GciFiles = Get-ChildItem "/usr" -Force | where {$_.attributes -Match "System"} $GciFiles | Sort-Object | Format-Table name, attributes -auto Write-Host "Number of system files: " $GciFiles.Count 4 行目は、前項のコードに対して、 | where {$_.attributes -Match "System"} が追加され、システムアイテムのみ選択します。 5 〜 6 行目は、前項と同じです。 実行結果は、下記です。 Number of system files: 0やはり、Linux の Attributes には、system が定義されていないようだ! |
次の事例を実行してみます。#!/usr/bin/pwsh # PowerShell cmdlet to list the System files in the /usr $GciFiles = gci /usr -Force | where {$_.attributes -ne "Directory"} $GciFiles | Sort-Object | FT Name, Attributes -auto Write-Host "Number of plain files: " $GciFiles.Count 4 行目は、前項のコードに対して、 | where {$_.attributes -Match "System"} が | where {$_.attributes -ne "Directory"} 変更され、ディレクトリ以外を選択します。 5 〜 6 行目は、前項と同じです。 実行結果は、下記です。 Name Attributes ---- ---------- _ww ReadOnly bin ReadOnly, Directory etc ReadOnly, Directory games ReadOnly, Directory include ReadOnly, Directory java ReadOnly, Directory lib ReadOnly, Directory lib64 ReadOnly, Directory libexec ReadOnly, Directory local ReadOnly, Directory sbin ReadOnly, Directory share ReadOnly, Directory src ReadOnly, Directory tmp Directory, ReparsePoint Number of files in the /usr: 14 この例では、where {$_.attributes -ne "Directory"} が機能していないと思われる。 |
次の事例を実行してみます。#!/usr/bin/pwsh # Research PowerShell Get-Childitem Properties Get-Childitem | Get-Member 実行結果は、下記に示します。長文なので途中省略しました。各自確認してみてください。 TypeName: System.IO.DirectoryInfo Name MemberType Definition ---- ---------- ---------- LinkType CodeProperty System.String LinkType{get=GetLinkTyp… Mode CodeProperty System.String Mode{get=Mode;} Target CodeProperty System.Collections.Generic.IEnumerabl… Create Method void Create() CreateSubdirectory Method System.IO.DirectoryInfo CreateSubdire… Delete Method void Delete(), void Delete(bool recur… EnumerateDirectories Method System.Collections.Generic.IEnumerabl… EnumerateFiles Method System.Collections.Generic.IEnumerabl… EnumerateFileSystemInfos Method System.Collections.Generic.IEnumerabl… Equals Method bool Equals(System.Object obj) GetDirectories Method System.IO.DirectoryInfo[] GetDirector… GetFiles Method System.IO.FileInfo[] GetFiles(), Syst… GetFileSystemInfos Method System.IO.FileSystemInfo[] GetFileSys… GetHashCode Method int GetHashCode() GetLifetimeService Method System.Object GetLifetimeService() GetObjectData Method void GetObjectData(System.Runtime.Ser… GetType Method type GetType() InitializeLifetimeService Method System.Object InitializeLifetimeServi… MoveTo Method void MoveTo(string destDirName) Refresh Method void Refresh() ToString Method string ToString() PSChildName NoteProperty string PSChildName=images PSDrive NoteProperty PSDriveInfo PSDrive=/ PSIsContainer NoteProperty bool PSIsContainer=True PSParentPath NoteProperty string PSParentPath=Microsoft.PowerSh… PSPath NoteProperty string PSPath=Microsoft.PowerShell.Co… PSProvider NoteProperty ProviderInfo PSProvider=Microsoft.Pow… Attributes Property System.IO.FileAttributes Attributes {… CreationTime Property datetime CreationTime {get;set;} CreationTimeUtc Property datetime CreationTimeUtc {get;set;} Exists Property bool Exists {get;} Extension Property string Extension {get;} FullName Property string FullName {get;} LastAccessTime Property datetime LastAccessTime {get;set;} LastAccessTimeUtc Property datetime LastAccessTimeUtc {get;set;} LastWriteTime Property datetime LastWriteTime {get;set;} LastWriteTimeUtc Property datetime LastWriteTimeUtc {get;set;} Name Property string Name {get;} Parent Property System.IO.DirectoryInfo Parent {get;} Root Property System.IO.DirectoryInfo Root {get;} BaseName ScriptProperty System.Object BaseName {get=$this.Nam… TypeName: System.IO.FileInfo Name MemberType Definition ---- ---------- ---------- LinkType CodeProperty System.String LinkType{get=GetLinkTyp… Mode CodeProperty System.String Mode{get=Mode;} Target CodeProperty System.Collections.Generic.IEnumerabl… AppendText Method System.IO.StreamWriter AppendText() CopyTo Method System.IO.FileInfo CopyTo(string dest… Create Method System.IO.FileStream Create() CreateText Method System.IO.StreamWriter CreateText() Decrypt Method void Decrypt() Delete Method void Delete() Encrypt Method void Encrypt() Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetLifetimeService Method System.Object GetLifetimeService() GetObjectData Method void GetObjectData(System.Runtime.Ser… GetType Method type GetType() InitializeLifetimeService Method System.Object InitializeLifetimeServi… MoveTo Method void MoveTo(string destFileName) Open Method System.IO.FileStream Open(System.IO.F… OpenRead Method System.IO.FileStream OpenRead() OpenText Method System.IO.StreamReader OpenText() OpenWrite Method System.IO.FileStream OpenWrite() Refresh Method void Refresh() Replace Method System.IO.FileInfo Replace(string des… ToString Method string ToString() PSChildName NoteProperty string PSChildName=_index.html PSDrive NoteProperty PSDriveInfo PSDrive=/ PSIsContainer NoteProperty bool PSIsContainer=False PSParentPath NoteProperty string PSParentPath=Microsoft.PowerSh… PSPath NoteProperty string PSPath=Microsoft.PowerShell.Co… PSProvider NoteProperty ProviderInfo PSProvider=Microsoft.Pow… Attributes Property System.IO.FileAttributes Attributes {… CreationTime Property datetime CreationTime {get;set;} CreationTimeUtc Property datetime CreationTimeUtc {get;set;} Directory Property System.IO.DirectoryInfo Directory {ge… DirectoryName Property string DirectoryName {get;} Exists Property bool Exists {get;} Extension Property string Extension {get;} FullName Property string FullName {get;} IsReadOnly Property bool IsReadOnly {get;set;} LastAccessTime Property datetime LastAccessTime {get;set;} LastAccessTimeUtc Property datetime LastAccessTimeUtc {get;set;} LastWriteTime Property datetime LastWriteTime {get;set;} LastWriteTimeUtc Property datetime LastWriteTimeUtc {get;set;} Length Property long Length {get;} Name Property string Name {get;} BaseName ScriptProperty System.Object BaseName {get=if ($this… VersionInfo ScriptProperty System.Object VersionInfo {get=[Syste… |
次の事例を実行してみます。#!/usr/bin/pwsh # PowerShell script to investigate file properties Get-ChildItem | Get-Member -Membertype property 実行結果は、下記です。 TypeName: System.IO.DirectoryInfo Name MemberType Definition ---- ---------- ---------- Attributes Property System.IO.FileAttributes Attributes {get;set;} CreationTime Property datetime CreationTime {get;set;} CreationTimeUtc Property datetime CreationTimeUtc {get;set;} Exists Property bool Exists {get;} Extension Property string Extension {get;} FullName Property string FullName {get;} LastAccessTime Property datetime LastAccessTime {get;set;} LastAccessTimeUtc Property datetime LastAccessTimeUtc {get;set;} LastWriteTime Property datetime LastWriteTime {get;set;} LastWriteTimeUtc Property datetime LastWriteTimeUtc {get;set;} Name Property string Name {get;} Parent Property System.IO.DirectoryInfo Parent {get;} Root Property System.IO.DirectoryInfo Root {get;} TypeName: System.IO.FileInfo Name MemberType Definition ---- ---------- ---------- Attributes Property System.IO.FileAttributes Attributes {get;set;} CreationTime Property datetime CreationTime {get;set;} CreationTimeUtc Property datetime CreationTimeUtc {get;set;} Directory Property System.IO.DirectoryInfo Directory {get;} DirectoryName Property string DirectoryName {get;} Exists Property bool Exists {get;} Extension Property string Extension {get;} FullName Property string FullName {get;} IsReadOnly Property bool IsReadOnly {get;set;} LastAccessTime Property datetime LastAccessTime {get;set;} LastAccessTimeUtc Property datetime LastAccessTimeUtc {get;set;} LastWriteTime Property datetime LastWriteTime {get;set;} LastWriteTimeUtc Property datetime LastWriteTimeUtc {get;set;} Length Property long Length {get;} Name Property string Name {get;} |
次の事例を実行してみます。#!/usr/bin/pwsh # PowerShell Alias GCI Get-Alias -Definition Get-ChildItem 実行結果は、下記です。 CommandType Name Version Source ----------- ---- ------- - Alias dir -> Get-ChildItem Alias gci -> Get-ChildItem Linux版では、ls がエイリアスとして設定されていない。UNIX の ls コマンドであるため、設定されていないようだ。 |
次の事例を実行してみます。#!/usr/bin/pwsh # PowerShell Item Cmdlet Research Get-Command -Noun Item 実行結果は、下記です。 CommandType Name Version Source ----------- ---- ------- ------ Cmdlet Clear-Item 6.1.0.0 Microsoft.PowerShell.Management Cmdlet Copy-Item 6.1.0.0 Microsoft.PowerShell.Management Cmdlet Get-Item 6.1.0.0 Microsoft.PowerShell.Management Cmdlet Invoke-Item 6.1.0.0 Microsoft.PowerShell.Management Cmdlet Move-Item 6.1.0.0 Microsoft.PowerShell.Management Cmdlet New-Item 6.1.0.0 Microsoft.PowerShell.Management Cmdlet Remove-Item 6.1.0.0 Microsoft.PowerShell.Management Cmdlet Rename-Item 6.1.0.0 Microsoft.PowerShell.Management Cmdlet Set-Item 6.1.0.0 Microsoft.PowerShell.Management Windows版と同じコマンドのようだが、果たして、纏もに動作するのか確認が大変だ! UNIX系に長けた方は、sh , bash あるいは perl などのスゥリプトを使うでしょう。 |