簡體   English   中英

將Powershell輸出管道到文本文件

[英]Piping Powershell output to a text file

我有以下Powershell腳本,該腳本使用順序的文件名將文件從一個位置重命名為另一個位置。 最終,這些文件更改需要映射,就像原始的一樣-新建。 當前,我只有一個Write-Host cmdlet,我只是將cmd Windows輸出復制到txt文件中,然后通過編寫的python腳本運行,以將原始文件和重命名的文件吐出為excel文件。 我想知道在最初的ps腳本中是否有更簡單的方法來做到這一點。 即使制表符分隔的內容也可以輕松地復制粘貼到excel文件中。

Set-Location -Path "C:\Users\mmcintyre\Desktop\grail_new"
$destLoc = "C:\Users\mmcintyre\Desktop\renamed"
$countRef = [ref] 0
Get-ChildItem -Filter *.pdf -Recurse |
   Copy-Item -WhatIf -Destination { '{0}\{1}.pdf' -f $destLoc,++$countRef.Value }

任何幫助將不勝感激。

編輯:我目前正在使用PS 2.0。

除了復制操作( PSv3 +語法)之外,以下輸出舊名稱/新名稱對到TSV文件的操作:

$countRef = [ref] 0
Get-ChildItem -Filter *.pdf -Recurse | ForEach-Object {
  $newFullName = '{0}\{1}.pdf' -f $destLoc, ++$countRef.Value
  Copy-Item -WhatIf -LiteralPath $_.FullName -Destination $newFullName
  [pscustomobject] @{
    Old = $_.FullName
    New = $newFullName
  }
} | Export-Csv -Delimiter "`t" NameMappings.tsv

這將創建一個TSV(制表符分隔的值)文件,其文件名為OldNew列分別包含舊的和新的完整文件名。


PSv2 :v2中沒有用於從哈希表創建自定義對象的[pscustomobject] @{ ... }語法糖,因此必須使用New-Object

$countRef = [ref] 0
Get-ChildItem -Filter *.pdf -Recurse | ForEach-Object {
  $newFullName = '{0}\{1}.pdf' -f $destLoc, ++$countRef.Value
  Copy-Item -WhatIf -LiteralPath $_.FullName -Destination $newFullName
  New-Object PSCustomObject -Property @{
    Old = $_.FullName
    New = $newFullName
  }
} | Export-Csv -Delimiter "`t" NameMappings.tsv

警告-Property接受哈希表 [1] ,這意味着不能保證其鍵順序,因此,所得對象的屬性順序通常不會反映輸入順序-在這種情況下,它恰好這樣做。

如果生成的屬性順序不理想,則有兩個選擇:

  • 緩慢但方便:以所需順序插入具有屬性的Select-Object調用(例如Select-Object Old, New )。

  • 更為麻煩:首先將對象構造為空,然后創建New-Object PSCustomObject ,然后通過各個Add-Member調用按所需順序逐一附加屬性。


[1] PSv3 + [pscustomobject] @{ ... }語法似乎也是基於哈希表的,但是它以保留鍵順序的方式進行解析。 即,就像您隱式使用了[ordered] @{ ... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM