【发布时间】:2018-03-06 00:02:38
【问题描述】:
我正在学习 PowerShell,但我的作业有困难。我的目标是获取当前目录中所有文件的列表,并将其保存到变量中。然后使用 foreach 循环根据文件名将每个文件移动到不同的文件夹,使用文件标签搜索文件名。
文件:
- 1讲座文件
- 1实验室文件
- 1分配文件
- 1.ps1
文件夹:
- 讲座
- 实验室
- 作业
- 脚本
当我运行脚本时,这些文件会进入它们各自的文件夹。
我必须使用文件标签(例如*lec*、*lab*、*Assign*、*Scripts*)来搜索文件。
这是我目前的代码:
# Gets a list of all file names and saves it to a variable
$Files2 = Get-ChildItem "dir" -File
foreach ($i in $Files2) {
#My attempt at searching for the files containing lec
if (gci ($i -eq "*lec*")) {
#Moves the file that fits the description into Lecture folder
Move-Item $i -Destination "Lecture"
# If $i doesn't fit first if, repeats and looks for Lab
} elseif (" ") {
Move-Item " "
}
}
我不希望任何人给我答案。任何提示或提示或一般指南将我指向正确的方向将不胜感激。我在网上搜索过,但大多数建议的答案对我来说太难理解了(大多数命令我还没有学过)。
【问题讨论】:
-
另外,尝试在控制台中运行几行代码。
$Files2 | Get-Member是找出$Files2对象的成员(属性、方法等)的有用方法。 (Get-Member docs) -
在循环顶部添加: $filename = $i.name 这将为您提供文件名,然后使用 if (gci ( $i -eq "") 代替 if ($filename -比如 "lec") 你对一个对象使用 -eq ,你需要对一个字符串使用 -like
-
正如@gms0ulman 所说,通过get-member 看看$files2 的内容。
-
感谢您的提示,相信我找到了卡住的原因。
-
仅供参考,根据我的经验,学习 PowerShell 的最佳方法是使用 Get-Help -full [command] 和 Get-Member。
标签: powershell foreach