本文介紹在PowerShell中創(chuàng)建函數(shù)時(shí),如何讓函數(shù)的參數(shù)輸入值的時(shí)候自動(dòng)變成星號(hào)。
什么叫自動(dòng)變成星號(hào)呢?舉個(gè)例子,我們?cè)诘卿浺粋€(gè)郵箱時(shí),輸入用戶時(shí)看到的是明文的,但我們?cè)谳斎朊艽a時(shí),看到的是一個(gè)個(gè)增加的星號(hào)。在使用PowerShell自定義函數(shù)時(shí),如何設(shè)置才能讓輸入密碼之類的參數(shù)時(shí),自己用星號(hào)掩蓋呢?且往下看。
復(fù)制代碼 代碼如下:
function Test-Password {
param
(
[Parameter(Mandatory=$true)]
$password
)
$plain = (New-Object System.Management.Automation.PSCredential(‘splaybow.com',$password)).GetNetworkCredential().Password
Write-Host “你輸入了: $plain”
}
像上面這個(gè)函數(shù),定義了一個(gè)必選的$password函數(shù),我們不希望在輸入這個(gè)參數(shù)的值時(shí)以明文顯示,因?yàn)槟菢雍苡锌赡軙?huì)被旁邊的人把密碼剽竊。于是我們將代碼作一下修改。
復(fù)制代碼 代碼如下:
function Test-Password {
param
(
[System.Security.SecureString]
[Parameter(Mandatory=$true)]
$password
)
$plain = (New-Object System.Management.Automation.PSCredential(‘splaybow.com',$password)).GetNetworkCredential().Password
Write-Host “你輸入了: $plain”
}
注意,上面在Parameter這個(gè)限制語句之前加了一句“[System.Security.SecureString]”,這個(gè)修飾語句用于將輸入?yún)?shù)設(shè)置為安全字符串類型,這樣輸入這個(gè)參數(shù)的值時(shí),就會(huì)變成星號(hào)了。這是一個(gè)很有用的技巧,大家不妨試試。
關(guān)于PowerShell函數(shù)設(shè)置輸入?yún)?shù)被星號(hào)掩蓋,本文就介紹這么多,希望對(duì)您有所幫助,謝謝!
您可能感興趣的文章:- PowerShell函數(shù)參數(shù)設(shè)置成自動(dòng)識(shí)別數(shù)據(jù)類型的例子
- PowerShell函數(shù)參數(shù)設(shè)置為即可選又必選的方法
- PowerShell函數(shù)參數(shù)使用智能提示功能例子
- PowerShell使用枚舉變量定義帶智能提示功能的函數(shù)參數(shù)