Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Powershell Functions

Posted on 2012-04-12
4
Medium Priority
?
465 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 71

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 71

Accepted Solution

by:
Qlemo earned 2000 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

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.
My attempt to use PowerShell and other great resources found online to simplify the deployment of Office 365 ProPlus client components to any workstation that needs it, regardless of existing Office components that may be needing attention.
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…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

705 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