Powershell:如何同时使用Invoke-Command和dot sourcing?

时间:2014-04-18 18:40:05

标签: powershell remote-server

我有以下脚本:

.
|-- 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)

用双点sourcing.ps1

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

问题

如果我用-FilePath "$scriptPath\no-dot-sourcing.ps1"调用Invoke-Command,一切都运行良好。我需要将其称为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 Datacenter。

我有什么方法可以使用点源并仍然能够使用Invoke-Command?

2 个答案:

答案 0 :(得分: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 :(得分:1)

你不能使用点源,因为执行不会发生直到它到达目标机器,然后点源引用将是该机器的本地,并且这些脚本不会#&# 39;存在于那里。您需要在脚本中包含所有内容。

话虽这么说,您可以在发送之前从本地脚本文件构建脚本:

@'
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