LoginSignup
0
0

More than 1 year has passed since last update.

【Power Shell】テスト用_ファイル or フォルダ作成スクリプト

Last updated at Posted at 2022-07-21

たまにですが、、

テストで大量にファイルを作成する事があり、毎回コマンド作るのが面倒くさかったのでスクリプト作りました。コマンドの復習ついでに備忘残しておきます。

カレントディレクリ内にテスト用のファイルを作成するので、Get-Locationコマンドで現在地を取得します。
フォルダパスを作成したいので、-replaceで置換します。(`n は改行を意味します。)
Set-Locationで作成したフォルダパスを指定して、移動します。

Create_Object.ps1
#現在のフォルダパスを取得
$Folder_Pass = Get-Location
$Folder_Pass = $Folder_Pass -replace "Path`n---- "

Set-Location $Folder_Pass

今回はConfファイルで引数を定義します。
Create_Object.confを作成して、中身に下記のような記載を行います。

Create_Object.conf
#カンマ区切りで、引数を指定します。
#引数に"#"は含めないで下さい。
#引数の順番は(①File or Directory,②ファイル数,③名前)
File,10,test.log

作成したCreate_Object.confをスクリプト内に定義します。
Get-Contentコマンドでファイルを読み込み、Select-Stringコマンドで行頭に#がついている行以外の文字列を取得します。-NotMatch は指定したパターンに一致しない文字列を取得したい場合に使用します。
文字列取得後に、改行を置換します。

Create_Object.ps1
#Confファイルの定義
$Conf = "C:\Test\Config_Powershell\Create_Object.conf"
#Confファイルの読み込み
$Conf_Read = Get-Content $Conf | Select-String -NotMatch "^#"
$Conf_Read = $Conf_Read -replace "`n",""

splitを使用して、Conf内で定義していた引数を配列に格納します。

Create_Object.ps1
#パラメーターの作成
$Parameter = $Conf_Read.split(",")

あとは、ループ文でnew-itemコマンドを回せばOKでございます。
ファイル名の頭に番号を割り振っておきました。

Create_Object.ps1

for($i=1;$i -le $Parameter[1]){
    
    $Create_Object = [string]$i + "_" + $Parameter[2]
    New-item -itemtype $Parameter[0] $Create_Object
    $i += 1

}

ここまでのコマンドを組み合わせて、スクリプトを実行すればカレントディレクトリ上にファイル or フォルダ が作成されます。

Create_Object.ps1
#現在のフォルダパスを取得
$Folder_Pass = Get-Location
$Folder_Pass = $Folder_Pass -replace "Path`n---- "

Set-Location $Folder_Pass

#Confファイルの定義
$Conf = "C:\Test\Config_Powershell\Create_Object.conf"
#Confファイルの読み込み
$Conf_Read = Get-Content $Conf | Select-String -NotMatch "^#"
$Conf_Read = $Conf_Read -replace "`n",""

#パラメーターの作成
$Parameter = $Conf_Read.split(",")

for($i=1;$i -le $Parameter[1]){
    
    $Create_Object = [string]$i + "_" + $Parameter[2]
    New-item -itemtype $Parameter[0] $Create_Object
    $i += 1

}
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