Powershell:从$ file.Fullname中减去$ pwd

El *_*ldo 5 powershell split path

给出以下文件:

c:\dev\deploy\file1.txt
c:\dev\deploy\file2.txt
c:\dev\deploy\file3.txt
c:\dev\deploy\lib\do1.dll
c:\dev\deploy\lib\do2.dll
Run Code Online (Sandbox Code Playgroud)

例如,如果$ pwd如下

c:\dev\deploy
Run Code Online (Sandbox Code Playgroud)

运行声明

$files = get-childitem
Run Code Online (Sandbox Code Playgroud)

我想取这个列表并使用foreach ($file in $files)我想替换我自己的路径,$pwd例如我想打印c:\temp\files如下:

c:\temp\files\file1.txt
c:\temp\files\file2.txt
c:\temp\files\file3.txt
c:\temp\files\lib\do1.dll
c:\temp\files\lib\do2.dll
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做呢

A = c:\dev\deploy\file1.txt - c:\dev\deploy\
B = c:\temp\files\ + A

giving B = c:\temp\files\file1.txt
Run Code Online (Sandbox Code Playgroud)

ste*_*tej 6

我会在这里使用过滤器并考虑像这样管道文件:

filter rebase($from=($pwd.Path), $to)  {
    $_.FullName.Replace($from, $to)
}
Run Code Online (Sandbox Code Playgroud)

你可以这样称呼它:

Get-ChildItem C:\dev\deploy | rebase -from C:\dev\deploy -to C:\temp\files\
Get-ChildItem | rebase -from (Get-Location).path -to C:\temp\files\
Get-ChildItem | rebase -to C:\temp\files\
Run Code Online (Sandbox Code Playgroud)

请注意,替换区分大小写.


如果您需要不区分大小写的替换,正则表达式会有所帮助:( 根据Keith的评论编辑.感谢Keith!)

filter cirebase($from=($pwd.Path), $to)  {
    $_.Fullname -replace [regex]::Escape($from), $to
}
Run Code Online (Sandbox Code Playgroud)

  • -replace运算符允许使用不区分大小写的正则表达式,例如`$ _.Fullname -replace [regex] :: escape($ from),$ to` (2认同)

小智 1

有一个 cmdlet,Split-Path-leaf选项为您提供文件名。还有Join-Path,所以你可以尝试这样的事情:

dir c:\dev\deploy | % {join-path c:\temp\files (split-path $_ -leaf)} | % { *action_to_take* }
Run Code Online (Sandbox Code Playgroud)