LoginSignup
0
0

More than 5 years have passed since last update.

ファイル操作:PowershellからExcelにファイルリストを作る

Last updated at Posted at 2017-04-05

Dirから作るよりはるかに強力

PowershellからCSVを作りExcelのマクロでxlsx形式にします

手順1 ドキュメントフォルダに Ps_GetChildItem.xlsmを作成し、以下のマクロを登録


Sub SpecialCSVtoXLSX(strFile As String)
Dim wb As Workbook: Set wb = ThisWorkbook
Dim wbPath As String: wbPath = wb.Path
Dim wb1 As Workbook
Dim strPath As String
strPath = Environ("HOMEDRIVE") & Environ("HOMEPATH") & "\Documents"
ChDir Environ("HOMEDRIVE") & "\"
'strPath = "F:\My Documents"
'ChDir (strPath)
Workbooks.OpenText Filename:=strFile, Origin:=65001, StartRow:=1 _
, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=True, Tab:=True, Semicolon:=False, Comma:=False, _
Space:=False, Other:=True, OtherChar:="a", FieldInfo:=Array(Array(1, 5), _
Array(2, 5), Array(3, 5), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1), _
Array(9, 1), Array(10, 1), Array(11, 1)), TrailingMinusNumbers:=True
Set wb1 = Workbooks("psList.Csv")
Range("A:A,B:B,C:C").Select
Range("C1").Activate
Range("A:A,B:B,C:C").EntireColumn.AutoFit
Selection.ColumnWidth = 16.88
Range("A2:C2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Font.Size = 10
Columns("A:C").Select
Columns("A:C").EntireColumn.AutoFit
Rows("2:2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.RowHeight = 27.75
Columns("D:G").Select
Range("D6747").Activate
With Selection
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Selection.Font.Size = 10
Selection.ColumnWidth = 30
Range("A1").Select
ActiveWindow.SmallScroll Down:=152
Range("A1").Select
Windows("PS_GetChildItem.xlsm").Activate
With CreateObject("Scripting.FileSystemObject")
If .fileexists(wbPath & "\psList.xlsx") Then Kill wbPath & "\psList.xlsx"

End With
wb1.SaveAs Filename:=wbPath & "\psList.xlsx": DoEvents
wb1.Close
wb.Close
Application.Quit

Powershell ISEを起動する

ちなみにWの項目でPのところではない。
(X86)でなくてよい。
以下のスクリプトを白い画面にコピペする

#Set-ExecutionPolicy remotesigned -Scope process -Force
#区切り文字としてaを使うことで、コンマのあるデータなどが途中で区切らないようにしている
$TargetFolder = "C:\hogehoge\hogehoge" #ここで調べたいフォルダを決めている
$sPSListcsv = "psList.csv"
$xlFN = "PS_GetChildItem.xlsm" #マクロを搭載したエクセルファイル。このスクリプトと同じフォルダにおくこと。変更しないこと。
$sBase = (Get-ChildItem $sCSV).Basename
$VbCrLf = “`r`n #改行を定義
$sFolder = [environment]::getfolderpath(mydocuments) #ドキュメントフォルダを環境変数から判断
#$sFolder = "F:\My Documents"
$sCSV = Join-Path "$sFolder" "$sPSListcsv" #csvファイルはのちにエクセルで使用するため、変更しないこと
$file_name_B = Join-Path $sFolder $xlFN
if(!(Test-Path $file_name_B)){
$blResult = [System.Windows.Forms.MessageBox]::Show(
"$sFolder$xlFN が存在しないのでCSVの変換ができません。" + $VbCrLf + `
"OKをクリックすると処理を中止します。" + $VbCrLf + `
"CSVのみ作成あればキャンセルをクリックしてください。" + $VbCrLf ,
"CSVを変換するマクロのあるエクセルファイルがありません", "OKCancel","Information")
IF($blResult -eq "OK"){Exit}ELSE{Remove-Item $sCSV}
}
if(Test-Path $sCSV){
$blResult2 = [System.Windows.Forms.MessageBox]::Show(" $sFolder$sPSListcsv が存在します。OKをクリックすると削除して作業します。必要な場合はファイル名を変更してください。" + $VbCrLf +"キャンセルをクリックすると終了します。" `
,"同名のファイルあり", "OKCancel","Information")
IF($blResult2 -eq "Cancel"){Exit}ELSE{Remove-Item $sCSV}
}
Get-ChildItem -Path "$TargetFolder" -Recurse -Force | Select-Object creationtime, lastaccesstime,lastwritetime,directoryname,fullname,name,basename,extension,attributes,isreadonly, length `
| Export-Csv -Path "$sCSV" -Encoding utf8 -NoTypeInformation -Force -Delimiter "a"
#Get-ChildItem -Path E:\music -Filter *.mp3 -Recurse | Select-Object creationdate, lastaccesstime,lastwritetime,directoryname,fullname,basename,extension,attributes,isreadonly,directoryname, basename, length | Export-Csv -Path c:\fso\music.csv -Encoding ascii -NoTypeInformation

$DebugPreference = "SilentlyContinue"

if(Test-Path $file_name_B){
# excel用のオブジェクト生成
$excel = New-Object -ComObject Excel.Application
# 表示モード
$excel.Visible = $True
$macro_name="SpecialCSVtoXLSX"
$book_B = $excel.workbooks.Open( $file_name_B )
$excel.run( $macro_name ,$sCSV )
}

Powershell ISEの青い画面にスクリプトの1行目のSet-ExecutionPolicy remotesigned -Scope process -Forceをコピー(Ctrl+Cでよい)

青い画面にペーストする(このペーストはマウスの右クリックが確実)
Enterを押す

Powershell ISEの白い画面をクリックして F5キーを押してスクリプトを起動する

これでドキュメントフォルダにC:\HogehogeのファイルリストpsList.xlsxがドキュメントフォルダに完成する。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0