通过变量查找文件夹并对其进行操作

时间:2019-02-04 20:27:28

标签: windows powershell variables scripting directory

我正在尝试使用基于文件夹名称的文本文件构建带有变量的脚本,在一个目录中找到它们,然后将它们移动到另一个目录(或在其他脚本中删除它们)。

例如:

$foldernames = Get-Content -Path "C:\Users\Me\Desktop\Folders.txt"
$startpath = "C:\Users\Me\Desktop\Test"
$topath = "C:\Users\Me\Desktop\Moved"

然后在$startpath的文件夹名称中找到每个选项行,如果找到它们,将其移至$topath

1 个答案:

答案 0 :(得分:0)

这将完成工作。 [咧嘴]它会伪造在您要移动的目录的文本文件中读取[使用Get-Content实作],然后在源中收集目录的目录位置。接下来,它会测试.Name是否在要移动的目录列表中。最后,它运行Move-Item来移动目录。

请注意最后的-WhatIf ...准备好对测试数据集进行实时测试时,请将其删除。 [咧嘴]

# fake reading in a text file
#    in real life, use Get-Content
$ToMoveDirNameList = @(
    'test1'
    'TuTu'
    'GoGoGadget'
    'WPF'
    )

$SourceDir = $env:TEMP
$DestDir = 'd:\temp'

$SourceDirList = Get-ChildItem -LiteralPath $SourceDir -Directory

foreach ($SDL_Item in $SourceDirList)
    {
    if ($SDL_Item.Name -in $ToMoveDirNameList)
        {
        Move-Item -LiteralPath $SDL_Item.FullName -Destination $DestDir -WhatIf
        }
    }

输出...

What if: Performing the operation "Move Directory" on target "Item: C:\Temp\test1 Destination: D:\temp\test1".
What if: Performing the operation "Move Directory" on target "Item: C:\Temp\TuTu Destination: D:\temp\TuTu".
What if: Performing the operation "Move Directory" on target "Item: C:\Temp\WPF Destination: D:\temp\WPF".

注释#2-没有错误检查。如果目的地已经有一个同名目录,这将为您提供许多红色错误文本。

注释#3-也没有未找到目录的记录。 [咧嘴]

相关问题