Creating folders and moving files in powershell

2019-10-09 16:47发布

I have a folder with thousands of files (let's say .txt) with different names: VBH_V001.txt VDD_V001.txt DTG_V001.txt ADC_V001.txt DFD_V001.txt etc....

I need to create directories in that folder with the name of each file and then move those files to directories. The result should be for example Folder with the the name VBH (without _V001.txt) and in that folder I should have VBH_V001.txt file. How can I do that. Please advise.

标签: powershell
2条回答
啃猪蹄的小仙女
2楼-- · 2019-10-09 17:14
cd <path to your folder>
  $files = Get-ChildItem -file;
  ForEach ($file in $files)
  {
    $folder = New-Item -type directory -name $file.BaseName;
    Move-Item $file.FullName $folder.FullName;
  }

This script creates a directory for each file and moves the file to this directory. To exclude _V001 from the directory name, you can call the TrimEnd method on $file.BaseName -

$file.BaseName.TrimEnd ("_V001")

Step by step.

  1. First of all, go to the directory that contains your files.
  2. Get a list of objects that represent your files by using the Get-ChildItem cmdlet with the -file attribute. These objects contain properties - such as BaseName, FullName, and so on.
  3. Save this list to the $files variable.
  4. Loop through the list with ForEach.
  5. In the ForEach body, create a directory for each file with the New-Item cmdlet. The -type attribute specifies the type for the new item (-type directory), for the -name attribute substitute the $file.BaseName property. BaseName property returns a string with the name of the file without the extension and path.
  6. Save the object of the newly created directory into the $folder variable.

  7. Move the file using the Move-Item cmdlet. This cmdlet requires two attributes: source path and destination path. As the source path, use the FullName property of the file object, and the FullName property of the directory object for the destination path. FullName property returns the name of the file or directory that contains the full path, for example D:\directory\file.txt for a file and D:\directory\anotherDirectory for a directory.

It's not a big deal, actually, and without shortcuts it looks like a plain English.

查看更多
甜甜的少女心
3楼-- · 2019-10-09 17:15

What you basically need to do, is to:

  1. Get a list of files in a selected folder through PowerShell.
  2. Create new folders in a loop by using the New-Item cmdlet which have name made by using substring of a name of a selected file.
  3. For each of the files, move the file to the new location, using the Move-Item cmdlet.

Hope that helps.

查看更多
登录 后发表回答