I'm preparing a report for disks in Azure and I want to include a VM name onto which disk is assigned. I found a property called managedby in get-azurermdisk cmdlet, but it represent a whole directory, not the VM name only (which is included at the very end). I want to split a whole string by '/' and want to leave only the very last part of property.
This is the script i prepared:
$DISK = Get-AzureRmDisk
$Output = $DISK | ForEach-Object {
[PSCustomObject]@{
"Name" = $_.Name
"Resource Group Name" =$_.ResourceGroupName
"Disk Tier" = $_.Sku.Tier
"Disk Type" = $_.Sku.Name
"Managed By" = $_.ManagedBy
"Time Created" = $_.TimeCreated
"Disk Size (in GB)" = $_.DiskSizeGB
"I/O per second" = $_.DiskIOPSReadWrite
"MBps per second" = $_.DiskMBpsReadWrite
"Location" = $_.Location
}
}
I already tried to do split:
"Managed By" = ($_.ManagedBy).Split('/')[8]
And separate loops to fill the "Managed By" column:
foreach($dsk in $dsks){
$vm = $DISK | Where-Object -Property id -EQ $dsk.Name
$prv = $dsk.ManagedBy.Split('/')[6]
$managed.Add($vm.Name,$prv)
}
foreach($vm in $Output)
{
if($ips.ContainsKey($vm."Name"))
{
$vm."Managed By"=$ips[$vm."Managed By"]
}
}
Error:
You cannot call a method on a null-valued expression.
How can I add a some kind of ignore when value is null statement?
The error means that the ManagedBy
is null when you try to split on it.
Just add if else
for ManagedBy
in this code block $Output = $DISK | ForEach-Object{}
,
like below:
$Output = $DISK | ForEach-Object {
[PSCustomObject]@{
"Name" = $_.Name
"Resource Group Name" =$_.ResourceGroupName
"Disk Tier" = $_.Sku.Tier
"Disk Type" = $_.Sku.Name
"Managed By" = if($_.ManagedBy){$_.ManagedBy.Remove(0,$_.ManagedBy.LastIndexOf('/')+1)}else{"none"}
"Time Created" = $_.TimeCreated
"Disk Size (in GB)" = $_.DiskSizeGB
"I/O per second" = $_.DiskIOPSReadWrite
"MBps per second" = $_.DiskMBpsReadWrite
"Location" = $_.Location
}
}
I write a sample code and test result as blow, you can just make some changes to meet your need: