diff options
author | mail_redacted_for_web | 2025-07-24 14:49:27 +0200 |
---|---|---|
committer | mail_redacted_for_web | 2025-07-24 14:49:27 +0200 |
commit | 1b082205f1e98a084695b042adec5cc122ff7717 (patch) | |
tree | ddfc10de4f5a9f7b6732ae98d6d52cf72769f58e /AzureHelpers/Public/Find-AzVm.ps1 | |
download | azure-helpers-1b082205f1e98a084695b042adec5cc122ff7717.tar.bz2 |
InComm, rather spontaneous
Diffstat (limited to 'AzureHelpers/Public/Find-AzVm.ps1')
-rw-r--r-- | AzureHelpers/Public/Find-AzVm.ps1 | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/AzureHelpers/Public/Find-AzVm.ps1 b/AzureHelpers/Public/Find-AzVm.ps1 new file mode 100644 index 0000000..73467c0 --- /dev/null +++ b/AzureHelpers/Public/Find-AzVm.ps1 @@ -0,0 +1,69 @@ +function Find-AzVm {
+ <#
+ .SYNOPSIS
+ Return an Azure VM object if we find exactly one match for a given VM name string.
+
+ .DESCRIPTION
+ We'll search for all VMs inside the subsctription we are logged into containing
+ the input string. If we find exactly one match, we will output an object as
+ delivered by `az vm list`.
+
+ .EXAMPLE
+ Find-AzVm -VmName "substring-01"
+
+ .INPUTS
+ String. The VM name we want to investigate. Part of the name is sufficient if
+ unambiguous inside the active subscription.
+
+ .OUTPUTS
+ PSCustomObject. `az vm list` object of the resulting Azure virtual machine.
+ #>
+ [OutputType([PSCustomObject])]
+ [Alias(
+ 'azvmidentify',
+ 'azvmf',
+ 'azvmi'
+ )]
+ Param (
+ [Parameter(
+ Mandatory=$true,
+ ValueFromPipeline=$true,
+ HelpMessage="String that is a VM name or is part of one unambiguous VM",
+ Position=0
+ )
+ ]
+ [ValidateLength(1,64)]
+ [string]
+ $VmName
+ )
+ $ErrorActionPreference = 'Stop'
+ $count = 0
+ $result = @()
+ foreach ($myvm in (List-AzVms | ConvertFrom-Json) ) {
+ if ($myvm.name.Contains($VmName)) {
+ $count++
+ $result += $myvm
+ }
+ }
+ switch ($result.Count) {
+ 0 {
+ throw [System.ArgumentNullException]::New("No VM found with its name containing `"$($VmName)`"")
+ }
+ 1 {
+ $true | Out-Null
+ }
+ Default {
+ throw [System.ArgumentException]::New("More than one VM found with their names containing `"$($VmName)`"")
+ }
+ }
+ # We throw exceptions whenever we don't have exactly one element - here we return the first element as there
+ # should be only one at this stage.
+ # Also, Powershell (again!): If you "return" something from a function anything else that produces output
+ # will also be returned. Why, Microsoft, why ლ(ಠ_ಠლ)
+ # > PowerShell has really wacky return semantics - at least when viewed from a more traditional programming perspective. There are two main ideas to wrap your head around:
+ # > * All output is captured, and returned
+ # > * The return keyword really just indicates a logical exit point
+ # ( https://stackoverflow.com/a/10288256 )
+ # This sorry state of a "shell" or "programming language" ...
+ return $result[0]
+}
\ No newline at end of file |