Powershell - 引用文件名字符串的一部分

时间:2018-03-26 18:02:59

标签: powershell

我正在尝试提取文件名的第一部分,然后使用powershell移动到相应的文件夹。文件名看起来像" X02348957 RANDOM WORDS HERE" - 我试图让PowerShell只看X02348957。 X#也是不同的长度,所以我不能根据位置变量来做(就像读取左边8个空格的所有数字 - 赢得的数字总是8个空格)。 / p>

到目前为止,我的代码正在进行中;

# 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!"
  }

}

1 个答案:

答案 0 :(得分:4)

如果我理解了这个问题,那么:

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

如果您觉得需要使用正则表达式:

$wFile -match '^(?<FirstPart>x\d+)'
$firstPart = $matches.FirstPart
相关问题