I am running this from PowerShell with gcloud CLI installed on my local Windows machine.
If I run disks.list by itself as followed, I get the expected output.
gcloud compute disks list `
--project=prj-d-jenkins-poc `
--filter="-users:*" `
--format="csv(name,sizeGb,zone,status,type,lastAttachTimestamp,lastDetachTimestamp)"
If I run it as part of a script, I get an error.
Script:
#Initiated OUTPUT variable as ArrayList to collect results
$OUTPUT = New-Object -TypeName "System.Collections.ArrayList"
$OUTPUT.Add("name,sizeGb,zone,status,type,lastAttachTimestamp,lastDetachTimestamp")
#Get list of accessible projects to PROJECTS
$PROJECTS = gcloud projects list --format="value(projectId)"
#Iterate through projects list
foreach ($i in $PROJECTS)
{
#Get list of unattached disks
$list = gcloud compute disks list `
--project=$i `
--filter="-users:*" `
--format="csv(name,sizeGb,zone,status,type,lastAttachTimestamp,lastDetachTimestamp)"
#If list is not empty, add it to OUTPUT
if ($list.count -gt 0){
$list = [System.Collections.ArrayList]$list #Convert a to ArrayList
$list.RemoveAt($list.0) #Remove first entry for a
$OUTPUT += $list #append a to OUTPUT
Write-Host "Unattached disks in $i wrote to OUTPUT variable."
}
else{ #If list is empty, skip
Write-Host "No unattached disks found in $i."
}
}
$OUTPUT
Error I get sometimes as it iterates through the project list:
python.exe : WARNING: The following filter keys were not present in any resource : users
At C:\Users\minh.tran\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gcloud.ps1:117 char:3
+ & "$cloudsdk_python" $run_args_array
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (WARNING: The fo...esource : users:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
I think this is because it was iterating through projects where there was no unattached disks, and that threw the error.
How do I modify my code so it will ignore these projects without unattached disks?