简体   繁体   English

无法在Powershell脚本中使用Get-ChildItem列出文件名

[英]Cannot use Get-ChildItem to list filesnames in powershell script

In the powershell command-line I can execute the following 在powershell命令行中,我可以执行以下命令

$list = Get-ChildItem $path -name
foreach($k in $list){Write-host $k}

And it will list all the filenames in $path 它将列出$ path中的所有文件名

But if I copy and paste the same thing in code to execute, the output is blank 但是,如果我将相同的内容复制并粘贴到代码中以执行,则输出为空白

Why would this even happen? 为什么会发生这种情况?

Write-Host will write the string directly to the Host aka. Write-Host会将字符串直接写入Host the command line window, nowhere else 命令行窗口,其他任何地方

Just replace Write-Host with Write-Output if you want $k written to STDOUT : 如果要将$ k写入STDOUT只需将Write-Host替换为Write-Output

$list = Get-ChildItem $path -name
foreach($k in $list){Write-Output $k}

But in reality, that is unnecessary, Write-Output is called implicitly. 但是实际上,这是不必要的,隐式调用Write-Output You could achieve the same thing with just: 您可以通过以下方式实现相同的目的:

Get-ChildItem $path -Name

I wanted just a list of files sorted by size without directory headers. 我只需要一个按大小排序的文件列表,而没有目录头。 I used this to accomplish it. 我用它来完成它。

get-childitem foldername -file -recurse | get-childitem文件夹名-file -recurse | select FullName,Length | 选择FullName,Length | sort Length -descending | 降序排序 export-csv c:\\export.csv export-csv c:\\ export.csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM