dslreports logo
 
    All Forums Hot Topics Gallery
spc
uniqs
219

PToN
Premium Member
join:2001-10-04
Houston, TX

PToN

Premium Member

Powershell variable scope?

Hello,

This is the first time for me writing a PS script and i would like to know how to have variables easilly accessed between methods in the same script. For example:
$HostName = ""
$Model = ""
 
$UserXpPath = "C:\Documents And Settings"
$User7Path = "C:\Users"
$UserProfilesPath = ""
 
function SetComputerName {
  Write-Host "Trying to find and set Hostname for installation..."
 
  $PC = Get-WmiObject Win32_ComputerSystemProduct -Property Name,IdentifyingNumber
  $ServiceTag = $PC.IdentifyingNumber
  $Model = $PC.Name -a -replace "OptiPlex ",""
 
  if($ServiceTag -eq $NULL -or $Model -eq $NULL)
  {
    Write-Host "ServiceTag or Model number could be found halting script"
    Exit
  }
 
  if($Model.length -gt 4) { $Model = $Model -replace " ","" }
 
  $HostName = "HST" + $Model + $ServiceTag
}
 
function CheckProfilePath {
  if (Test-Path $UserXpPath) {
    Write-Host "Found Windows XP path for User profiles."
    $UserProfilePath = $UserXpPath
  }
  else if (Test-Path $User7Path) {
    Write-Host "Found Windows 7 path for User profiles."
    $UserProfilePath = $User7Path
  }
  else {
    Write-Host "Unable to find: " + $UserXpPath + " nor: " + $User7Path
    Write-Host "Terminating process..."
    Exit
  }
}
 
function MigrateProfiles {
  Write-Host "Checking for existance of profiles in: " + $UserProfilesPath
  if ((Get-ChildItem $UserProfilesPath | Measure-Object).Count -gt 0) {
    #
    #Code for USMT Here Create local USMT folder structore, etc
    #
  }
}
 
 

The way it seems to be is that PS calls global variables to variables set/used under the entire PS environment. I dont wanna do that as everything i need is done in a single script. I just wanna set vars from functions and access those vars from other functions so that i can get my results.

In the snippet above a function sets some vars to some values and those are later used by other functions.

Thanks for any info.
PToN

PToN

Premium Member

Ok, just use $Script: within the functions or $Global: