2017-05-16 33 views
-3

我正在使用Get-ChildItem瀏覽目錄,以便將文件路徑記錄到文本文件。但是,我想根據我是否位於特定文件夾中來動態創建文本文件。例如,讓我們說這是我的文件結構:如何在PowerShell腳本中動態知道位置

+--Root 
    +--LaunchFromHere 
     +--File1 
     +--file_I_want1.doc 
     +--File2 
     +--file_I_want2.doc 

如果我的腳本在LaunchFromHere開始,我要遍歷文件1和文件2遞歸,最終到達file_I_want.doc的。但是,我想將它們的文件路徑記錄在不同的.txt文件中,每個文件都帶有我找到的文件的名稱。因此,當我找到file_I_want1.doc時,它的文件路徑將被記錄在名爲File1.txt的文本文件中。

這是我的問題:我找不到如何獲取我目前在腳本中的文件的文件名。

根據網站上的類似的問題,這是我的代碼:

$invocation = (Get-Variable MyInvocation).Value 
$directorypath = Split-Path $invocation.MyCommand.Path 
$file_title = $directorypath.split('\')[-1]  

Get-ChildItem -include *.doc, -recurse | Select -Expand FullName | 
     ForEach-Object { 
      $invocation = (Get-Variable MyInvocation).Value 
      $directorypath = Split-Path $invocation.MyCommand.Path 
      $file_title = $directorypath.split('\')[-1] 
      "----- 
      "Directory path: `t" + $directorypath 
      "Current file: `t`t" + $file_title 
      "----" 
     } 

我的輸出永遠只能顯示在我運行腳本的文件路徑,因此在這種情況下:

PS C:\Root\LaunchFromHere 
---- 
Directory path: C:\Root\LaunchFromHere 
Current file:  LaunchFromHere 
--- 

而我的.txt的標題始終是LaunchFromHere.txt 編輯:我刪除了Out-File,但我確實希望將結果保存到文本文件。

那麼,如何獲得我在執行腳本期間遍歷的文件的當前名稱?

+4

這顯然是不可能的,你發佈的代碼給你的輸出,因爲'出File'終止您的管道。你永遠不會去'ForEach-Object'。 –

+0

你是對的,在我的原始代碼中,我有其他的打印語句打印出來的結果,我沒有簡單地加入。儘管如此,在刪除了「Out-File」的情況下,我得到的輸出仍然是我所描述的。 – gsamerica

+0

爲了擴充我的評論,我的意思是說我的個人代碼中沒有包含的打印語句是我儘管輸出文件仍然收到的輸出的原因。但是,在刪除了註釋和Out-File之後,我仍然得到了我所描述的輸出。 – gsamerica

回答

0

下面的代碼片段可以幫助:

Push-Location "C:\Root\LaunchFromHere" 
Get-ChildItem -include *.doc -recurse | 
    ForEach-Object { 
     $directorypath = $_.DirectoryName 
     $file_title = $_.Name 
     ( "-----", 
      "Directory path:`t$directorypath", 
      "Current file: `t$file_title", 
      "---" 
     ) | Out-File "$(Join-Path $directorypath "$($_.BaseName).txt")" 
    } 
Pop-Location 

這樣可以節省例如file_I_want1.txt在同一目錄下,其中file_I_want1.doc文件位於:

PS D:\PShell> Get-Content C:\Root\LaunchFromHere\File1\file_I_want1.txt 
----- 
Directory path: C:\Root\LaunchFromHere\File1 
Current file: file_I_want1.doc 
--- 
PS D:\PShell> 
相關問題