Merge pull request #9925 from chrisroberts/u-powershelling

Misc. PowerShell cleanup
This commit is contained in:
Chris Roberts 2018-06-13 14:51:43 -07:00 committed by GitHub
commit 4d3f5d33c6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 48 additions and 99 deletions

View File

@ -68,7 +68,7 @@ module Vagrant
"-NoProfile", "-NoProfile",
"-NonInteractive", "-NonInteractive",
"-ExecutionPolicy", "Bypass", "-ExecutionPolicy", "Bypass",
"#{resize_console}#{env}&('#{path}')", "#{env}&('#{path}')",
args args
].flatten ].flatten
@ -104,7 +104,7 @@ module Vagrant
"-NonInteractive", "-NonInteractive",
"-ExecutionPolicy", "Bypass", "-ExecutionPolicy", "Bypass",
"-Command", "-Command",
"#{resize_console}#{env}#{command}" "#{env}#{command}"
].flatten.compact ].flatten.compact
r = Subprocess.execute(*c) r = Subprocess.execute(*c)
@ -135,7 +135,7 @@ module Vagrant
"-NonInteractive", "-NonInteractive",
"-ExecutionPolicy", "Bypass", "-ExecutionPolicy", "Bypass",
"-Command", "-Command",
"#{resize_console}#{env}#{command}" "#{env}#{command}"
].flatten.compact ].flatten.compact
c << opts c << opts
@ -254,19 +254,6 @@ module Vagrant
def self.reset! def self.reset!
instance_variables.each(&method(:remove_instance_variable)) instance_variables.each(&method(:remove_instance_variable))
end end
# @private
# This is a helper method that provides the PowerShell command to resize
# the "console" to prevent output wrapping or truncating. An environment
# variable guard is provided to disable the behavior in cases where it
# may cause unexpected results (VAGRANT_POWERSHELL_RESIZE_DISABLE)
def self.resize_console
if ENV["VAGRANT_POWERSHELL_RESIZE_DISABLE"]
""
else
"$host.UI.RawUI.BufferSize = New-Object System.Management.Automation.Host.Size(512,50); "
end
end
end end
end end
end end

View File

@ -129,7 +129,7 @@ module VagrantPlugins
# #
# @return [Hash] # @return [Hash]
def self.get_smbshares def self.get_smbshares
result = Vagrant::Util::PowerShell.execute_cmd("Get-SmbShare|Format-List") result = Vagrant::Util::PowerShell.execute_cmd("Get-SmbShare|Format-List|Out-String -Width 4096")
if result.nil? if result.nil?
return nil return nil
end end
@ -151,7 +151,7 @@ module VagrantPlugins
# #
# @return [Hash] # @return [Hash]
def self.get_netshares def self.get_netshares
result = Vagrant::Util::PowerShell.execute_cmd("net share") result = Vagrant::Util::PowerShell.execute_cmd("net share | Out-String -Width 4096")
if result.nil? if result.nil?
return nil return nil
end end
@ -164,7 +164,7 @@ module VagrantPlugins
shares = {} shares = {}
share_names.each do |share_name| share_names.each do |share_name|
shares[share_name] = {} shares[share_name] = {}
result = Vagrant::Util::PowerShell.execute_cmd("net share #{share_name}") result = Vagrant::Util::PowerShell.execute_cmd("net share #{share_name} | Out-String -Width 4096")
next if result.nil? next if result.nil?
result.each_line do |line| result.each_line do |line|
key, value = line.strip.split(/\s+/, 2) key, value = line.strip.split(/\s+/, 2)

View File

@ -5,4 +5,4 @@ $result = @{
result = $check result = $check
} }
Write-Output-Message $(ConvertTo-Json $result) Write-OutputMessage $(ConvertTo-Json $result)

View File

@ -13,6 +13,6 @@ $ErrorActionPreference = "Stop"
try { try {
Hyper-V\New-VHD -Path $Destination -ParentPath $Source Hyper-V\New-VHD -Path $Destination -ParentPath $Source
} catch { } catch {
Write-Error-Message "Failed to clone drive: ${PSItem}" Write-ErrorMessage "Failed to clone drive: ${PSItem}"
exit 1 exit 1
} }

View File

@ -26,7 +26,7 @@ $ErrorActionPreference = "Stop"
try { try {
$VM = Hyper-V\Get-VM -Id $VMID $VM = Hyper-V\Get-VM -Id $VMID
} catch { } catch {
Write-Error-Message "Failed to locate VM: ${PSItem}" Write-ErrorMessage "Failed to locate VM: ${PSItem}"
exit 1 exit 1
} }
@ -34,7 +34,7 @@ if($Processors) {
try { try {
Set-VagrantVMCPUS -VM $VM -CPUCount ($Processors -as [int]) Set-VagrantVMCPUS -VM $VM -CPUCount ($Processors -as [int])
} catch { } catch {
Write-Error-Message "Failed to configure CPUs: ${PSItem}" Write-ErrorMessage "Failed to configure CPUs: ${PSItem}"
exit 1 exit 1
} }
} }
@ -43,7 +43,7 @@ if($Memory -or $MaxMemory) {
try { try {
Set-VagrantVMMemory -VM $VM -Memory $Memory -MaxMemory $MaxMemory Set-VagrantVMMemory -VM $VM -Memory $Memory -MaxMemory $MaxMemory
} catch { } catch {
Write-Error-Message "Failed to configure memory: ${PSItem}" Write-ErrorMessage "Failed to configure memory: ${PSItem}"
exit 1 exit 1
} }
} }
@ -52,7 +52,7 @@ if($AutoStartAction -or $AutoStopAction) {
try { try {
Set-VagrantVMAutoActions -VM $VM -AutoStartAction $AutoStartAction -AutoStopAction $AutoStopAction Set-VagrantVMAutoActions -VM $VM -AutoStartAction $AutoStartAction -AutoStopAction $AutoStopAction
} catch { } catch {
Write-Error-Message "Failed to configure automatic actions: ${PSItem}" Write-ErrorMessage "Failed to configure automatic actions: ${PSItem}"
exit 1 exit 1
} }
} }
@ -66,7 +66,7 @@ if($VirtualizationExtensions) {
try { try {
Set-VagrantVMVirtExtensions -VM $VM -Enabled $virtex Set-VagrantVMVirtExtensions -VM $VM -Enabled $virtex
} catch { } catch {
Write-Error-Message "Failed to configure virtualization extensions: ${PSItem}" Write-ErrorMessage "Failed to configure virtualization extensions: ${PSItem}"
exit 1 exit 1
} }
@ -75,7 +75,7 @@ if($SwitchID) {
$SwitchName = Get-VagrantVMSwitch -NameOrID $SwitchID $SwitchName = Get-VagrantVMSwitch -NameOrID $SwitchID
Set-VagrantVMSwitch -VM $VM -SwitchName $SwitchName Set-VagrantVMSwitch -VM $VM -SwitchName $SwitchName
} catch { } catch {
Write-Error-Message "Failed to configure network adapter: ${PSItem}" Write-ErrorMessage "Failed to configure network adapter: ${PSItem}"
} }
} }
@ -90,6 +90,6 @@ if($EnableCheckpoints) {
try { try {
Hyper-V\Set-VM -VM $VM -CheckpointType $checkpoints Hyper-V\Set-VM -VM $VM -CheckpointType $checkpoints
} catch { } catch {
Write-Error-Message "Failed to ${CheckpointAction} checkpoints on VM: ${PSItem}" Write-ErrorMessage "Failed to ${CheckpointAction} checkpoints on VM: ${PSItem}"
exit 1 exit 1
} }

View File

@ -12,6 +12,6 @@ try {
$VM = Hyper-V\Get-VM -Id $VmId $VM = Hyper-V\Get-VM -Id $VmId
Hyper-V\Checkpoint-VM $VM -SnapshotName $SnapName Hyper-V\Checkpoint-VM $VM -SnapshotName $SnapName
} catch { } catch {
Write-Error-Message "Failed to create snapshot: ${PSItem}" Write-ErrorMessage "Failed to create snapshot: ${PSItem}"
exit 1 exit 1
} }

View File

@ -12,5 +12,5 @@ try {
$VM = Hyper-V\Get-VM -Id $VmId $VM = Hyper-V\Get-VM -Id $VmId
Hyper-V\Remove-VMSnapshot $VM -Name $SnapName Hyper-V\Remove-VMSnapshot $VM -Name $SnapName
} catch { } catch {
Write-Error-Message "Failed to delete snapshot: ${PSItem}" Write-ErrorMessage "Failed to delete snapshot: ${PSItem}"
} }

View File

@ -11,6 +11,6 @@ try {
$VM = Hyper-V\Get-VM -Id $VmId $VM = Hyper-V\Get-VM -Id $VmId
Hyper-V\Remove-VM $VM -Force Hyper-V\Remove-VM $VM -Force
} catch { } catch {
Write-Error-Message "Failed to delete VM: ${PSItem}" Write-ErrorMessage "Failed to delete VM: ${PSItem}"
exit 1 exit 1
} }

View File

@ -13,7 +13,7 @@ try {
$vm = Hyper-V\Get-VM -Id $VmId $vm = Hyper-V\Get-VM -Id $VmId
$vm | Hyper-V\Export-VM -Path $Path $vm | Hyper-V\Export-VM -Path $Path
} catch { } catch {
Write-Error-Message "Failed to export VM: ${PSItem}" Write-ErrorMessage "Failed to export VM: ${PSItem}"
exit 1 exit 1
} }
@ -24,6 +24,6 @@ try {
Remove-Item -Path $Path/Snapshots -Force -Recurse Remove-Item -Path $Path/Snapshots -Force -Recurse
Remove-Item -Path $Path/$name -Force Remove-Item -Path $Path/$name -Force
} catch { } catch {
Write-Error-Message "Failed to format exported box: ${PSItem}" Write-ErrorMessage "Failed to format exported box: ${PSItem}"
exit 1 exit 1
} }

View File

@ -120,4 +120,4 @@ $resultHash = @{
message = "OK" message = "OK"
} }
$result = ConvertTo-Json $resultHash $result = ConvertTo-Json $resultHash
Write-Output-Message $result Write-OutputMessage $result

View File

@ -10,7 +10,7 @@ $ErrorActionPreference = "Stop"
try { try {
$vm = Hyper-V\Get-VM -Id $VmId $vm = Hyper-V\Get-VM -Id $VmId
} catch { } catch {
Write-Error-Message "Failed to locate VM: ${PSItem}" Write-ErrorMessage "Failed to locate VM: ${PSItem}"
exit 1 exit 1
} }
@ -57,12 +57,12 @@ try {
ip = $guest_ipaddress ip = $guest_ipaddress
} }
$result = ConvertTo-Json $resultHash $result = ConvertTo-Json $resultHash
Write-Output-Message $result Write-OutputMessage $result
} else { } else {
Write-Error-Message "Failed to determine IP address" Write-ErrorMessage "Failed to determine IP address"
exit 1 exit 1
} }
} catch { } catch {
Write-Error-Message "Unexpected error while detecting network configuration: ${PSItem}" Write-ErrorMessage "Unexpected error while detecting network configuration: ${PSItem}"
exit 1 exit 1
} }

View File

@ -25,8 +25,8 @@ try {
mac = "$mac_address" mac = "$mac_address"
} }
$result = ConvertTo-Json $resultHash $result = ConvertTo-Json $resultHash
Write-Output-Message $result Write-OutputMessage $result
} catch { } catch {
Write-Error-Message "Unexpected error while fetching MAC: ${PSItem}" Write-ErrorMessage "Unexpected error while fetching MAC: ${PSItem}"
exit 1 exit 1
} }

View File

@ -7,4 +7,4 @@
$Switches = @(Hyper-V\Get-VMSwitch ` $Switches = @(Hyper-V\Get-VMSwitch `
| Select-Object Name,SwitchType,NetAdapterInterfaceDescription,Id) | Select-Object Name,SwitchType,NetAdapterInterfaceDescription,Id)
Write-Output-Message $(ConvertTo-JSON $Switches) Write-OutputMessage $(ConvertTo-JSON $Switches)

View File

@ -46,4 +46,4 @@ $resultHash = @{
status = "$Status" status = "$Status"
} }
$result = ConvertTo-Json $resultHash $result = ConvertTo-Json $resultHash
Write-Output-Message $result Write-OutputMessage $result

View File

@ -6,4 +6,4 @@ $result = @{
result = $check result = $check
} }
Write-Output-Message $(ConvertTo-Json $result) Write-OutputMessage $(ConvertTo-Json $result)

View File

@ -30,8 +30,8 @@ try {
$Result = @{ $Result = @{
id = $VM.Id.Guid; id = $VM.Id.Guid;
} }
Write-Output-Message (ConvertTo-Json $Result) Write-OutputMessage (ConvertTo-Json $Result)
} catch { } catch {
Write-Error-Message "${PSItem}" Write-ErrorMessage "${PSItem}"
exit 1 exit 1
} }

View File

@ -11,9 +11,9 @@ try {
$VM = Hyper-V\Get-VM -Id $VmId $VM = Hyper-V\Get-VM -Id $VmId
$Snapshots = @(Hyper-V\Get-VMSnapshot $VM | Select-Object Name) $Snapshots = @(Hyper-V\Get-VMSnapshot $VM | Select-Object Name)
} catch { } catch {
Write-Error-Message "Failed to get snapshot list: ${PSItem}" Write-ErrorMessage "Failed to get snapshot list: ${PSItem}"
exit 1 exit 1
} }
$result = ConvertTo-json $Snapshots $result = ConvertTo-json $Snapshots
Write-Output-Message $result Write-OutputMessage $result

