0

I am trying to extract the first part of a file name, then move to a corresponding folder with powershell. The filename looks something like "X02348957 RANDOM WORDS HERE" - I'm trying to get powershell to only look at the X02348957. The X#'s are also different lengths, so I can't just do it based on a location variable (like read everything 8 spaces to the left - the number won't always be eight spaces).

Here is my code in progress so far;

# Retrieve list of files
# $sDir = Source Directory
$sDir = "U:\Test\"

# Generate a list of all files in source directory
$Files = (Get-ChildItem $sDir)

# $tDir = Root Target Directory
$tDir = "N:\USERS\Username\General\Test\"

# Loop through our list of file names
foreach($File in $Files)
{
# $wFile is the working file name
$wFile = $File.BaseName

# Here is where the code to make it only move based on the first part of file name would go (the X#)?



# dFold = the destination folder in the format of \\drive\folder\SubFolder\    
$dFold = "$tDir$wFile"

# Test if the destination folder exists
if(Test-Path $dFold -PathType Container)
  {
  # If the folder exists then move the file
  Copy-Item -Path $sDir$File -Destination $dFold

  # Denote what file was moved to where        
  Write-Host $File "Was Moved to:" $dFold
  Write-Host
  }
  # If the folder does not exist, leave file alone
  else 
  {
  # Denote if a file was not moved
  Write-Host $File "Was not moved!"
  }

}
4
  • You could use a regular expression on the name of the file. Something like "X\d+" will match an X followed by any number of numbers or digits Commented Mar 26, 2018 at 18:16
  • But then you have two problems Commented Mar 26, 2018 at 18:20
  • @EBGreen ha ha you and regex... best buddies aren't you Commented Mar 26, 2018 at 18:35
  • I actually enjoy them...just only when they are needed. Commented Mar 26, 2018 at 18:39

1 Answer 1

4

If I understand the issue, then:

$firstPart = $wFile.Split(' ')[0]

If you feel the need to use a regex:

$wFile -match '^(?<FirstPart>x\d+)'
$firstPart = $matches.FirstPart
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I will try this. I had looked into splitting but I was struggling to understand exactly how to split the filename. Edit: It worked perfect, thank you so much!
Not a huge deal but split with nothing supplied will split on space $wFile.Split()[0]
Is there a speed or reliability difference? Or is it just a matter of not typing the three extra characters and being less explicit in the code?
@Matt - That splits on all whitespace (including a tab for instance) which is not the same as splitting on space.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.