Powershell 将变量传递给远程脚本

标签 powershell invoke-command

我有以下 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

最佳答案

您需要在脚本中使用参数 block ,传递给文件的参数将分配给 $domainName,您将使用它将值传递给脚本 block :

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

关于Powershell 将变量传递给远程脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13036327/

相关文章:

powershell - 使用 powershell 提取 zip 文件

Powershell脚本将文件复制到所有给定的子文件夹中?

Powershell Invoke-Command 导致不同的结果

Powershell 错误/异常处理

powershell - 需要通过带有调用命令的 powershell 远程访问第二个跃点

c++ - 我们可以在不使用 pCmdInfo->lpVerb 的情况下执行右键单击吗

powershell - 从IF ELSE语句输出到管道

Powershell批量查找ActiveDirectory对象

powershell - Invoke-Command 更改输出编码

powershell - 在 PowerShell 中使用属性设置别名