数组元素类型因元素数量而异 [英] Array element types vary depending quantity of elements

查看:57
本文介绍了数组元素类型因元素数量而异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据一个文件夹中有多少个csv文件来填充数组.到目前为止,这是我的代码:

I am trying to populate an array based on how many csv files are in a folder. here is my code so far:

CD "\\domain\folder\file drop location"
$Array = Get-ChildItem -Filter *.csv | 
       Where-Object {-not $_.PsIsContainer} | 
       Foreach-Object {$_.Name}
$Array[0]

这将返回不同的值,具体取决于文件夹中有多少个.csv文件.如果仅存在1个csv,则 $ Array [0] 返回文件名的第一个字符(我不希望这样).如果有多个csv文件,则它将返回整个文件名(我确实希望这样做).如何使数组将单个文件接受为1元素数组?

This returns different values depending on how many .csv files are in the folder. If only 1 csv is present then $Array[0] returns the first character of the file name (I do not want this). If there are more than one csv files then it returns the entire file name (I DO want this). How do I cause the array to accept a single file as a 1-element array?

编辑除非您认为不了解PowerShell的业余爱好者/学习者不知道如何表达问题,否则可以将该问题视为重复问题.我对问题的解释使我浏览了数十页,这些页回答了其他问题,而不是我的.

EDIT This question can be viewed as a duplicate unless you consider that amateurs/learners who don't understand PowerShell don't know how to phrase a question. My interpretation of the problem led me to dozens of pages which answered other problems, not mine.

推荐答案

您可以在创建变量时将其转换为数组,即使只有一个结果,也始终是数组.

You can cast your variable as an array when you create it, and then it will always be an array, even if there's only one result.

[array]$Array = Get-ChildItem -Filter *.csv | 
       Where-Object {-not $_.PsIsContainer} | 
       Foreach-Object {$_.Name}

这篇关于数组元素类型因元素数量而异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