15 powershell
我可以删除这样的别名:
Remove-Item Alias:wget
Run Code Online (Sandbox Code Playgroud)
然后尝试别名给出预期的结果:
PS > wget
wget : The term 'wget' is not recognized as the name of a cmdlet, function,
script file, or operable program.
Run Code Online (Sandbox Code Playgroud)
但是,如果我将相同的内容添加到脚本中,
PS > cat wget.ps1
Remove-Item Alias:wget
wget
Run Code Online (Sandbox Code Playgroud)
它给人意想不到的结果
cmdlet Invoke-WebRequest at command pipeline position 1
Supply values for the following parameters:
Uri:
Run Code Online (Sandbox Code Playgroud)
Guv*_*nte 16
以下似乎有效
If (Test-Path Alias:wget) {Remove-Item Alias:wget}
If (Test-Path Alias:wget) {Remove-Item Alias:wget}
wget
Run Code Online (Sandbox Code Playgroud)
第一行删除Script级别别名,第二行删除Global级别别名.请注意,两者都需要进行测试,因为如果Global不存在Script则不会创建.
这也是错误的,因为它修改了父级而不是点源.
或者你可以点源你的原始,这将工作
. .\wget.ps1
Run Code Online (Sandbox Code Playgroud)
小智 8
这背后的原因是范围 ......
有四个范围:本地,脚本,私有和全局
变量,函数和别名的规则表明,如果它们未在当前范围中定义,那么PowerShell将搜索父范围.
别名的默认设置设置为allscope,这使得它可以从任何子范围中看到,并且它们也会被继承到任何新的子范围(我认为这将是一个公平的定义).
Get-Alias -Name wget | select Name,options
Name Options
wget AllScope
Run Code Online (Sandbox Code Playgroud)
删除作为脚本范围的别名(范围0)后,它将从全局/父范围(范围1)中找到别名.
当您点源它时,您只是说首先在调用/全局范围内运行脚本,因此默认情况下您将删除全局别名.
试试这些......
例如#1.
1.1)从全局范围中删除别名.
Remove-Item -Path Alias:\wget
Run Code Online (Sandbox Code Playgroud)
1.2)创建一个新的(全局范围)并将其设为私有.
New-Alias -Name wget -Value dir -Scope private
Run Code Online (Sandbox Code Playgroud)
1.3)现在,从嵌套范围中看不到别名.所以尝试运行脚本,它将无法找到.
例如#2.
2.1)从全局范围中删除别名.Remove-Item -Path Alias:\ wget
2.2)创建一个新的并使其成为AllScope
New-Alias -Name wget -Value dir -Option AllScope
Run Code Online (Sandbox Code Playgroud)
2.3)现在运行你的脚本,它将正常工作(使用父作用域中的新别名dir)
您也可以尝试使用相同的变量.它们应该更容易演示(并且可以使用),因为当您使用New/Get/Set/Remove -scope 1或scope 0或使用范围修饰符时,您可以更轻松地使用scope参数,例如,$ global:一个.
Get-Command -Noun variable -ParameterName scope
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6549 次 |
| 最近记录: |