2015-09-12 67 views
1

我會進入這個快速,基本上,我試圖讓這個函數的輸出被髮送到一個文件中。該文件創建時沒有問題,但始終爲0字節。這不是通過傳遞信息,我不明白爲什麼。PowerShell的輸出文件無法填充文件

第一次嘗試

function Get-MD5{ 
<# 
.Synopsis 
MD5 file hasher 
.Description 
Generates the MD5 hash of a file you feed in. 
.Example 
Get-MD5 -FilePath c:\windows\system32\cmd.exe 
#> 
Param(
    [Parameter(Mandatory=$True)] 
    [string]$FilePath = "C:\Windows\system32\cmd.exe" 
) 
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider 
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($FilePath))).Replace('-', '') 
Write-Host `nFile: $FilePath`nMD5: $hash`n | Out-File -FilePath "D:\AyyInfo\ MD5-%computername%-$(((get-date).ToUniversalTime()).ToString("ddMMyyyy_hhmmss")).txt" 
} 

第二次嘗試

function Get-MD5{ 
<# 
.Synopsis 
MD5 file hasher 
.Description 
Generates the MD5 hash of a file you feed in. 
.Example 
Get-MD5 -FilePath c:\windows\system32\cmd.exe 
#> 
Param(
    [Parameter(Mandatory=$True)] 
    [string]$FilePath = "C:\Windows\system32\cmd.exe" 
) 
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider 
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($FilePath))).Replace('-', '') 
Write-Host `nFile: $FilePath`nMD5: $hash`n > "D:\AyyInfo\ MD5-%computername%-$(((get-date).ToUniversalTime()).ToString("ddMMyyyy_hhmmss")).txt" 
} 

最後一次嘗試

function Get-MD5{ 
<# 
.Synopsis 
MD5 file hasher 
.Description 
Generates the MD5 hash of a file you feed in. 
.Example 
Get-MD5 -FilePath c:\windows\system32\cmd.exe 
#> 
Param(
    [Parameter(Mandatory=$True)] 
    [string]$FilePath = "C:\Windows\system32\cmd.exe" 
) 
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider 
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($FilePath))).Replace('-', '') 
Out-File -FilePath "D:\AyyInfo\ MD5-%computername%-$(((get-date).ToUniversalTime()).ToString("ddMMyyyy_hhmmss")).txt" 
} 

任何幫助將非常感激。

回答

1

你需要管你的變量$hashout-file cmdlet的內容:

"$filepath`t$hash" | out-file "D:\AyyInfo\MD5-$($env:computername)-$(((get-date).ToUniversalTime()).ToString("ddMMyyyy_hhmmss")).txt" 

我已經建立使用環境變量實際的計算機名稱的字符串以正確的方式改變了%computername%

在除了缺少你的變量的管導致其強制輸出只到控制檯和其他地方你不能使用該cmdlet寫入主機的兩個第一代碼。

+0

這就是我在第一個例子中所做的,雖然正確嗎?我的意思是,'n只是爲了讓輸出在控制檯中更清晰可見,我現在已經刪除了它們,但它仍然會創建空白文件。並感謝更改計算機名的事情,我不知道那一個要麼但在我的防守,也沒有做什麼尋找到它尚未:d – Sevaara

+0

我回去,並意識到你在說,工程。任何想法如何強制換行到文件中?現在它只是將兩個變量都放在一行中,沒有格式。 – Sevaara

+0

第一個例子有一個管道,但它也輸出到主機,我認爲可能是一個問題。我將只寫兩行。 – Sevaara