Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

invoke command - Powershell passing variables to remote script

I have the following cmd file:-

PowerShell.exe -noexit E:wwwrootdomainsprocessesAddDirectory.ps1 -Param testdomain.co.uk

which goes through to:-

$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 $sitepathwwwroot -type directory 
}
set-executionpolicy restricted -force     
}
Invoke-Command -Session $Session -ScriptBlock $script

But it just runs but does nothing.

If I declare the $domain variable as $domain = 'testdomain.co.uk' it works but it doesn't want to pass through the var from the cmd file. What am I doing wrong? I've tried to put it in the Invoke-Command as -ArgumentsList -$Param1 but that doesn't work either.....

Any ideas greatfully received

Thanks Paul

Update - I've updated my code as per below but getting same issue:-

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 $sitepathwwwroot -type directory
        New-Item -Path $sitepathdb -type directory
        New-Item -Path $sitepathstats -type directory
    }
    set-executionpolicy restricted -force
}

$Session = New-PSSession -ComputerName 192.168.0.25

Invoke-Command -Session $Session -ScriptBlock $script -ArgumentList $domainName
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use a param block in the script, the argument you pass to the file will be assign to $domainName and you will use it to pass the value to the scriptblock :

PowerShell.exe -noexit E:wwwrootdomainsprocessesAddDirectory.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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...