Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
961 views
in Technique[技术] by (71.8m points)

Creating folders and moving files in powershell

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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:directoryfile.txt for a file and D:directoryanotherDirectory for a directory.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...