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
-
AuthorPosts
-
November 6, 2017 at 7:01 pm #83690
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
-
November 6, 2017 at 8:49 pm #83698
# 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' -
November 6, 2017 at 11:00 pm #83717
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
-
November 7, 2017 at 5:55 pm #83750
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
-
AuthorPosts
The topic ‘Problem with passing variable to remote session’ is closed to new replies.