繁体   English   中英

如何在不知道文件名称的情况下在 powershell 中获取文件的完整路径?

[英]How can I get the full path to a file in powershell without knowing its name?

我在子目录中有一个文件。 如何在不知道其名称的情况下获取该文件的完整路径? 注意,我知道这个目录中永远只有一个文件。

这是一个 MWE:

cd D:
mkdir directory1
cd directory1
mkdir directory2
cd directory2
notepad file.txt # save when prompted and close
cd ..
PS D:\directory1> ls


    Directory: D:\directory1


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        20/11/2020     14:04                directory2


PS D:\directory1>

在 bash 我会做这样的事情:

$ my_file=$(ls directory2)
$ echo "$my_file"

在powershell中,我正在尝试

# error
Set-Variable -name my_file -value (Resolve-Path -LiteralPath (get-item (ls dist))
          

我希望我的输出看起来像这样:

# powershell
$my_file
D:\full\path\to\directory1\directory2\file.txt
  • 很少需要Set-Variable 使用直接赋值更简单,但请注意,PowerShell 与 Bash 不同,在这种情况下也使用$符号: $my_file = ... (注意$=周围允许有空格,而不是 Bash 的my_file=...

  • 如果您只对完整路径字符串感兴趣,那么使用Convert-Path是最简单的。

$my_file = Convert-Path directory2/*  # Note: could return an *array* of paths

相比之下,如果您想要稍后可以查询其.FullName属性的文件信息对象,请使用Get-ChildItem

$my_file = Get-ChildItem directory2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM