Solved

Powershell Functions

Posted on 2012-04-12
4
448 Views
Last Modified: 2012-04-12
I'm kinda new to Power-Shell and my previous scripting experience was DOS Batch as well as a little Perl several years ago, but in both cases most of my scripts were at the largest about 100 lines so I never bothered much with Functions. I am now attempting to write a very large script and wanted to keep it organized by using Functions, but I'm having issues...

Can somebody explain to me how to make variables work between functions and the root level of the script in a powershell script? For example, why doesn't this work:
Function Get-NewUserInfo
{
$fname = (Read-Host "First Name")
$lname = (Read-Host "Last Name")
$mi = (Read-Host "Middle Initial")
$job = (Read-Host "Job Title")
$dept = (Read-Host "Department")
}

Get-NewUserInfo

Write-Host ""
Write-Host $fname
Write-Host $mi
Write-Host $lname
Write-Host $job
Write-Host $dept

Open in new window


Thanks,
-Al
0
Comment
Question by:Cacophony777
  • 2
  • 2
4 Comments
 
LVL 69

Expert Comment

by:Qlemo
ID: 37838499
The default scope of vars is "local to script block". A function builds an own script block, and hence all vars set therein are volatile. You can use something like
$script:fname = (Read-Host "First Name")

Open in new window

in your function. If you use $global, the vars are set for the scope of the PowerShell session.
0
 
LVL 1

Author Comment

by:Cacophony777
ID: 37838592
So once I call that variable by $script:fname is it available to the entire script for the duration of it's run? ...or if another function in my script needs to modify that same variable do I have to again refer to it by $script:fname?

Also, is there a way to tell my script that I want all variable I use set to the "Script" scope?
0
 
LVL 69

Accepted Solution

by:
Qlemo earned 500 total points
ID: 37838729
If you access $fname, it should be available everywhere. However, if you try to set it, you will create a local instance of that var. Example:
function test
{
  Write-Host $var
  $script:var = "set in function,#1"
  Write-Host $var
  $var = "set in function,#2"
  Write-Host $var
}

Cls
$var = "set in script"
test
Write-Host $var

Open in new window

You can't change or set a default scope, sorry. It is an intentional implemention detail of PowerShell that all changes should be local by default.
Causing side-effects like setting global vars in a function is considered bad practice anyway. You should construct an object, change it attributes, and use that object for the "interface":
Function Get-NewUserInfo ($emp)
{
  $emp.fname = Read-Host "First Name"
  $emp.lname = Read-Host "Last Name"
  $emp.mi    = Read-Host "Middle Initial"
  $emp.job   = Read-Host "Job Title"
  $emp.dept =  Read-Host "Department"
}

$emp = New-Object PSObject
"fname","lname","mi","job","dept" | % { Add-Member -InputObject $emp NoteProperty $_ "" -PassThru }
      
Get-NewUserInfo($emp)

$emp | format-list

Open in new window

I know this is much different from cmd batches, however it is an important step to write "PowerShell'ish" in a proper way ;-).
0
 
LVL 1

Author Closing Comment

by:Cacophony777
ID: 37839289
Thanks... great explanation!
0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will help you understand what HashTables are and how to use them in PowerShell.
A project that enables an administrator to perform actions within a user session context not just at the time of login but any time later on day(s) or week(s) later.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the adminiā€¦

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question