3 回答

TA貢獻1784條經驗 獲得超9個贊
-ArgumentList基于與腳本塊命令一起使用,例如:
Invoke-Command -Cn (gc Servers.txt) {param($Debug=$False, $Clear=$False) C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 } -ArgumentList $False,$True
當您使用a調用它時,-File它仍會像啞啞數組那樣傳遞參數。我已經提交了功能請求,以將其添加到命令中(請對此進行投票)。
因此,您有兩個選擇:
如果您有一個看起來像這樣的腳本,那么該腳本位于遠程機器可以訪問的網絡位置(請注意,這-Debug是因為當我使用該Parameter屬性時,該腳本隱式地獲取了CmdletBinding,因此,所有通用參數也都包含在內):
param(
[Parameter(Position=0)]
$one
,
[Parameter(Position=1)]
$two
,
[Parameter()]
[Switch]$Clear
)
"The test is for '$one' and '$two' ... and we $(if($DebugPreference -ne 'SilentlyContinue'){"will"}else{"won't"}) run in debug mode, and we $(if($Clear){"will"}else{"won't"}) clear the logs after."
如果$Clear不想調用... 的含義,則可以使用以下兩種Invoke-Command語法之一:
icm -cn (gc Servers.txt) {
param($one,$two,$Debug=$False,$Clear=$False)
C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 @PSBoundParameters
} -ArgumentList "uno", "dos", $false, $true
在那篇文章中,我將在腳本塊中復制我關心的所有參數,以便可以傳遞值。如果我可以對它們進行硬編碼(這是我實際上所做的),則無需這樣做并使用PSBoundParameters,我只需傳遞所需的內容即可。在下面的第二個示例中,我將傳遞$ Clear,只是為了演示如何傳遞開關參數:
icm -cn $Env:ComputerName {
param([bool]$Clear)
C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $(Test-Path $Profile)
另一種選擇
如果腳本在您的本地計算機上,并且您不想將參數更改為位置參數,或者您想指定作為通用參數的參數(因此您無法控制它們),則需要獲取以下內容:該腳本并將其嵌入到您的scriptblock中:
$script = [scriptblock]::create( @"
param(`$one,`$two,`$Debug=`$False,`$Clear=`$False)
&{ $(Get-Content C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -delimiter ([char]0)) } @PSBoundParameters
"@ )
Invoke-Command -Script $script -Args "uno", "dos", $false, $true
后記:
如果您確實需要為腳本名稱傳遞一個變量,那么您將執行的操作將取決于該變量是在本地還是遠程定義的。在一般情況下,如果你有一個變量$Script或環境變量$Env:Script與腳本的名稱,就可以與呼叫運營商()執行它:&$Script或&$Env:Script
如果它是已經在遠程計算機上定義的環境變量,則僅此而已。如果它是局部變量,則必須將其傳遞給遠程腳本塊:
Invoke-Command -cn $Env:ComputerName {
param([String]$Script, [bool]$Clear)
&$Script "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $ScriptPath, $(Test-Path $Profile)

TA貢獻1890條經驗 獲得超9個贊
我的解決方案是使用[scriptblock]:Create以下命令動態編寫腳本塊:
# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.
$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not
# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script
傳遞參數是非常令人沮喪,嘗試各種方法,例如
-arguments,$using:p1等,如沒有問題,期望這只是工作。
由于我控制以[scriptblock]這種方式創建(或腳本文件)的字符串的內容和變量擴展,因此“ invoke-command”命令沒有真正的問題。
(不應該那么難。:))

TA貢獻1772條經驗 獲得超8個贊
我懷疑這是自創建該帖子以來的一項新功能-使用$ Using:var將參數傳遞到腳本塊。然后,如果腳本已在計算機上或相對于計算機的已知網絡位置中,則傳遞參數很簡單
以主要示例為例:
icm -cn $Env:ComputerName {
C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -one "uno" -two "dos" -Debug -Clear $Using:Clear
}
- 3 回答
- 0 關注
- 1557 瀏覽
添加回答
舉報