View File

@ -12,6 +12,6 @@ try {
$VM = Hyper-V\Get-VM -Id $VmId $VM = Hyper-V\Get-VM -Id $VmId
Hyper-V\Restore-VMSnapshot $VM -Name $SnapName -Confirm:$false Hyper-V\Restore-VMSnapshot $VM -Name $SnapName -Confirm:$false
} catch { } catch {
Write-Error-Message "Failed to restore snapshot: ${PSItem}" Write-ErrorMessage "Failed to restore snapshot: ${PSItem}"
exit 1 exit 1
} }

View File

@ -11,6 +11,6 @@ try {
$VM = Hyper-V\Get-VM -Id $VmId $VM = Hyper-V\Get-VM -Id $VmId
Hyper-V\Resume-VM $VM Hyper-V\Resume-VM $VM
} catch { } catch {
Write-Error-Message "Failed to resume VM: ${PSItem}" Write-ErrorMessage "Failed to resume VM: ${PSItem}"
exit 1 exit 1
} }

View File

@ -12,13 +12,13 @@ $ErrorActionPreference = "Stop"
try { try {
$VM = Hyper-V\Get-VM -Id $VMID $VM = Hyper-V\Get-VM -Id $VMID
} catch { } catch {
Write-Error-Message "Failed to locate VM: ${PSItem}" Write-ErrorMessage "Failed to locate VM: ${PSItem}"
exit 1 exit 1
} }
try { try {
Hyper-V\Set-VM -VM $VM -NewVMName $VMName Hyper-V\Set-VM -VM $VM -NewVMName $VMName
} catch { } catch {
Write-Error-Message "Failed to assign new VM name ${VMName}: ${PSItem}" Write-ErrorMessage "Failed to assign new VM name ${VMName}: ${PSItem}"
exit 1 exit 1
} }

View File

@ -13,6 +13,6 @@ try {
$vm = Hyper-V\Get-VM -Id $VmId $vm = Hyper-V\Get-VM -Id $VmId
Hyper-V\Set-VMNetworkAdapter $vm -StaticMacAddress $Mac Hyper-V\Set-VMNetworkAdapter $vm -StaticMacAddress $Mac
} catch { } catch {
Write-Error-Message "Failed to set VM MAC address: ${PSItem}" Write-ErrorMessage "Failed to set VM MAC address: ${PSItem}"
exit 1 exit 1
} }

View File

@ -18,5 +18,5 @@ try {
Hyper-V\Set-VMNetworkAdapterVlan $vm -Access -Vlanid $VlanId Hyper-V\Set-VMNetworkAdapterVlan $vm -Access -Vlanid $VlanId
} }
catch { catch {
Write-Error-Message "Failed to set VM's Vlan ID $_" Write-ErrorMessage "Failed to set VM's Vlan ID $_"
} }

View File

@ -14,7 +14,7 @@ $ErrorActionPreference = "Stop"
try { try {
$VM = Hyper-V\Get-VM -Id $VMID $VM = Hyper-V\Get-VM -Id $VMID
} catch { } catch {
Write-Error-Message "Failed to locate VM: ${PSItem}" Write-ErrorMessage "Failed to locate VM: ${PSItem}"
exit 1 exit 1
} }
@ -22,6 +22,6 @@ try {
Set-VagrantVMService -VM $VM -Name $Name -Enable $Enable Set-VagrantVMService -VM $VM -Name $Name -Enable $Enable
} catch { } catch {
if($Enable){ $action = "enable" } else { $action = "disable" } if($Enable){ $action = "enable" } else { $action = "disable" }
Write-Error-Message "Failed to ${action} VM integration service ${Name}: ${PSItem}" Write-ErrorMessage "Failed to ${action} VM integration service ${Name}: ${PSItem}"
exit 1 exit 1
} }

View File

@ -19,8 +19,8 @@ try {
name = "$name" name = "$name"
} }
$result = ConvertTo-Json $resultHash $result = ConvertTo-Json $resultHash
Write-Output-Message $result Write-OutputMessage $result
} catch { } catch {
Write-Error-Message "Failed to start VM ${PSItem}" Write-ErrorMessage "Failed to start VM ${PSItem}"
exit 1 exit 1
} }

