使用PowerShell创建部分字符串匹配和文件夹

时间:2016-10-26 20:55:05

标签: string powershell pdf copy

我有一个包含数千个文件的目录,我想根据部分文件名创建新目录,然后将部分匹配文件排序到这些目录中。

这些文件都以相同的前缀开头," 123 - ",然后数字随机且长度不等,但我不想要数字之后的任何内容。我尝试了正则表达式,但是我遇到了在" 123之后匹配不同数字长度的问题 - "并在中间数字后跳过所有内容。

class MyMainClass
{
private:
    std::vector<MySecondaryClass> _secClassVec;
public:
    MyMainClass() {}
    ~MyMainClass() {}

    size_t addNewSecClass(int aValue) {
        MySecondaryClass newSecClass(aValue);
        _secClassVec.push_back(newSecClass);
        return _secClassVec.size() - 1;
    }

    const MySecondaryClass& operator [](size_t idx) const
    {
        return _secClassVec[idx];
    }
};


int main() {

    MyMainClass mainObject;

    size_t secObject1_idx = mainObject.addNewSecClass(1);
    size_t secObject2_idx = mainObject.addNewSecClass(2);
    size_t secObject3_idx = mainObject.addNewSecClass(3);

    std::cout << mainObject[secObject1_idx].aValue << std::endl;
    std::cout << mainObject[secObject2_idx].aValue << std::endl;
    std::cout << mainObject[secObject3_idx].aValue << std::endl;

    return 0;
}

2 个答案:

答案 0 :(得分:0)

PS C:\> '123-4441Zebra.pdf' -replace '(123-\d+).*', '$1'
123-4441

e.g。

gci "c:\place\" | mv -Dest { "c:\out\$($_.Name -replace '(123-\d+).*', '$1')\" } -Force -WhatIf

自我生成的PS帮助链接来自我的代码块(如果有):

  • gciGet-ChildItem的别名(在模块Microsoft.PowerShell.Management中)
  • mvMove-Item的别名(在模块Microsoft.PowerShell.Management中)

答案 1 :(得分:0)

试试这个:

 $yourdir="C:\temp\root"
 gci $yourdir -File -Filter 123-*.pdf | %{$newdir=$yourdir + "\" + ($_.Name -replace '(123-\d+).*', '$1'); New-Item -Path $newdir -Force -ItemType Directory; Move-Item -Path $_.FullName -Dest $newdir -Force }