【问题标题】:Powershell passing variables to remote scriptPowershell将变量传递给远程脚本
【发布时间】:2012-10-24 09:19:58
【问题描述】:

我有以下 cmd 文件:-

PowerShell.exe -noexit E:\wwwroot\domains\processes\AddDirectory.ps1 -Param testdomain.co.uk

经过:-

$Session = New-PSSession -ComputerName 192.168.0.25
$script = {
Param($Param1)
set-executionpolicy unrestricted -force

# Set Variables
$domain = $Param1
$sitepath = "e:\domains\" + $domain

# Check for physical path
if (-not (Test-Path -path $sitePath))
{
New-Item -Path $sitepath -type directory 
New-Item -Path $sitepath\wwwroot -type directory 
}
set-executionpolicy restricted -force     
}
Invoke-Command -Session $Session -ScriptBlock $script

但它只是运行但什么也不做。

如果我将 $domain 变量声明为 $domain = 'testdomain.co.uk' 它可以工作,但它不想通过 cmd 文件中的 var。我究竟做错了什么?我试图将它作为 -ArgumentsList -$Param1 放在 Invoke-Command 中,但这也不起作用.....

任何想法都非常受欢迎

谢谢 保罗

更新 - 我已经按照以下更新了我的代码,但遇到了同样的问题:-

param($domainName)
$script = {
    Param($Param1)
    set-executionpolicy unrestricted -force
    # Set Variables
    $domain = $Param1
    $sitepath = "e:\domains\" + $domain
    # Check for physical path
    if (-not (Test-Path -path $sitePath))
    {
        New-Item -Path $sitepath -type directory
        New-Item -Path $sitepath\wwwroot -type directory
        New-Item -Path $sitepath\db -type directory
        New-Item -Path $sitepath\stats -type directory
    }
    set-executionpolicy restricted -force
}

$Session = New-PSSession -ComputerName 192.168.0.25

Invoke-Command -Session $Session -ScriptBlock $script -ArgumentList $domainName

【问题讨论】:

  • 是 e:本地或网络映射驱动器。如果是后者,您可能会遇到双跳身份验证问题。

标签: powershell invoke-command


【解决方案1】:

您需要在脚本中使用一个参数块,您传递给文件的参数将被分配给 $domainName 并且您将使用它来将值传递给脚本块:

PowerShell.exe -noexit E:\wwwroot\domains\processes\AddDirectory.ps1 testdomain.co.uk


# script file

param($domainName)

$script = {
    Param($Param1)

    ...
    $domain = $Param1
    ...   
}

$Session = New-PSSession -ComputerName 192.168.0.25
Invoke-Command -Session $Session -ScriptBlock $script -ArgumentList $domainName

【讨论】:

  • 好的,我现在已经输出了以下代码,但它不起作用 - 文件运行但没有任何反应:-
  • param($domainName) $script = { Param($Param1) set-executionpolicy unrestricted -force # 设置变量 $domain = $Param1 $sitepath = "e:\domains\" + $domain #检查物理路径 if (-not (Test-Path -path $sitePath)) { New-Item -Path $sitepath -type directory New-Item -Path $sitepath\wwwroot -type directory New-Item -Path $sitepath\db -type directory New-Item -Path $sitepath\stats -type directory } set-executionpolicy restricted -force } $Session = New-PSSession -ComputerName 192.168.0.25 Invoke-Command -Session $Session -ScriptBlock $script -ArgumentList $domainName
  • 嗨 - 更新了初始问题中的代码,因为它不会让我在 cmets 框中正确格式化...
  • 这正在工作 - 在我的 cmd 文件中,我有 *.ps1 -param testdomain.co.uk。我已经取出 -param 并且它有效 - 非常感谢!
猜你喜欢
  • 2021-08-14
  • 2011-10-08
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
相关资源
最近更新 更多