Search code examples
powershellpowercli

Invoke-VMScript: Do not confirm/re-enter guest credentials


I'm performing an audit on VMs in our environment, and using Invoke-VMScript to get disk info:

$vmErrors = New-Object System.Collections.Generic.List[System.Object]

$report = foreach ($VM in $VMs){
    $name = $vm.Name
    Write-Host "Retrieving data for $name... " -NoNewline
    try{
        $output = Invoke-VMScript -ScriptText @'
            Get-Disk | Foreach-Object{
                [PSCustomObject]@{
                    ComputerName   = $env:COMPUTERNAME
                    Number         = $_.number
                    Size           = [int]($_.size/1GB)
                    PartitionStyle = $_.PartitionStyle
                }
            } | ConvertTo-Csv -NoTypeInformation
'@ -VM $name -GuestUser $Username -GuestPassword $Password -WarningAction SilentlyContinue -ErrorAction Stop

        if($output.ScriptOutput -match 'PartitionStyle')
        {
            $output.ScriptOutput -replace '(?s)^.+(?="Com)' | ConvertFrom-Csv
        }
        Write-Host "Done" -ForegroundColor Green
    }catch{
        $vmErrors.Add($name)
        Write-Host "Error!" -ForegroundColor Red
    }
}

When running the code in Powershell ISE, I do not need to confirm the credentials for each VM and the script loops perfectly fine, however if I run the script in a standard Powershell window, for each VM I have to enter the username and password for each VM (the credentials will always be the same as what I use to authenticate with the vCenter server. Example:

Retrieving data for VM NAME...
Specify Credential
Please specify guest credential
User:

How can I run this in a normal window and avoid having to re-enter my credentials each time?

Edit

Example of setting username & password:

$Username = ""
$Password = ""
Function GetUser{
    do{
        $global:Username = Read-Host "What is your username? (DOMAIN\Username)"
    }while($global:Username -eq "")
}

Function GetPassword{
    do{
        $global:Password = Read-Host "What is your password?" -AsSecureString
        $global:Password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($global:Password))
    }while($global:Password -eq "")
}

Solution

  • Solved by changing the credential references in Invoke-VMScript to use $global:Username and $global:Password