2014-10-17 60 views
0

嘿,我有一個Powershell 2.0問題,讓我發瘋。我的目標是:創建一個腳本,用於確定Documents文件夾的大小以及同一行上的當前用戶,但在csv文件的兩個不同字段中。我曾嘗試以下腳本至今:在Powershell中將多個變量傳遞給Export-CSV

$startFolder= "C:\Users\$env:username\Documents" 
$docinfo = Get-ChildItem $startFolder -recurse | Measure-Object -property length -sum | 
$docinfo | Export-Csv -Path C:\MyDocSize\docsize.csv -Encoding ascii -NoTypeInformation 

這個腳本工程和出口文件夾的大小(總和),某些列,我不需要,「平均值,最大值,最小值一起,和一個屬性欄「長度」作爲一個值。有誰知道如何顯示總和列和其他的東西嗎?我的主要問題是,如何將「$ env:username」傳遞到「$ docinfo」然後獲取?「$文檔信息」,以傳遞到CSV作爲附加列和同一行的測量值的附加價值

我嘗試這樣做:

$startFolder= "C:\Users\$env:username\Documents" 
$docinfo = Get-ChildItem $startFolder -recurse | Select-Object $env:username 
$docinfo | Export-Csv -Path C:\MyDocSize\docsize.csv -Encoding ascii - NoTypeInformation 

這將只傳遞當前用戶名到CSV文件,但沒有列名,然後我不知道如何將測量值與此結合。此外,我甚至不知道爲什麼這會通過用戶名,因爲如果我把「Get-ChildItem $ startFolder -recurse」出來,它將停止工作。

我也試過這個腳本:

$startFolder= "C:\Users\$env:username\Documents" 
$docinfo = Get-ChildItem $startFolder -recurse | Measure-Object -property length -sum 
New-Object -TypeName PSCustomObject -Property @{ 
UserName = $env:username 
DocFolderSize = $docinfo  
} | Export-Csv -Path C:\MyDocSize\docsize.csv -Encoding ascii -NoTypeInformation 

該腳本將很好地傳遞用戶名與「用戶名」的列名,但在「DocFolderSize」一欄,而不是測量值我得到這個的字符串:Microsoft.PowerShell.Commands.GenericMeasureInfo

不知道現在該做什麼或如何解決這個問題,我會非常感謝任何幫助!謝謝閱讀。

回答

1

試試這個」

Get-ChildItem $startFolder -Recurse | Measure-Object -property length -sum | Select Sum, @{Label="username";Expression={$env:username}} 

@{Label="username";Expression={$env:username}}將讓您設置自定義列標題和值

您可以使用相同的技術定製總和列:

Get-ChildItem $startFolder -Recurse | Measure-Object -property length -sum | Select @{Label="FolderSize";Expression={$_.Sum}}, @{Label="username";Expression={$env:username}} 

如果你想顯示MB文件夾的大小:

Get-ChildItem $startFolder -Recurse | Measure-Object -property length -sum | Select @{Label="FolderSize";Expression={$_.Sum/1MB}}, @{Label="username";Expression={$env:username}} 
+0

謝謝!這工作,但是如果我只是選擇總和它出口到csv作爲「@ {總和= 10915869}」我怎麼才能得到這個數字?非常感謝你的幫助。 – 2014-10-17 18:08:29

+0

沒關係,只是當我用我的對象嘗試它時才顯示出來, 「$ startFolder =」C:\ Users \ $ env:username \ Documents「 Get-ChildItem $ startFolder -Recurse | Measure-Object -property length -sum | Select Sum,@ {Label =「username」; Expression = {$ env:username}} | Export-Csv -Path C:\ MyDocSize \ info.csv \ MyDocSize \ info.csv -Encoding ascii -NoTypeInformation「 這工作完美,比我有更簡單的。謝謝,非常感謝! – 2014-10-17 18:20:11

+0

但是,還有一個問題,我如何自定義Sum列名稱? 「Get-ChildItem $ startFolder -Recurse | Measure-Object -property length -sum | @ {Label =」MyDocSize「; Expression = {Select Sum}},@ {Label =」username「; Expression = {$ env:username }} | Export-Csv -Path C:\ MyDocSize \ info.csv -Encoding ascii -NoTypeInformation「 拋出」僅允許將表達式作爲管道的第一個元素「錯誤 – 2014-10-17 18:23:30