[英]How to create empty files in all empty folders using PowerShell?
I want to create empty text files in all the subfolders which are empty. 我想在所有空的子文件夹中创建空的文本文件。 The following piece of script will list all the empty subfolders.
下面的脚本将列出所有空的子文件夹。
$a = Get-ChildItem D:\test -recurse | Where-Object {$_.PSIsContainer -eq $True}
$a | Where-Object {$_.GetFiles().Count -eq 0} | Select-Object FullName
How can I iterate through the output of the above command and create empty text files in them? 如何遍历上述命令的输出并在其中创建空文本文件?
There were a few too many loops in the answer you made for yourself. 您为自己做出的答案中有很多循环。 I offer this solution which will make an empty file in all directories that do not have files ( From your solution it is OK if they have folders so I'm keeping with that logic.)
我提供了此解决方案,该解决方案将在所有没有文件的目录中创建一个空文件(从您的解决方案中可以找到是否有文件夹,所以我会保持这种逻辑。)
Get-ChildItem -Recurse C:\temp |
Where-Object {$_.PSIsContainer -and ($_.GetFiles().Count -eq 0)} |
ForEach-Object{[void](New-Item -Path $_.FullName -Name "Touch.txt" -ItemType File)}
If $_.PSIsContainer
is false then it won't bother with the other condition of checking for files. 如果
$_.PSIsContainer
为false,那么它将不会受到其他检查文件条件的困扰。 Also cast the output of New-Item
to void to stop the output of successfully created all those new files. 还将
New-Item
的输出New-Item
为void以停止成功创建所有这些新文件的输出。
The following piece of code worked for me. 以下代码对我有用。
$a = Get-ChildItem D:\test -recurse | Where-Object {$_.PSIsContainer -eq $True}
$path = $a | Where-Object {$_.GetFiles().Count -eq 0} | foreach {$_.FullName}
$a | Where-Object {$_.GetFiles().Count -eq 0} | foreach {$_.FullName}|ForEach-Object -Process {New-Item -Path $path -Name "testfile.txt" -Value "Test Value" -ItemType File }
How make sure.. this does not create the file in a directory, which has sub directory in it. 如何确保..这不会在目录中创建文件,该目录中包含子目录。
ie file should be created in a directory where there are no files and sub-directories 即,应在没有文件和子目录的目录中创建文件
this worked for me .. it creates file only if the directory neither has sub-directories or files 这对我有用..仅当目录既没有子目录也没有文件时,它才创建文件
$a = Get-ChildItem C:\tejasoft -recurse | Where-Object {$_.PSIsContainer -eq $True -and ($_.GetDirectories().Count -eq 0)}
$path = $a | Where-Object {$_.GetFiles().Count -eq 0} | foreach {$_.FullName}
$a | Where-Object {$_.GetFiles().Count -eq 0} | foreach {$_.FullName}|ForEach-Object -Process {New-Item -Path $path -Name ".keep" -Value "Test Value" -ItemType File }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.