Problem with passing variable to remote session

Welcome Forums General PowerShell Q&A Problem with passing variable to remote session

This topic contains 3 replies, has 3 voices, and was last updated by

1 year, 3 months ago.

  • Author
  • #83690

    Points: 1
    Rank: Member

    Hello I am using below scriptblock and have passed variable name "localfolderpath" where while testing path it is coming null . could you please suggest what I am missing here . Due to this we are unable to folder for users who do not have it on server.

    $ScriptBlockDir = {
    Param (
    [string] $samAccountName )

    if( $Env:ComputerName -eq "fileserver101" ) {
    $LocalFolderPath = "H:\Users"
    else {
    $LocalFolderPath = "D:\Users"

    if( -not (test-path -Path "$LocalFolderPath\$samAccountName") ) {
    try {
    LogEntry "New Home Drive Folder"
    $NewFolder = New-Item -Path $LocalFolderPath -Name $samAccountName -ItemType Directory
    return 1
    catch {
    Write-Host "Failed with error"
    return -1

    Write-Host "already exists"
    return 0

    $result = Invoke-Command -Session $PSSession -ScriptBlock $ScriptBlockDir -ArgumentList $samAccountName

  • #83698

    Points: 780
    Helping Hand
    Rank: Major Contributor

    # See – PSTip Passing local variables to a remote session in PowerShell 3.0

    # As well as

  • #83717

    Points: 101
    Helping Hand
    Rank: Participant

    Test by using a simple test 1st to get the hand of how remoting and variables works and go from there.

    Test path using the local computer

    PS C:\> Invoke-Command -ComputerName "localhost" -ScriptBlock {Test-Path C:\Windows}

    Now add the path to a variable

    PS C:\> $path = "C:\Windows"

    Use the variable in your remoting session and it fails because the variable is local to your machine and not the remote machine.

    PS C:\> Invoke-Command -ComputerName "localhost" -ScriptBlock {Test-Path $path}
    Cannot bind argument to parameter 'Path' because it is null.
        + CategoryInfo          : InvalidData: (:) [Test-Path], ParameterBindingValidationException
        + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand
        + PSComputerName        : localhost

    To get the local variable sent over to the remote machine you have to prefix it with "using"

    PS C:\> Invoke-Command -ComputerName "localhost" -ScriptBlock {Test-Path $using:path}
  • #83750

    Points: 1
    Rank: Member


    just for your information
    just removed logentry line from try block and it worked
    logentry is a function we have to logs comments.

    thanks for your reply

The topic ‘Problem with passing variable to remote session’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort