[玩转系统] 优雅的 PowerShell 圣诞节
作者:精品下载站 日期:2024-12-14 07:50:26 浏览:14 分类:玩电脑
优雅的 PowerShell 圣诞节
又到了一年中使用 PowerShell 享受假期乐趣的时候了。今年我想送你一份优雅的礼物。或者更准确地说,是一个基于类的 PowerShell 玩具。 PowerShell 5.0 中引入了类,主要考虑到 DSC 资源,但您可以将类用于各种用途。
简单来说,类是某种类型对象的定义。在 PowerShell 中,您现在可以在简单的 PowerShell 脚本文件中定义类。基本轮廓如下所示:
Class theClassName {
#define properties
#define methods (optional)
#define constructors (optional
}
构造函数是可以创建类或对象实例的代码块。它是完全可选的,因为您可以使用以下语句之一创建类的实例:
[theClassname]::New()
New-Object theClassname
但也许我应该让你打开我的班级礼物。
#requires -version 5.0
<#
ChristmasClass.ps1
A demo PowerShell class
#>
Enum ListStatus {
Naughty
Nice
}
Enum Present {
Socks
Barbie
Elmo
XBox
GIJoe
Underwear
HotWheels
EZBakeOven
Walkman
PS4
Pajamas
Stratego
GinzuKnives
ChiaPet
Tie
Mittens
Bicycle
Pony
Battleship
CabbagePatchDoll
}
Class myChristmas {
#class properties
[string]$Greeting
[string]$ElfName
[ListStatus]$List
[int]$DaysRemaining
[string]$CountDown
#class methods
[string]GetGreeting() {
$texts = @("Merry Christmas","Happy Holidays","HO-HO-HO","Vrolijk Kerstfeest",
"Joyeux Noël","Frohe Weihnachten","Hyvää Joulua","Glædelig Jul","Kala Christouyenna",
"Mele Kalikimaka","Buon Natale","Merry Xmas","Merry Christmas & A Happy New Year",
"Meri Kuri","God Jul","Nollaig Chridheil","Feliz Navidad",
"Schöni Wiehnachte","Mutlu Noeller","Nadolig Llawen","toDwI'ma' qoS yItIvqu'"
)
$text = $texts | Get-Random
return $text
}
[string]GetElfName() {
$first = "Toby","Bernard","Princess","Harvey","Chuck","Doris","Elsa",
"Snookums","Honey","Norm","Coco","Sven","Inga","Boris",
"Benedict","Sunshine","Kiki","Nutmeg","Humperdink","Jack",
"Bertha","Matilda","Clarice","Dwight","Hermey","Rupert","Lady",
"Izzy"
$mod = "Ginger","Glitter","Frosty","Sugar","Sour","Pepper",
"Minty","Crazy","Spicy","Pickle","Twinkle","Sparkle","Disco","Red",
"Green","Little","Big","Tiny","Glow","Shimmer","Dazzle","Winter","Jingle",
"Puffy","Fluffy","Saucy","Crinkle"
$last = "pants","toes","bottom","beard","nose","puss","lips",
"ears","socks","stockings","belly","cheeks","bells","chin",
"mctush","sticks","fish","whisker","boots","slippers","knicker",
"knocker"
$name = "{0} {1}{2}" -f (Get-Random $first),(Get-Random $mod),(Get-Random $last)
return $name
}
[void]Refresh() {
#calculate christmas for the current year that should be culture aware
$Christmas = [datetime]::new( (Get-Date).Year,12,25)
$span = $Christmas - (Get-Date)
$this.DaysRemaining = $span.totalDays
#strip off milliseconds
$timestring = $span.ToString()
$this.CountDown = $timestring.Substring(0,$timestring.LastIndexOf("."))
$this.Greeting = $this.GetGreeting()
}
#overloaded method
[Present]GetPresent() {
$presents = [enum]::GetNames([present]) | Get-Random
return $presents
}
[Present[]]GetPresent([int]$Count) {
$presents = [enum]::GetNames([present]) | Get-Random -count $Count
return $presents
}
[void]Play() {
#The first number is the reciprocal of the duration and the rest is the
#note and octave (which we use for getting the frequency).
#For example, 4A4 is a quarter A note
#first verse only
$notes = write 4A4 4A4 2A4 4A4 4A4 2A4 4A4 4C4 4F3 8G3 1A4 `
4Bb4 4Bb4 4Bb4 8Bb4 4Bb4 4A4 4A4 8A4 8A4 4A4 4G3 4G3 4A4 2G3 2C4 `
4A4 4A4 2A4 4A4 4A4 2A4 4A4 4C4 4F3 4G3 1A4 4Bb4 4Bb4 4Bb4 4Bb4 `
4Bb4 4A4 4A4 8A4 8A4 4C4 4C4 4Bb4 4G3 1F3
function Play([int] $freq, [int] $duration)
{
[console]::Beep($freq, $duration);
}
#
# Note is given by fn=f0 * (a)^n
# a is the twelth root of 2
# n is the number of half steps from f0, positive or negative.
# f0 used here is A4 at 440 Hz
#
$f0 = 440;
$a = [math]::pow(2,(1/12)); # Twelth root of 2
function GetNoteFreq([string]$note)
{
# n is the number of half steps from the fixed note.
$note -match '([A-G#]{1,2})(\d+)' | out-null
$octave = ([int] $matches[2]) - 4;
$n = $octave * 12 + ( GetHalfStepsFromA $matches[1] );
$freq = $f0 * [math]::Pow($a, $n);
return $freq;
}
function GetHalfStepsFromA([string] $note)
{
switch($note)
{
'A' { 0 }
'A#' { 1 }
'Bb' { 1 }
'B' { 2 }
'C' { 3 }
'C#' { 4 }
'Db' { 4 }
'D' { 5 }
'D#' { 6 }
'Eb' { 6 }
'E' { 7 }
'F' { 8 }
'F#' { 9 }
'Gb' { 9 }
'G' { 10 }
'G#' { 11 }
'Ab' { 11 }
}
}
$StandardDuration = 1000;
foreach($note in $notes)
{
$note -match '(\d)(.+)' | out-null
$duration = $StandardDuration / ([int] $matches[1]);
$playNote = $matches[2];
$freq = GetNoteFreq $playNote;
#write-host $playNote $freq $duration;
Play $freq $duration
start-sleep -milli 50
}
}
[void]Show() {
cls
$Msg1 =
@"
.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:.
. * .
. /.\ Merry Christmas .
. /..'\ from all of us .
. /'.'\ in PowerShell .
. /.''.'\ .
. /.'.'.\ .
. /'.''.'.\ .
. ^^^[_]^^^ .
. .
. .
. .
.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:.
"@
$Msg2 =
@"
_...
o_.-"` `\
.--. _ `'-._.-'""-; _
.' \`_\_ {_.-a"a-} _ / \
_/ .-' '. {c-._o_.){\|` |
(@`-._ / \{ ^ } \ _/
`~\ '-._ /'. } \} .-.
|>:< '-.__/ '._,} \_/ / ())
| >:< `'---. ____'-.|(`"`
\ >:< \_\_\ | ;
\ \-{}-\/ \
\ '._\' /)
'. /(
`-._ _____ _ _____ __.'\ \
/ \ / \ / \ \ \
_.'/^\'._.'/^\'._.'/^\'.__) \
,==' `---` '---' '---' )
`"""""""""""""""""""""""""""""""`
"@
$msg3 =
@"
___
/` `'.
/ _..---;
| /__..._/ .--.-.
|.' e e | ___\_|/____
(_)'--.o.--| | | |
.-( `-' = `-|____| |____|
/ ( |____ ____|
| ( |_ | | __|
| '-.--';/'/__ | | ( `|
| '. \ )"";--`\ /
\ ; |--' `;.-'
|`-.__ ..-'--'`;..--'`
"@
$msg4 =
@"
* ,
_/^\_
< >
* /.-.\ *
* `/&\` *
,@.*;@,
/_o.I %_\ *
* (`'--:o(_@;
/`;--.,__ `') *
;@`o % O,*`'`&\
* (`'--)_@ ;o %'()\ *
/`;--._`''--._O'@;
/&*,()~o`;-.,_ `""`)
* /`,@ ;+& () o*`;-';\
(`""--.,_0 +% @' &()\
/-.,_ ``''--....-'`) *
* /@%;o`:;'--,.__ __.'\
;*,&(); @ % &^;~`"`o;@(); *
/(); o^~; & ().o@*&`;&%O\
`"="==""==,,,.,="=="==="`
__.----.(\-''#####---...___...-----._
'` \)_`"""""`
.--' ')
o( )_-\
`"""` `
"@
$msg5 =
@"
.--------.
* . |________| . *
| __|/\
* .-'======\_\o/.
/___________<>__\
|||||| / (o) (o) \
|||||| | _ O _ | .
. |||||| | (_) (_) |
|||||| \ '---' / *
\====/ [~~~~~~~~~]
\// _/~||~`|~~~~~\_
_||-'`/ || | \`'-._ *
* .-` )| ; || |) ; '.
/ `--.| || | | `\
| \ |||||) |-, \ .
\ .; _ ; |_, |
`'''||` ,\ (_) /, `.__/
||.` '. .' `. *
* || ` ' ' ` \
|| ;
. * || | .
|| | *
|| |
.__.-""-.__.-"""|| ;.-"""-.__.-""-.__.
|| /
||'. .'
|| '-._ _ _ _ _.-'
`""`
"@
$msg6 =
@"
_
.-(_)
/ _/
.-' \
/ '.
,-~--~-~-~-~-,
{__.._...__..._} ,888,
,888, /\##" 6 6 "##/\ ,88' `88,
,88' '88,__ |(\` (__) `/)| __,88' `88
,88' .8(_ \_____\_ '----' _/_____/ _)8. 8'
88 (___)\ \ '-.__ __.-' / /(___)
88 (___)88 | '--' | 88(___)
8' (__)88,___/ \___,88(__)
__`88,_/__________________\_,88`__
/ `88, |88| ,88' \
/ `88, |88| ,88' \
/____________`88,_/_,88`____________\
/88888888888888888;8888;88888888888888888\
/^^^^^^^^^^^^^^^^^^`/88\^^^^^^^^^^^^^^^^^^\
/ |88| \============, \
/_ __ __ __ _ __ |88|_|^ MERRY | _ ___\
|;:. |88| | CHRISTMAS! | |
|;;:. |88| '============' |
|;;:. |88| |
|::. |88| |
|;;:' |88| |
|:;, |88| |
'---------------------""""---------------------'
"@
$i = Get-Random -Minimum 1 -Maximum 6
$selected = ($msg1,$msg2,$msg3,$msg4,$msg5,$msg6 | Get-Random)
If([bool]!($i%2)) {
Write-Host -ForegroundColor Green -Object $selected
} else {
Write-Host -ForegroundColor Red -Object $selected
}
}
#class constructor
myChristmas() {
$this.ElfName = $this.GetElfName()
if ( (Get-Date).Second%2) {
$this.List = [ListStatus]::Naughty
}
else {
$this.List = [ListStatus]::Nice
}
#set the rest of the properties by invoking the defined
#Refresh() method
$this.Refresh()
}
}
[myChristmas]::new()
您将需要 PowerShell 5.0 或更高版本才能运行此文件。该脚本定义了类,然后创建它的实例,因此我将运行该脚本并将结果保存到变量中。
属性在类中定义。当我调用 New() 方法来创建对象的实例时,将执行构造函数会话中的代码。 $this 对象将引用新实例。在我的例子中,我调用一个名为 GetElfName() 的内部方法来设置 ElfName 属性。如果您查看该方法,您会发现它以对象时间(字符串)开头。在 PowerShell 类中使用方法时,必须指定它将返回的对象类型,或者使用 [void] 不返回任何内容。另请注意,如果您的方法将对象写入管道,则必须使用 return 关键字。
List 属性是从枚举设置的。这是一种创建预先确定的可能值数组的方法。就我而言,顽皮或友善,这或多或少是随机分配的。
其余属性通过调用内部 Refresh() 方法来设置,该方法计算距离圣诞节还剩多少天。如果通过管道将该对象传递给 Get-Member,您将看到该对象如何与类定义匹配。
我不想破坏所有的惊喜,所以我会让你尝试一些方法。但至少让我指出 GetPresent() 方法。如果您查看屏幕截图,您会发现有两种运行方法。这称为过载。如果查看类定义中的代码,您将看到该方法的多个条目,具有不同的参数选项。
顺便说一句,该方法只是从另一个枚举中返回一个或多个随机选择的项目作为礼物。希望你会得到你喜欢的东西。
享受我的礼物,祝您节日快乐,度过美好的 2017 年。
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[影视] 黑道中人 Alto Knights(2025)剧情 犯罪 历史 电影
[古装剧] [七侠五义][全75集][WEB-MP4/76G][国语无字][1080P][焦恩俊经典]
[实用软件] 虚拟手机号 电话 验证码 注册
[电视剧] 安眠书店/你 第五季 You Season 5 (2025) 【全10集】
[电视剧] 棋士(2025) 4K 1080P【全22集】悬疑 犯罪 王宝强 陈明昊
[软件合集] 25年6月5日 精选软件22个
[软件合集] 25年6月4日 精选软件36个
[短剧] 2025年06月04日 精选+付费短剧推荐33部
[短剧] 2025年06月03日 精选+付费短剧推荐25部
[软件合集] 25年6月3日 精选软件44个
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[实用软件] 虚拟手机号 电话 验证码 注册
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[影视] 内地绝版高清录像带 [mpg]
[书籍] 古今奇书禁书三教九流资料大合集 猎奇必备珍藏资源PDF版 1.14G
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag