我正在为我的客户提供在我的应用程序中使用PowerShell编写脚本的功能,但我想严格限制他们可以使用的命令。将cmibility的Visibility设置为Private适用于顶级作用域,但如果将命令包装在函数中,它将再次可用。为什么这样做?可见性在函数中是否仍然是私有的,因此我无法执行cmdlet?
PS C:\> Get-Process -name "firefox"
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
470 53 143336 141720 390 5.71 18380 firefox
PS C:\> Get-Command -name "Get-Process" | % { $_.Visibility = "Private" }
PS C:\> Get-Process -name "firefox"
The term 'Get-Process' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:12
+ Get-Process <<<< -name "firefox"
+ CategoryInfo : ObjectNotFound: (Get-Process:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
_________________
PS C:\> function getp { Get-Process -name "firefox" }<br/>
PS C:\> getp
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
470 53 143336 141720 390 5.71 18380 firefox
答案 0 :(得分:0)
您只是从顶级范围更改了Get-Process
的可见性。较低级别范围内的函数名称(getp
内部)在不同范围内看get-process
,因此不是私有的。根据{{3}}:
Private:
Items in private scope cannot be seen outside of the current
scope. You can use private scope to create a private version
of an item with the same name in another scope.
如果您有一组想要有选择地显示的功能,我认为您最好使用help。假设您有一个包含许多函数的模块 - scopes.psm1
:
function write-private { "From Private Func."}
function write-public { "From Public Func." }
export-modulemember -function public-func
因为只导出write-public
,所以它是唯一可见的函数。然后导入它的人只能调用:
# > Import-Module .\scopes.psm1
# > write-private
write-private : The term 'write-private' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is
correct and try again.
At line:1 char:1
+ write-private
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (write-private:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
# > write-public
From Public Func.