What is wrong with this script to create files in all subfolders?

浪尽此生 提交于 2019-12-13 05:51:06

问题


I have a directory tree, consisting of several layers, within which I want to create 30 placeholder files, recursively in each folder.

The tree looks something like this:

--F:\inbox\test  
 ----folder1  
 ------subfolder1  
 ------subfolder2  
 ----folder2  
 ------subfolder1  
 ------subfolder2  
 ----folder3  
 ------subfolder1  
 ------subfolder2

Here is what I have.

$folders = gci -path f:\inbox\test -recurse | where {$_.PsIsContainer}  
foreach ($folder in $folders) {  
        1..30 | % { New-Item -Name "$_.txt" -Value (get-date).tostring() -Itemtype file -force}
}

This just creates 30 files in the root folder. I know I am missing something in my logic.


回答1:


You're not telling new-item where to put the file, so it uses the current working directory. Fortunately, this is easliy fixed with the -Path parameter for the cmdlet.

$folders = gci -path f:\inbox\test -recurse | where {$_.PsIsContainer}  
foreach ($folder in $folders) {  
        1..30 | % { New-Item -Path $folder.FullName -Name "$_.txt" -Value (get-date).tostring() -Itemtype file -force}
}


来源:https://stackoverflow.com/questions/19911435/what-is-wrong-with-this-script-to-create-files-in-all-subfolders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!