|
1 | 1 | --- |
2 | 2 | description: Function |
3 | 3 | Locale: en-US |
4 | | -ms.date: 06/10/2024 |
| 4 | +ms.date: 03/06/2025 |
5 | 5 | online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_function_provider?view=powershell-5.1&WT.mc_id=ps-gethelp |
6 | 6 | schema: 2.0.0 |
7 | 7 | title: about_Function_Provider |
@@ -78,8 +78,8 @@ drive. To reference a function from another location, use the drive name |
78 | 78 | > [!NOTE] |
79 | 79 | > PowerShell uses aliases to allow you a familiar way to work with provider |
80 | 80 | > paths. Commands such as `dir` and `ls` are now aliases for |
81 | | -> [Get-ChildItem][09], `cd` is an alias for [Set-Location][10] and `pwd` is |
82 | | -> an alias for [Get-Location][01]. |
| 81 | +> [Get-ChildItem][09], `cd` is an alias for [Set-Location][10] and `pwd` is an |
| 82 | +> alias for [Get-Location][01]. |
83 | 83 |
|
84 | 84 | ## Getting functions |
85 | 85 |
|
@@ -153,9 +153,33 @@ function name. |
153 | 153 | New-Item -Path Function:Win32: -Value {Set-Location C:\Windows\System32} |
154 | 154 | ``` |
155 | 155 |
|
156 | | -You can also create a function by typing it at the PowerShell command line. For |
157 | | -example, tpe `Function:Win32: {Set-Location C:\Windows\System32}`. If you are |
158 | | -in the `Function:` drive, you can omit the drive name. |
| 156 | +### Scopes |
| 157 | + |
| 158 | +Just like variables, functions belong to a specific scope. When you create a |
| 159 | +function, it is available only in the scope in which it was created. To make a |
| 160 | +function available, use a scope modifier when you create the function. For more |
| 161 | +information, see [about_Scopes][15]. |
| 162 | + |
| 163 | +The following example uses the `global:` scope modifier to create a function in |
| 164 | +the global scope. |
| 165 | + |
| 166 | +```powershell |
| 167 | +function New-Function { |
| 168 | + param( |
| 169 | + [string] $Name, |
| 170 | + [scriptblock] $Script |
| 171 | + ) |
| 172 | +
|
| 173 | + $lp = "Function:\global:$($name)" |
| 174 | + Set-Item -LiteralPath $lp -Value $script -PassThru -Force |
| 175 | +} |
| 176 | +
|
| 177 | +New-Function -Name 'Win32:' -Script { Set-Location C:\Windows\System32 } |
| 178 | +``` |
| 179 | + |
| 180 | +Without the `global:` scope modifier, the function would be created in the |
| 181 | +local scope. When `New-Function` exits the newly created function would no |
| 182 | +longer exist. |
159 | 183 |
|
160 | 184 | ## Deleting a function |
161 | 185 |
|
@@ -268,3 +292,4 @@ Get-Help Get-ChildItem -Path function: |
268 | 292 | [12]: xref:Microsoft.PowerShell.Core.Get-Help |
269 | 293 | [13]: about_Functions.md |
270 | 294 | [14]: about_Providers.md |
| 295 | +[15]: about_Scopes.md |
0 commit comments