我有一个函数,我传递一个哈希表.在我想要的功能中1)通过Write-Host在屏幕上显示文本; 2)显示哈希表的内容一次 - 提供通常的两列"名称"/"值"哈希表显示.3)有功能返回$true或$false.
MyFunction $MyHashTable
Run Code Online (Sandbox Code Playgroud)
在功能内:
param (
[hashtable]$TheHashTable
)
# Sundry things here and then:
write-host "Some information to display on-screen`n"
# and then:
$TheHashTable
Run Code Online (Sandbox Code Playgroud)
后者的预期结果如下:
Some information to display on-screen
Name Value
---- -----
a b
c d
Run Code Online (Sandbox Code Playgroud)
并最终:
return $true # If what I'm doing worked; otherwise, $false
Run Code Online (Sandbox Code Playgroud)
如果我按上面所示调用该函数,我会看到通过Write-Host屏幕显示的文本,以及散列表内容的两列显示 - 以及文本True或False屏幕上的内容,具体取决于函数返回的内容.
如果我这样称呼它:
$myResult = MyFunction $MyHashTable
Run Code Online (Sandbox Code Playgroud)
...我捕获函数的返回值$myResult- 但是哈希表内容的显示被抑制.如果我这样做也会被抑制:
if ( (MyFunction …Run Code Online (Sandbox Code Playgroud) "它有效 - 但它是最好的做法吗?" 题.在Perl中,有一种紧凑的方式来跟踪文件中发现的字符串的出现:将它们存储在哈希表中.例如:
$HashTable{'the string in question'}++;
Run Code Online (Sandbox Code Playgroud)
Perl会在the string in question完成此操作后多次递增key的值.它可以在跟踪事件发生的同时确保独特的"命中".只是乱搞,我发现我可以用Powershell做同样的事情:
$HashTable['a']++甚至
$Hashtable.a++(哪种让我感到惊讶 - 甚至)
$Hashtable."this is a key"++
好的,所以它有效.但是,Powershell中有一种方法被认为是更好的做法吗?
当我了解Perl和PowerShell的不同之处时,我试图通过引用确定传递和更新列表之间的差异.我认为我现在得到了这个想法,PowerShell明智.
通过引用传递哈希表:
调用函数时:没有必要在表的名称前面加上[ref].在功能:表格的名称param列表,可以先简单地通过[hashtable],而不是[ref]- (因为"收到"它已经是一个参考,所以这是我的解释).如果要在函数内更新哈希表,.Value则在未使用时[ref]不需要.IOW:用这种方式调用函数:MyFunction $MyHashTable.该功能包含:
param([hashtable]$HashNameWithinFunction)
$HashNameWithinFunction.Add('x', 'y')
Run Code Online (Sandbox Code Playgroud)
通过引用传递数组:
无论当函数被调用,并在功能的param()列表:数组的名称必须在前面加[ref].当通过引用更新数组时,.Value必须使用.该函数以这种方式调用:MyFunction ([ref]$MyArray).该功能包含:
param([ref]$ArrayNameWithinFunction)
$ArrayNameWithinFunction.Value += 'something new'
Run Code Online (Sandbox Code Playgroud)
我的理解是否正确?我已经测试了上述内容,我知道两者都有效.但这样做有什么可能会有一些微妙的错误吗?
添加Chrstian的以下回复:
function UpdateArray {
param([ref]$ArrayNameWithinFunction)
$ArrayNameWithinFunction.Value += 'xyzzy'
}
$MyArray = @('a', 'b', 'c')
UpdateArray ([ref]$MyArray)
Run Code Online (Sandbox Code Playgroud)