2010-02-12 68 views
3

鑑於以下文件:

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 

例如如果$ PWD是以下

c:\dev\deploy 

運行

$files = get-childitem 

我想利用這個列表中的語句和使用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 

我怎麼能這樣[執行即

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

giving B = c:\temp\files\file1.txt 

回答

3

這裏有一個cmdlet,拆分路徑,-leaf選項爲您提供文件名。還有聯接路徑,所以你可以嘗試這樣的事:

dir c:\dev\deploy | % {join-path c:\temp\files (split-path $_ -leaf)} | % { *action_to_take* } 
1

如何像:

function global:RelativePath 
{ 
    param 
    (
     [string]$path = $(throw "Missing: path"), 
     [string]$basepath = $(throw "Missing: base path") 
    ) 

    return [system.io.path]::GetFullPath($path).SubString([system.io.path]::GetFullPath($basepath).Length + 1) 
}  

$files = get-childitem Desktop\*.* 

foreach($f in $files) 
{ 
    $path = join-path "C:\somepath" (RelativePath $f.ToString() $pwd.ToString()) 
    $path | out-host 
} 

我帶着簡單的相對路徑從here雖然有一些問題,但你只需要處理以下工作目錄路徑,它應該沒問題。

6

我會在這裏使用過濾器和管道考慮這些文件是這樣的:

filter rebase($from=($pwd.Path), $to) { 
    $_.FullName.Replace($from, $to) 
} 

你可以這樣調用:

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\ 

注意,更換是區分大小寫的。


如果你需要區分大小寫替換,正則表達式將有助於:(!基於基思的評論編輯感謝基思

filter cirebase($from=($pwd.Path), $to) { 
    $_.Fullname -replace [regex]::Escape($from), $to 
} 
+2

的-replace運算允許不區分大小寫例如正則表達式的使用'$ _。Fullname -replace [regex] :: escape($ from),$ to' – 2010-02-12 17:23:37

+0

哦,我總是會學到一些新東西。謝謝! ;) – stej 2010-02-12 17:59:14

2

這工作得很好,對我來說:

gci c:\dev\deploy -r -name | %{"c:\temp\$_"}