[英]Powershell - Referencing part of file name string
I am trying to extract the first part of a file name, then move to a corresponding folder with powershell. 我正在尝试提取文件名的第一部分,然后使用powershell移至相应的文件夹。 The filename looks something like "X02348957 RANDOM WORDS HERE" - I'm trying to get powershell to only look at the X02348957. 文件名看起来像“ X02348957 RANTER WORDS HERE”-我正在尝试使Powershell只查看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). X#的长度也不同,因此我不能仅基于位置变量来执行此操作(例如读取所有内容到左侧的8个空格-该数字并不总是8个空格)。
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!"
}
}
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.