今天我开始在Windows Powershell中拼写脚本 - 所以请原谅我的“愚蠢” ...

我想创建带有驱动器g::我的每个“ rootfolder”的子文件夹的名称的TXT文件。在g: i上有以下文件夹:

1_data
2_it_area
3_个人
4_Apprenticeship
7_backup
8_archives
9_USER_PROFILE

所以我写了这个脚本:

get-childitem G:\ | ForEach-Object -process {gci $_.fullName -R} | WHERE {$_.PSIsContainer} > T:\listing\fileListing+$_.Name+.txt

但是脚本不做我想要的 - 它只创建一个文本文件..您能帮我吗?我已经尝试了此处描述的>> http://www.powershellpro.com/powershell-tutorial-indroduction/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} 

$_ 特殊变量通常仅在scriptblock中有效 { ... } 对于for-object,whot-object或任何其他与管道相关的脚本块。因此以下文件名构造 T:\listing\fileListing+$_.Name+.txt 不太正确。通常,您会在字符串中扩展一个变量:

$name = "John"
"His name is $name"

但是,当您访问像对象的成员时 $_.Name 然后,您需要能够在字符串中执行表达式。您可以使用子表达操作员来做到这一点 $() 例如:

"T:\listing\fileListing_$($_.Name).txt"

除了所有的文件名构造,您无法使用 $_ 外部脚本块。因此,您只需将文件名构造移到foreach ScriptBlock中即可。然后用相关的dir的内容创建该文件,将其重定向到该文件名 - 将创建文件。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top