Powershell Foreach循环将特定文件移动到指定文件夹中

Powershell Foreach循环将特定文件移动到指定文件夹中,powershell,foreach,Powershell,Foreach,我正在学习PowerShell,我的家庭作业有困难。我的目标是获取当前目录中所有文件的列表,并将其保存到变量中。然后使用foreach循环根据文件名将每个文件移动到不同的文件夹,使用文件标记搜索文件名 档案: 1建筑物 1LabFile 1分配文件 1.ps1 文件夹: 讲课 实验室 分配 剧本 当我运行脚本时,这些文件进入各自的文件夹 我必须使用文件标记(例如*lec*,*lab*,*分配*,*脚本*)来搜索文件 以下是我目前掌握的代码: # Gets a list of all fi

我正在学习PowerShell,我的家庭作业有困难。我的目标是获取当前目录中所有文件的列表,并将其保存到变量中。然后使用foreach循环根据文件名将每个文件移动到不同的文件夹,使用文件标记搜索文件名

档案:

  • 1建筑物
  • 1LabFile
  • 1分配文件
  • 1.ps1
文件夹:

  • 讲课
  • 实验室
  • 分配
  • 剧本
当我运行脚本时,这些文件进入各自的文件夹

我必须使用文件标记(例如
*lec*
*lab*
*分配*
*脚本*
)来搜索文件

以下是我目前掌握的代码:

# 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 "    "
    }
}

我不希望有人给我答案。任何提示,或提示或一般指南指向正确的方向我将不胜感激。我在网上搜索过,但大多数建议的答案对我来说太难理解(大多数命令我还没有学会)。

谢谢你提供的所有有用的提示和提示。我已经成功地完成了脚本,它正在按预期工作。为了提高效率,我没有使用
if
语句,而是使用
Switch
语句。因为我正在向循环中添加更多内容,所以
forloop
将保持不变,否则我将忽略它

Foreach ($i in $Files2) {

    switch -Wildcard ($i) {
        ("*lec*") {Move-Item $i -Destination "Lecture"}
        ("*lab*") {Move-Item $i -Destination "Lab"}
        ("*assign*") {Move-Item $i -Destination "Assignment"}
        ("*.ps1*") {Move-Item $i -Destination "Scripts"}
    }
}

您的
开关可以简化为:

switch -Wildcard ($Files2) {
    "*lec*" {Move-Item $_ -Destination "Lecture"}
    "*lab*" {Move-Item $_ -Destination "Lab"}
    "*assign*" {Move-Item $_ -Destination "Assignment"}
    "*.ps1*" {Move-Item $_ -Destination "Scripts"}
}
switch命令将遍历文件对象数组。在开关中,我们引用了
$\uuu
,它表示正在测试的阵列的当前项

另一种方法是使用哈希表创建每种文件应该放在哪里的字典映射,然后在select语句中使用
-match
,并使用自动
$matches
变量查找每种文件应该放在哈希表中的位置。比如:

$PathLookup = @{
        'lec' = "Lecture"
        'lab' = "Lab"
        'assign' = "Assignment"
        '.ps1' = "Scripts"
}

$Files2 | Where{$_.Name -match '(lec|lab|assign|\.ps1)'} | ForEach{
    Move-Item $_ -Destination $PathLookup[$Matches[1]]
}

另外,尝试在控制台中运行几行
$Files2 | Get Member
是一个很有用的工具,它可以找出
$Files2
对象的成员(属性、方法等)。()在循环的顶部添加:$filename=$i.name这将为您提供文件名,然后使用if($filename-like“lec”)代替if(gci($i-eq“”)你对一个对象使用了-eq,你需要对一个stringas@gms0ulman说,查看get member并查看$files2的内容。谢谢你的提示,我相信我找到了陷入困境的原因。仅供参考,根据我的经验,学习PowerShell的最佳方法是使用get Help-full[command]和get member。