Problem with passing variable to remote session

This topic contains 3 replies, has 3 voices, and was last updated by  Rahul Kaim 1 week, 6 days ago.

  • Author
    Posts
  • #83690

    Rahul Kaim
    Participant

    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

    postanote
    Participant

    # See – PSTip Passing local variables to a remote session in PowerShell 3.0
    'powershellmagazine.com/2013/01/23/pstip-passing-local-variables-to-a-remote-session-in-powershell-3-0'

    # As well as
    'technet.microsoft.com/en-us/library/ee692790.aspx'
    'technet.microsoft.com/en-us/library/jj574187(v=ws.11).aspx'

  • #83717

    Alex Aymonier
    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}
    True
    

    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}
    True
    
  • #83750

    Rahul Kaim
    Participant

    Hi

    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

You must be logged in to reply to this topic.