PowerShell脚本简单应用

1.背景#

Windows系统的HyperV中的虚拟机,在正常关机、开机后不能正确(符合预期地)保存/恢复虚拟机状态;
具体表现在CentOS7 Linux虚拟机中prometheus服务启动出错(详细错误未记录);
在尝试通过HyperV的配置使达到预期未果后,转而使用其他方式;
只要使虚拟机经历正常关机和开机就能使结果符合预期;
最终使用Windows PowerShell自动化脚本的方式。

2.代码#

2.1 启动脚本:StartHyperVMs.ps1#

1
2
3
4
5
6
7
8
9
10
11
12
# Self-elevate the script if required
# 这段代码会使脚本已管理员角色运行,不添加会报权限错误
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
$Command = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
Start-Process -FilePath PowerShell.exe -Verb RunAs -ArgumentList $Command
Exit
}
}

# Place your script here
start-vm -name vhost*

2.2 关机脚本:StopHyperVMs.ps1#

1
2
3
4
5
6
7
8
9
10
11
12
# Self-elevate the script if required
# 这段代码会使脚本已管理员角色运行,不添加会报权限错误
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
$Command = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
Start-Process -FilePath PowerShell.exe -Verb RunAs -ArgumentList $Command
Exit
}
}

# Place your script here
stop-vm -name vhost*

3.配置#

3.1 打开【本地组策略编辑器】#

Win + r 输入 gpedit.msc

3.1 配置启动脚本#

计算机配置 -> Windows设置 -> 脚本(启动/关机) -> 【启动】 -> PowerShell脚本 -> 添加 -> 脚本名(配置为StartHyperVMs.p1的路径)

3.1 配置关机脚本#

计算机配置 -> Windows设置 -> 脚本(启动/关机) -> 【关机】 -> PowerShell脚本 -> 添加 -> 脚本名(配置为StopHyperVMs.p1的路径)

4.资料#