2014-04-18 60 views
2

我有以下腳本:Powershell:如何在同一時間使用Invoke-Command和點源?

. 
|-- invoke-command.ps1 
|-- no-dot-sourcing.ps1 
`-- with-dot-sourcing.ps1 

這裏是它們的內容:

調用-command.ps1

$scriptPath = Split-Path -Parent $PSCommandPath 
Invoke-Command ` 
    -ComputerName "myserver" ` 
    -Credential "myusername" ` 
    -FilePath "$scriptPath\with-dot-sourcing.ps1" 

無點sourcing.ps1

function getMessage() { 
    return "This script just shows a message - executed on $env:COMPUTERNAME" 
} 

Write-Host (getMessage) 

with-dot-sourcing.ps1

$scriptPath = Split-Path -Parent $PSCommandPath 
. "$scriptPath\no-dot-sourcing.ps1" 

問題

如果我打電話調用命令與-FilePath "$scriptPath\no-dot-sourcing.ps1"一切都工作得很好。我需要叫它with-dot-sourcing.ps1,其原因是我有一些常用的功能,我在其他腳本中使用。所以,一種解決方案是將所有內容都包含在一個巨大的腳本中,然後一切都可以工作,但我認爲這不是一個好的解決方案。

如果我運行該腳本invoke-command.ps1我得到以下錯誤:

Cannot bind argument to parameter 'Path' because it is an empty string. 
    + CategoryInfo   : InvalidData: (:) [Split-Path], ParameterBindingValidationException 
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.SplitPathCommand 
    + PSComputerName  : myserver 

The term '\no-dot-sourcing.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the 
path is correct and try again. 
    + CategoryInfo   : ObjectNotFound: (\no-dot-sourcing.ps1:String) [], CommandNotFoundException 
    + FullyQualifiedErrorId : CommandNotFoundException 
    + PSComputerName  : myserver 

如果它的事項:我使用本地計算機上的Windows 7旗艦版SP1並在服務器上我的Windows Server 2012數據中心。

有沒有什麼辦法可以使用點源並仍然可以使用Invoke-Command?

回答

3

它可以使用PowerShell會話來完成它以下列方式:

調用-command.ps1

$scriptPath = Split-Path -Parent $PSCommandPath 
$credential = Get-Credential 

$remoteSession = New-PSSession -ComputerName "myserver" -Credential $credential 

Invoke-Command -Session $remoteSession -FilePath "$scriptPath\no-dot-sourcing.ps1" 
Invoke-Command -Session $remoteSession -FilePath "$scriptPath\with-dot-sourcing.ps1" 
1

您不能使用點源,因爲直到它到達目標機器纔會執行,然後點源參考對於該機器是本地的,並且那些腳本在那裏不存在。您需要在腳本中包含所有內容。

話雖這麼說,你可以直接從本地腳本文件的腳本在發送前:

@' 
Write-Output 'This is test.ps1' 
'@ | sc test.ps1 


$sb = [scriptblock]::create(@" 
Write-Output "Checking test." 
. {$(get-content test.ps1)} 
"@) 

invoke-command -ScriptBlock $sb 

Checking test. 
This is test.ps1 
+0

複製依賴文件比將所有內容合併到一個文件更麻煩,謝謝! –