Powershell - 文本行中的最后两个字符

Powershell - last two characters in the text line

如果有人指出正确的方向,我将不胜感激。

任务 ----------

  1. 拆分字符串并将文件夹路径(注意路径中的空格)分配给不同的变量。

  1. 从文本文件中获取行并提取最后 2 个字符,忽略文件夹路径和分配的驱动器号之间的空格。

文本文件示例----------

\FileServer\movetest\somefiles Z:
\FileServer\mogul 移动 OUT\anotherfiles Y:

尝试编码------------ 1)

 $getDriveLines = gc -Path $inputFile    

foreach( $_ in $getDriveLines)                                                                    { 
   [stringsplitoptions]$option = "removeEmptyEntries" $oldFILEPath = $_.split(" ",$option)[0]
   Write-Host ("Old FS path is ") $oldFILEPath

   $constantFILEDriveLetter = $_.split(" ",$option)[1]
   Write-Host ("Constant FS Letter is ") $constantFILEDriveLetter }

问题 ---------- 请注意,它拆分文件夹路径(第 3 行)并在输出的最后一行显示“文件夹路径”部分而不是驱动器号。

      Old FS path is  \FileServer\movetest\somefiles

常量 FS 字母为 Z: 旧的 FS 路径是 \FileServer\mogul 常量 FS 字母为 MOVE

)

$getDriveLines = gc -Path $inputFile

  foreach( $Line in $getDriveLines)

{

$值 = $Line.Substring($Line.Length - 2)

 }

问题 ---------- 它显示以下内容,请注意第二行“Z:”没有显示值

   \\FileServer\movetest\somefiles          Z:  
     The value is -  
   \\FileServer\mogul MOVE OUT\anotherfiles Y:

值为 - Y:

是否被覆盖?此代码缺少什么?

  • .Split().NET 方法没有简单的解决方案,它在文字上运行分隔符字符串,但使用基于 regex-split operator 可以实现简洁的解决方案 - 见下文。

  • 您的 .Substring() 方法 - $value = $Line.Substring($Line.Length - 2) 获取驱动器规格。 - 可能仅受输入文件第一行中的 尾随空格 的阻碍,您可以按如下方式轻松修复:

    $getDriveLines = (gc -Path $inputFile).Trim()
    

PowerShell (Core) 7+ 中有一个简单的解决方案,使用带有 negative 令牌计数的 -split operator , 具体来说 -2:

(Get-Content $inputFile).Trim() | ForEach-Object {
  $path, $drive = $_ -split ' +', -2
  # Sample output
  [pscustomobject] @{
    Path = $path
    Drive = $drive
  }
}
  • Regex ' +' 匹配一个或多个 (+) 个空格 (' ').

  • -2 告诉 -split 到 return 最多 2 个令牌 从最后,因为数字是负数。这导致拆分仅在输入字符串中的 last 运行 空格处有效执行,因此驱动器规范之前的路径。最后保留 as-is,即使它也包含空格。

输出:

Path                                       Drive
----                                       -----
\FileServer\movetest\somefiles          Z:
\FileServer\mogul MOVE OUT\anotherfiles Y:

Windows PowerShell 中,不支持负令牌计数,简洁的解决方案有点复杂:

(Get-Content $inputFile).Trim() | ForEach-Object {
  $path, $drive = $_ -split ' +(?=[a-z]:$)'
  # Sample output
  [pscustomobject] @{
    Path = $path
    Drive = $drive
  }
}
  • 这里也确保输入字符串仅被 last 运行 空格分割,通过使用(正)look-ahead 断言 ((?=...)) 仅匹配 运行 个空格 (' +'),前提是它后跟与驱动器规格匹配的子表达式。 ([a-z]:) 在字符串的末尾 ($).

您的 post 难以阅读,但阅读您的标题我可能有一个脚本可以帮助您

foreach ( $line in (Get-Content -Path $inputFile)) { 
   $oldFILEPath = $line.Substring(0,$line.length -3)
   $constantFILEDriveLetter = $line.Substring($line.length -2, 2)

   Write-Output "Old FS path is `"$oldFILEPath`""
   Write-Output "Constant FS letter is $constantFILEDriveLetter`r`n"
}

结果看起来像

Old FS path is "\FileServer\movetest\somefiles"
Constant FS letter is Z:

Old FS path is "\FileServer\mogul MOVE OUT\anotherfiles"
Constant FS letter is Y:

我向“An-dir”和“mklement0”致歉post。但是,是的,问题在于臭名昭著的尾随空格。感谢您花时间和精力检查我的 post 并提出您的想法。