PowerShell使用哈希表创建有条件的代码库 1


下面是常规的创建目录方法:

#requires -Version 1

$path = 'c:\testfolder'
$exists = Test-Path -Path $path

if ($exists)
{
  $null = New-Item -Path $path -ItemType Directory
  Write-Warning -Message 'Folder created'
}
else
{
  Write-Warning -Message 'Folder already present'
}

下面演示一种更高级的方法:

#requires -Version 1

$Creator = @{
  $true = { Write-Warning 'Folder already present'}
  $false = {$null = New-Item -Path $Path -ItemType Directory
            Write-Warning 'Folder created'}
}


$Path = 'c:\testfolder2'
& $Creator[(Test-Path $Path)]

事实上这个哈希表存储了两个脚本块,$true和$false都为$Creator的键值。根据(Test-Path $Path)执行结果就可以返回不同的脚本块,最后再使用“&”来执行脚本块。
原文地址:Using Hash Table as Conditional Code Repository

本文链接: https://www.pstips.net/using-hash-table-as-conditional-code-repository.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

回复 Mooser Lee 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

一条评论 “PowerShell使用哈希表创建有条件的代码库