windows - 如何从 PowerShell 中的 dir 命令中删除当前路径?

标签 windows powershell directory ls

当我在Powershell中输入dir命令时,它总是显示当前路径+一些空行,这确实没有必要。我想设置一个别名来从结果中删除当前路径。但是我可以使用什么命令/属性来删除该路径?我在互联网或 dir 的手册页上找不到任何内容。

我使用 Powershell 7.2.1,并且是 PS 新手。

最佳答案

首先,我认为提及 7.2.1 会让人们不敢回答你的问题。许多人,比如我自己,目前仍使用 5.x。如果我知道如何将 7.x 安装到 WinPE,我可能会进行切换。我可能是错的,但这似乎是一个问题。

其次,Dir 在 PowerShell 中是 Get-ChildItem 的别名。 看这个List of Compatibility Aliases

第三,您需要查看Working with Files and Folders , Get-ChildItem ,和Get-Item .

第四,PowerShell中的一切都是对象。因此,您在 Dir 中看到的所有额外行实际上并不是由 Dir 创建的,它们正在格式化 PowerShell 粘贴在那里的绒毛,以使其可读。 PowerShell 获取 Dir/Get-ChildItem 返回的对象并尝试使它们对您来说更漂亮,但是当您直接使用这些对象时,所有额外的内容都不存在。当您开始使用管道时,请记住这一点,它只是一次将一个对象送入管道的一组对象。

第五,PowerShell 5.x 及更新版本的所有版本都有相当多的重叠,因此理论上,如果我足够细心,我为您提供的 5.x 代码应该可以在 7.x 中运行。如果我犯了一个错误,我想很抱歉 - 我尝试过!

在此代码中:

  1. 轮流注释和取消注释顶部附近的“Objects =”行。
  2. 记下注释掉的“$_ | Format-List -Property *”。如果取消注释它,它将生成输入管道的对象中所有属性的长输出。您可以使用它来查看我主要如何访问这些对象来设置变量。
  3. 注意代码中 SubString 的使用。我很难证明 SubString 在 PowerShell 核心中可用,但如果是的话,它是一个可用于将路径分解为多个部分的工具。另一个工具是Split-Path ,所以你可能想研究一下。
  4. 如果您有所需的单个文件的确切名称,请在下面的代码中将 *.ps1 替换为该确切名称。或者在许多命令中将\FileName.ext 添加到路径末尾即可。
  5. 此代码在 Windows 中运行良好,但在其他操作系统中您可能需要进行调整。
#   Uncomment only one of the following lines at a time:
#$Objects = Get-ChildItem -Path $Home -File                 #   Gets files in home path
#$Objects = Get-ChildItem -Path $Home -Directory           #   Gets Directories in home path
#$Objects = Get-ChildItem -Path $PSScriptRoot -File        #   Gets files in same folder as the script
#$Objects = Get-ChildItem -Path $PSScriptRoot -Directory   #   Gets Directories in same folder as the script
$Objects = Get-ChildItem -Path "$Home\Documents" -File
#$Objects = Get-ChildItem -Path "$PSScriptRoot\*.ps1" -File
#$Objects = Get-Item -Path "$PSScriptRoot\*.ps1"

$Objects  | ForEach-Object {    #   Get files
    #$_ | Format-List -Property *

    $f =$_.FullName                     #   Get full path name
    $d = "$($_.PSDrive):\"     #   Get the drive
    $dp = $_.DirectoryName              #   Get drive and path
    $p = $dp.SubString($d.Length)       #   Get path only
    $n = $_.BaseName                    #   Get file name only
    $x = $_.Extension                   #   Get file extension only
    $nx = $_.Name                       #   Get files name and extension
    
    Write-Host
    Write-Host "f: $f"
    Write-Host "dp: $dp, nx: $nx"
    Write-Host "d: $d, p: $p, n: $n, x: $x"
}

关于windows - 如何从 PowerShell 中的 dir 命令中删除当前路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71191073/

相关文章:

c++ - 我应该安装什么才能在 C++ 中使用命名空间 Windows::Devices?

c++ - 您如何以编程方式检测 Windows 上的蓝屏死机在重启后刚刚发生?

string - 如何在Powershell中两次评估字符串

azure - 如何将 azure cli list 命令的值获取到变量中?

docker - 从派生的 docker 镜像在特定/home 文件夹中创建文件夹不起作用

javascript - 在 HTML 中创建循环以自动从目录加载图片

javascript - 像exe一样在Windows窗口中运行HTML页面

arrays - 使用两个数组创建注册表项/值

powershell - 从 PowerShell 窗口启动 .exe 有时会导致它在单独的窗口中运行,所以我看不到输出或获取 $lastexitcode

c++ - 文件或目录 _findfirst C++