我正在嘗試將 ShouldProcess 邏輯添加到洗掉遠程服務器上的檔案的腳本中,以便我可以使用 -WhatIf 引數,但它回傳錯誤。這是函式:
function testshouldprocess {
[CmdletBinding(SupportsShouldProcess = $true]
param(
$server
)
invoke-command $server {
Get-ChildItem c:\temp\ | ForEach-Object {
if($pscmdlet.ShouldProcess($Server)) {
remove-item $_.fullname
}
}
}
}
testshouldprocess 'Server1' -WhatIf
當腳本運行時,它回傳錯誤
InvalidOperation: You cannot call a method on a null-valued expression.
當每個檔案通過管道時。如果我將代碼更改為
if ($pscmdlet.ShouldProcess($server)) {
invoke-command $server {
Get-ChildItem c:\temp\ | ForEach-Object {
remove-item $_.fullname
}
}
}
它有效,但 WhatIf 只對整個目錄串列執行一次。如果我將代碼更改為
Get-ChildItem \\$server\c$\temp\ | ForEach-Object {
if ($pscmdlet.ShouldProcess($server)) {
remove-item $_.fullname
}
}
它有效,但我更喜歡使用 Invoke-Command。
ShouldProcess 與 Invoke-Command 不兼容嗎?
任何見解表示贊賞。
uj5u.com熱心網友回復:
遠程服務器只知道您執行的命令。不是來自遠程呼叫者的值。嘗試使用remove-item $_.fullname -Whatif:$($using:pscmdlet.ShouldProcess($server)). 請參閱遠程變數
另一種選擇是$WhatIfPreference在遠程服務器上指定并在下一個陳述句中使用它
$WhatIfPreference = $using:pscmdlet.ShouldProcess($server);
然后remove-item $_.fullname -WhatIf:$WhatIfPreference
uj5u.com熱心網友回復:
Hazrelle 的回答提供了關于需要使用$using:作用域以便遠程執行腳本塊能夠訪問來自呼叫者作用域的值的關鍵指標。
為了全力支持您的方案-兩個-WhatIf和-Confirm功能,兩者都通過轉動暗示SupportShouldProces的-你必須:
使您的遠程執行腳本塊也成為高級腳本塊
[CmdletBinding(SupportsShouldProcess)],在param()塊上方有自己的屬性,因此也有自己的$PSCmdlet實體。從呼叫者的范圍通過
$using:WhatIfPreference和參考假設/確認相關的值$using:ConfirmPreference- 請注意,對于高級函式和腳本,PowerShell使用函式區域變數將
-WhatIf和-Confirm開關轉換為等效的首選項變數值;即,通過-WhatIf創建一個功能本地$WhatIfPreference值為變數$true,和傳球-Confirm創建一個功能本地$ConfirmPreference與值High。
- 請注意,對于高級函式和腳本,PowerShell使用函式區域變數將
function testshouldprocess {
[CmdletBinding(SupportsShouldProcess)]
param(
$server
)
Invoke-Command $server {
[CmdletBinding(SupportsShouldProcess)]
param()
# Use the caller's WhatIf / Confirm preferences.
$WhatIfPreference = $using:WhatIfPreference
$ConfirmPreference = $using:ConfirmPreference
Get-ChildItem c:\temp\ | ForEach-Object {
if ($pscmdlet.ShouldProcess($using:server, "delete file: $($_.FullName)")) {
Remove-Item $_.FullName
}
}
}
}
testshouldprocess 'Server1' -WhatIf
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/345242.html
標籤:电源外壳
上一篇:Powershell腳本在SetAccessRule上拋出System.Management.Automation.PSMethod錯誤
