我正在嘗試撰寫一個簡單的函式,該函式從指定的目錄中獲取檔案,并使用一個條件過濾它們,然后將結果放回原處。我想出了這個如下。如果它沒有放在一個函式中,它就可以作業,而當它放在一個函式中時它只運行Get-ChildItem,我不知道為什么。這是我的簡單代碼:
function Move-AllSigned
{
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string] $Path
)
Process {
$TempPath = Join-Path -Path $Path -ChildPath '\1'
Write-Host $TempPath
Set-Location -Path $Path
Get-ChildItem -Name "*sig*" | Move-Item -Destination $TempPath
Remove-Item *.pdf
Set-Location -Path $TempPath
Move-Item * -Destination $Path
}
}
uj5u.com熱心網友回復:
雖然我對您的癥狀沒有任何解釋,但您可以通過簡化代碼和避免呼叫來繞過它Set-Location(最好避免呼叫,因為它們會更改當前位置session-wide):
Remove-Item (Join-Path $Path *.pdf) -Exclude *sig* -WhatIf
注意:上面命令中的-WhatIfcommon引數可以預覽操作。-WhatIf 一旦您確定操作會執行您想要的操作,請洗掉。
以上洗掉了.pdf檔案夾中名稱中$Path沒有子字串的所有檔案sig- 這就是我理解你的意圖。
封裝在一個函式中(省略了錯誤處理):
function Remove-AllUnsigned {
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory)]
[string] $Path,
[switch] $Force
)
# Ask for confirmation, unless -Force was passed.
# Caveat: The default prompt response is YES, unfortunately.
if (-not $Force -and -not $PSCmdlet.ShouldContinue($Path, "Remove all unsigned PDF files from the following path?")) { return }
# Thanks to SupportsShouldProcess, passing -WhatIf to the function
# is in effect propagated to cmdlets called inside the function.
Remove-Item (Join-Path $Path *.pdf) -Exclude *sig*
}
筆記:
由于該函式不是為接受管道輸入而設計的,因此不需要
process塊(盡管它不會受到傷害)。由于即時洗掉可能很危險,
$PSCmdlet.ShouldContinue()因此默認情況下用于提示用戶進行確認 - 除非您明確通過-Force$PSCmdlet.ShouldContinue()不幸的是,默認顯示的提示為 YES 作為回應;GitHub 問題 #9428建議引入一個允許默認為 NO 的新多載。
為了使函式本身還支持
-WhatIf常見的引數進行預覽操作,屬性SupportsShouldProcess在[CmdletBinding()]屬性設定(隱式$true)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/399974.html
標籤:电源外壳
