PowerShell:列出到txt文件的子目录

今天我开始在Windows PowerShell中编写脚本 - 所以请原谅我的“愚蠢”...... 我想创建txt-Files,其中包含驱动器G:上每个“rootfolder”的子文件夹的名称。在G:我有以下文件夹: 1_data 2_IT_area 3_personal 4_apprenticeship 7_backup 8_archives 9_user_profile 所以我写了这个脚本:
get-childitem G: | ForEach-Object -process {gci $_.fullName -R} | WHERE {$_.PSIsContainer} > T:listingfileListing+$_.Name+.txt
但是脚本没有做我想要的 - 它只创建一个文本文件..你能帮助我吗?我已按照此处所述尝试了它>> http://www.powershellpro.com/powershell-tutorial-introduction/variables-arrays-hashes/“T: listing $ _。Name.txt” - 不起作用好... 非常感谢你的帮助! -Patrick     
已邀请:
这应该做你想要的:
Get-ChildItem G: | Where {$_.PSIsContainer} | 
    Foreach {$filename = "T:fileListing_$($_.Name).txt"; 
             Get-ChildItem $_ -Recurse > $filename} 
如果以交互方式输入(使用别名):
gci G: | ?{$_.PSIsContainer} | %{$fn = "T:fileListing_$($_.Name).txt"; 
                                  gci $_ -r > $fn} 
$_
特殊变量通常仅在脚本块
{ ... }
中对Foreach-Object,Where-Object或任何其他管道相关的scriptblock有效。所以下面的文件名构造
T:listingfileListing+$_.Name+.txt
不太正确。通常,您会在字符串中展开变量,如下所示:
$name = "John"
"His name is $name"
但是,当您访问像
$_.Name
这样的对象的成员时,您需要能够在字符串中执行表达式。你可以使用子表达式运算符ѭ8例如:
"T:listingfileListing_$($_.Name).txt"
除了文件名字符串结构之外,你不能在scriptblock之外使用
$_
。所以你只需在Foreach scriptblock中移动文件名结构。然后使用重定向到该文件名的相关目录的内容创建该文件 - 这将创建该文件。     

要回复问题请先登录注册