我有個問題:
我需要用戶輸入稍后將使用的路徑(檔案),但我收到此錯誤:
我的問題是該檔案夾中有檔案,但我只需要輸入檔案夾的路徑:
輸入應該是:
C:\Users\USER1\Desktop\test\files
我需要將該路徑放入變數 $Source_UIP
我的 Powershell 錯誤是這樣的:
Set-Location : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter >'Path'. Specified method is not supported.
At Z:\PS_Hash_Compare.ps1:14 char:4
cd $Source_UIP
~~~~~~~~~~~
CategoryInfo : InvalidArgument: (:) [Set-Location], ParameterBindingException
FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.SetLocationCommand
這是我的代碼:
$Source_UIP = Get-ChildItem (Read-Host -Prompt 'Get path of the source files')
cd $Source_UIP
$Hash_Src = Get-Filehash -Algorithm SHA256 (Get-ChildItem -Recurse | Get-Item | where {!$_.PsIsContainer}
這將是最終用途:
$Compare = Compare-Object -ReferenceObject $Hash_Src -DifferenceObject $Hash_Extr -Property hash -IncludeEqual -PassThru | Format-List
有任何想法嗎?
編輯:非常感謝@Santiago Squarzon 的幫助!這是我的作業腳本。它也可以在沒有驗證步驟的情況下作業。如果我輸入一個“錯誤”的路徑,例如 *.txt (= File) 而不是路徑,這很有用
$Date_Time = Get-Date -Format "yyyyMMdd_HH_mm"
$ErrorActionPreference1 = 'Stop'
[ValidateScript({
if(-not (Test-Path -Path $_ -PathType Container))
{
throw 'Invalid Path'
}
$true
})]
$Source_UIP = Read-Host -Prompt 'Get path of the source files'
$ErrorActionPreference2 = 'Stop'
[ValidateScript({
if(-not (Test-Path -Path $_ -PathType Container))
{
throw 'Invalid Path'
}
$true
})]
$Extracetd_UIP = Read-Host -Prompt 'Get path of the Destination files'
#相比
$Hash_Src = Get-ChildItem $Source_UIP -Recurse -File | Get-FileHash -Algorithm SHA256
$Hash_Extr = Get-Filehash -Algorithm SHA256 (Get-ChildItem -Recurse | Get-Item | where {!$_.PsIsContainer})
$Hash_Extr = Get-ChildItem $Extracetd_UIP -Recurse -File | Get-FileHash -Algorithm SHA256
$Compare = Compare-Object -ReferenceObject $Hash_Src -DifferenceObject $Hash_Extr -Property hash -IncludeEqual -PassThru | Format-List
$Compare | Out-File -FilePath "C:\Users\USER1\Desktop\test\Destination\Hash_Result-$Date_Time.txt"
Invoke-Item -Path "C:\Users\USER1\Desktop\test\Destination\Hash_Result-$Date_Time.txt"
uj5u.com熱心網友回復:
在我看來,正確的方法是首先檢查用戶的輸入是否有效,這意味著路徑存在并且路徑是一個檔案夾。
為此,您可以使用多種方法,我喜歡使用的一種方法是ValidateScript validation attribute.
需要注意的一件事是,一旦我們確認路徑是一個檔案夾,我沒有使用Set-Location而是直接將路徑(用戶輸入)傳遞給Get-ChildItem,如果您希望以這種方式或使用cd.
$ErrorActionPreference = 'Stop'
[ValidateScript({
if(-not (Test-Path -Path $_ -PathType Container))
{
throw 'Invalid Path'
}
$true
})]
$Source_UIP = Read-Host -Prompt 'Get path of the source files'
# where {!$_.PsIsContainer} => Can be replaced with -File
$Hash_Src = Get-ChildItem $Source_UIP -Recurse -File | Get-FileHash -Algorithm SHA256
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/363103.html
標籤:电源外壳
上一篇:函式只顯示一次屬性
