Search code examples
powershellpowershell-2.0invoke-command

how to pass command line parameters to invoked session in powershell 2.0


How can i pass command line parameters to a session which is invoked using 'invoke-command' in powershell 2.0

my script:

param(
    [string]$hostname = 'my_server_name'
)

function createSession($hostname){
    return New-PSSession -ComputerName $hostname -Credential $env:UserDomain\$env:UserName
}
$session = createSession $hostname
invoke-command -Session $session -ScriptBlock {
   write-host $hostname
   write-host $using:hostname
   write-host $script:hostname 
   write-host '**test text**'

}
    Exit-PSSession

Output: (I'm getting empty string if i print the parameter value directly.)

**test text**

Solution

  • use param block

    $hostname = $env:computername
    Invoke-Command -ScriptBlock { param($hostname)
        Write-OutPut $hostname
    } -ArgumentList $hostname