Home > OS >  syntax in for-loop using local variables
syntax in for-loop using local variables

Time:08-02

Many of my scripts are using PSsession quite often checking on available shares on several remote PCs. PS-Remoting is great. Below is the simple working code-snippet:

if (Invoke-Command -Session $PSess -ScriptBlock {Get-SMBShare -Name $using:shareName_1 -ea 0}) {
    $mapPS_1=0
    write-Host "available: $shareName_1"
    } else {
    $mapPS_1=1
    write-Host "NOT available: $shareName_1"
    }

Instead of repeating this code several times (only with differing variables for the shareNames according to the examples in the list) I would like to create a for-loop (possibly) containing just that code. Here is a list of shares to be checked upon:

$shareName_1='TC-MEDIA-SYSTEM'
$shareName_2='TC-MEDIA-DATA1'
$shareName_3='V-15TB_01'
$shareName_4='W-LL-503DD'
$shareName_5='X-TL-503AA'
$shareName_6='Y-LL-503BB'
$shareName_7='Z-LL-503CC'
$shareName_8='DUMPSTER_01'
$shareName_9='BKUP-NAS-01'
$shareName_10='TC-DUMPSTER_02'

As one can read from the code-snippet, depending on the resulting output, one local variable $mapPS gets manipulated.

All this works fine as shown above. The trouble I am facing is to find the proper syntax for this to run in a for-loop.

I'd assume that the variable $using:shareName_$i is the troubling factor.

This is what I've got so far. Unfortunately, not bearing any fruit.

for ($i = 1; $i -lt 11; $i  ) {
if (Invoke-Command -Session $PSess -ScriptBlock {Get-SMBShare -Name $using:(Get-Variable -Name shareName_$i).Value} -ea 0) {
    Set-Variable -Name mapPS_$i value 0
    write-Host "available: $shareName_$i"
    } else {
    Set-Variable -Name mapPS_$i value 1
    write-Host "NOT available: $shareName_$i"
    }
}

I'm sure Powershell has a solution for this - I just don't know it. Any hints leading to the solution are appreciated.

CodePudding user response:

Generally, consider storing your share names in an array instead of in individual variables (e.g., $shareNames ='TC-MEDIA-SYSTEM', 'TC-MEDIA-DATA1', ...), which allows you to reference them by index (e.g., $shareNames[0]) instead of having to resort to variable indirection via the Get-Variable cmdlet.


A simple solution is to create an aux. local variable in the loop that your remote script can reference via the $using: scope (which doesn't support commands or expressions):

foreach ($i in 1..10) {
  $shareName = Get-Variable -ValueOnly "$shareName_$i"
  if (Invoke-Command -Session $PSess -ScriptBlock { Get-SMBShare -Name $using:shareName } -ea 0) {
    Set-Variable -Name mapPS_$i value 0
    write-Host "available: $shareName_$i"
  }
  else {
    Set-Variable -Name mapPS_$i value 1
    write-Host "NOT available: $shareName_$i"
  }
}
  • Related