【问题标题】:How do I get a file path without filename in PowerShell?如何在 PowerShell 中获取没有文件名的文件路径?
【发布时间】:2022-04-27 14:56:46
【问题描述】:

我在一个名为$file的变量中有C:\Temp\MyFolder\mytextfile.txt

我希望 C:\Temp\MyFolder\ 在另一个变量中。

【问题讨论】:

标签: powershell-2.0


【解决方案1】:

Extract the filename from a path

您可以使用:

   $file.psobject.properties

   $file | get-member -membertype properties

您可以在那里获得不同形式的结果:

   $file.PSParentPath
   $file.Directory
   $file.DirectoryName

或使用

   $file | Select-object DirectoryName

   $file | select DirectoryName

(您可以在 DirectoryName 之前添加 -ExpandProperties 以将输出作为基本属性类型,此处为 String)

【讨论】:

    【解决方案2】:

    这很简单 你可以使用这段代码来做到这一点:

    • 如果您想从 $file 变量中提取文件路径:

      $file = 'C:\Temp\MyFolder\mytextfile.txt'
      
      $myFilePath = Split-Path $file -Parent
      
      $myFilePath = $myFilePath+'\'
      
      Write-Host $myFilePath
      
    • 如果你只想提取文件名,那么,

      $file = 'C:\Temp\MyFolder\mytextfile.txt'
      
      $myFileName = Split-Path $file -leaf
      
      Write-Host $myFileName
      

    我知道这是一个老问题,但仍然, 如果您觉得此答案有帮助,请将其标记为已接受,谢谢您快乐编码:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      相关资源
      最近更新 更多