View File

@ -12,6 +12,6 @@ try{
$VM = Hyper-V\Get-VM -Id $VmId $VM = Hyper-V\Get-VM -Id $VmId
Hyper-V\Stop-VM $VM -Force Hyper-V\Stop-VM $VM -Force
} catch { } catch {
Write-Error-Message "Failed to stop VM: ${PSItem}" Write-ErrorMessage "Failed to stop VM: ${PSItem}"
exit 1 exit 1
} }

View File

@ -11,6 +11,6 @@ try{
$VM = Hyper-V\Get-VM -Id $VmId $VM = Hyper-V\Get-VM -Id $VmId
Hyper-V\Suspend-VM $VM Hyper-V\Suspend-VM $VM
} catch { } catch {
Write-Error-Message "Failed to suspend VM: ${PSItem}" Write-ErrorMessage "Failed to suspend VM: ${PSItem}"
exit 1 exit 1
} }

View File

@ -3,7 +3,7 @@
# All Rights Reserved. Licensed under the MIT License. # All Rights Reserved. Licensed under the MIT License.
#-------------------------------------------------------------------------- #--------------------------------------------------------------------------
function Write-Error-Message { function Write-ErrorMessage {
param ( param (
[parameter (Mandatory=$true,Position=0)] [parameter (Mandatory=$true,Position=0)]
[string] $Message [string] $Message
@ -16,7 +16,7 @@ function Write-Error-Message {
Write-Host "===End-Error===" Write-Host "===End-Error==="
} }
function Write-Output-Message { function Write-OutputMessage {
param ( param (
[parameter (Mandatory=$true,Position=0)] [parameter (Mandatory=$true,Position=0)]
[string] $Message [string] $Message

View File

@ -120,14 +120,6 @@ describe Vagrant::Util::PowerShell do
described_class.execute("custom-command") described_class.execute("custom-command")
end end
it "should automatically include console resize" do
expect(Vagrant::Util::Subprocess).to receive(:execute) do |*args|
comm = args.detect{|s| s.to_s.include?("custom-command") }
expect(comm.to_s).to include("BufferSize")
end
described_class.execute("custom-command")
end
it "should accept custom environment" do it "should accept custom environment" do
expect(Vagrant::Util::Subprocess).to receive(:execute) do |*args| expect(Vagrant::Util::Subprocess).to receive(:execute) do |*args|
comm = args.detect{|s| s.to_s.include?("custom-command") } comm = args.detect{|s| s.to_s.include?("custom-command") }
@ -173,15 +165,6 @@ describe Vagrant::Util::PowerShell do
described_class.execute_cmd("custom-command") described_class.execute_cmd("custom-command")
end end
it "should automatically include console resize" do
expect(Vagrant::Util::Subprocess).to receive(:execute) do |*args|
comm = args.detect{|s| s.to_s.include?("custom-command") }
expect(comm.to_s).to include("BufferSize")
result
end
described_class.execute_cmd("custom-command")
end
it "should accept custom environment" do it "should accept custom environment" do
expect(Vagrant::Util::Subprocess).to receive(:execute) do |*args| expect(Vagrant::Util::Subprocess).to receive(:execute) do |*args|
comm = args.detect{|s| s.to_s.include?("custom-command") } comm = args.detect{|s| s.to_s.include?("custom-command") }
@ -245,15 +228,6 @@ describe Vagrant::Util::PowerShell do
described_class.execute_inline("custom-command") described_class.execute_inline("custom-command")
end end
it "should automatically include console resize" do
expect(Vagrant::Util::Subprocess).to receive(:execute) do |*args|
comm = args.detect{|s| s.to_s.include?("custom-command") }
expect(comm.to_s).to include("BufferSize")
result
end
described_class.execute_inline("custom-command")
end
it "should accept custom environment" do it "should accept custom environment" do
expect(Vagrant::Util::Subprocess).to receive(:execute) do |*args| expect(Vagrant::Util::Subprocess).to receive(:execute) do |*args|
comm = args.detect{|s| s.to_s.include?("custom-command") } comm = args.detect{|s| s.to_s.include?("custom-command") }
@ -299,16 +273,4 @@ describe Vagrant::Util::PowerShell do
end end
end end
describe ".resize_console" do
it "should return command string" do
expect(described_class.resize_console).to include("BufferSize")
end
it "should return empty string when disabled" do
with_temp_env("VAGRANT_POWERSHELL_RESIZE_DISABLE" => "1") do
expect(described_class.resize_console).to be_empty
end
end
end
end end