这段代码适用于 PowerShell 控制台,您将见到一个“跳舞的 Rick Ascii 艺术”并听到有趣的音乐,如果在另一个编辑器中运行以上代码,您的 AV 可能会阻止该调用并且将它识别为一个严重的威胁。这是因为下载的代码会检测它运行的环境,由于它需要在控制台中运行,所以如果在其它地方运行它,将会启动一个 PowerShell 控制台。这个操作是由杀毒引擎控制的,随后会被系统阻止。
Invoke-WebRequest 获取一个 WEB 页面的原始内容,如果获取内容消耗一定的时间,将会显示进度条。
Whenever you run a cmdlet that shows a progress bar, you can hide the progress bar by temporarily changing the $ProgressPreference variable. Just make sure you restore its original value or else, you permanently hide progress bars for the current PowerShell session: 当您运行一个会显示进度条的 cmdlet,您可以通过临时改变 $ProgressPreference 变量来隐藏进度条。只需要记得恢复它的初始值或是设置成其它值,这样就可以针对当前 PowerShell 会话隐藏进度条。
functionSafety { # step 1: add -WhatIf and -Confirm, and mark as harmful [CmdletBinding(SupportsShouldProcess,ConfirmImpact="High")] param ( [Parameter(Mandatory)] $Something )
# step 2: abort function when confirmation was rejected if (!$PSCmdlet.ShouldProcess($env:computername, "doing something harmful")) { Write-Warning"Aborted!" return }
# ...and turn it into a hash table $hashtable = $process | ForEach-Object {
$object = $_
# determine the property names in this object and create a # sorted list $columns = $_ | Get-Member-MemberType *Property | Select-Object-ExpandProperty Name | Sort-Object
# create an empty hash table $hashtable = @{}
# take all properties, and add keys to the hash table for each property $columns | ForEach-Object { # exclude empty properties if (![String]::IsNullOrEmpty($object.$_)) { # add a key (property) to the hash table with the # property value $hashtable.$_ = $object.$_ } } $hashtable }
In the previous tip we explained how you can dump all the legal values for a PowerShell attribute. Today we’ll take a look at the [Parameter()] attribute and its value DontShow. Take a look at this function: 在前一个技能中我们介绍了如何导出一个 PowerShell 属性的所有合法值。今天我们将关注 [Parameter()] 属性和它的值 DontShow。我们来看看这个函数:
dynamicparam { # this hash table defines the departments available in each company $data = @{ Microsoft = 'CEO', 'Marketing', 'Delivery' Google = 'Marketing', 'Delivery' Amazon = 'CEO', 'IT', 'Carpool' Facebook = 'CEO', 'Facility', 'Carpool' }
# check to see whether the user already chose a company if ($Company) { # yes, so create a new dynamic parameter $paramDictionary = New-Object-TypeName System.Management.Automation.RuntimeDefinedParameterDictionary $attributeCollection = New-Object-TypeName System.Collections.ObjectModel.Collection[System.Attribute]
# create the appropriate ValidateSet attribute, listing the legal values for # this dynamic parameter $attribute = New-Object System.Management.Automation.ValidateSetAttribute($data.$Company) $attributeCollection.Add($attribute)