powershellinvoke-command

Pass local variable to invoke-command


I am executing the below Powershell script from a remote server. However it is failing as follows:

PS C:\\Windows\\system32\> Invoke-Command -Session $evServerSession -scriptblock {

\\>\> $ListArchiveNames = Get-Content "E:\\Utilities\\MyScripts\\EXOmigration\\ArchivePermissions\\ArchivesList.txt"

\\>\> Foreach ($ArchiveName in $ListArchiveNames) {
  Get-EVArchive -ArchiveName $ArchiveName |
    Get-EVArchivePermission |
      Export-Csv -Path E:\\Utilities\\MyScripts\\EXOmigration\\ArchivePermissions\\$NewTrusteesList.csv -Append -NoTypeInformation -Force}

\\>\>

\\>\> }
cls
#==============
$NewTrusteesList = Read-Host "Please enter the migration Transvault group name here " 
$NewTrusteesList = $NewTrusteesList + "-ArchiveTrustees" + $dateStr 
New-Item  E:\Utilities\MyScripts\EXOmigration\ArchivePermissions\$NewTrusteesList.csv -ItemType File

#------------
#--------------------Establish an EV PS session-----------------------------
$evServerSession = New-PSSession -ComputerName cov-msv-prd009.morganlewis.net -ConfigurationName Microsoft.Powershell32
Invoke-Command -Session $evServerSession -scriptblock {
Add-PSSnapin Symantec.EnterpriseVault.PowerShell.Snapin
}

#--------------------Run pertinent PS scripts-------------------------------
Invoke-Command -Session $evServerSession -scriptblock {
  $ListArchiveNames = Get-Content 
  "E:\Utilities\MyScripts\EXOmigration\ArchivePermissions\ArchivesList.txt"
  Foreach ($ArchiveName in $ListArchiveNames) {
    Get-EVArchive -ArchiveName $ArchiveName |
      Get-EVArchivePermission | Export-Csv -Path 
    E:\Utilities\MyScripts\EXOmigration\ArchivePermissions\$NewTrusteesList.csv -Append -NoTypeInformation -Force
  }
}

#------------------------Clean up the session----------------------------
$evServerSession | Remove-PSSession


Solution

  • You have to use $Using:variable_name to include variable_name local variable in a command run on a remote computer

    Example:

    $Log = 'PowerShellCore/Operational'
    Invoke-Command -ComputerName Server01 -ScriptBlock {
        Get-WinEvent -LogName $Using:Log -MaxEvents 10
    }