Reputation: 11
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!"
}
}
Upvotes: 0
Views: 570
Reputation: 37830
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
Upvotes: 4