PowerShell :: Microsoft.Azure.Commands.Sql.Database.Model.AzureSqlDatabaseModel.DatabaseName [duplicate] - azure

This question already has answers here:
How can you use an object's property in a double-quoted string?
(5 answers)
Closed 5 months ago.
I wrote a script that allows me to query the whole Azure database park:
#$ErrorActionPreference = 'SilentlyContinue'
# Connect to Azure
$azureAccount = Connect-AzAccount
# Get Azure Access Token (we will use this to query the databasees)
#$azureToken = Get-AzAccessToken -ResourceUrl https://database.windows.net
$access_token = (Get-AzAccessToken -ResourceUrl https://database.windows.net).Token
# Queries will be picked up from here
$folderPath = '.\Queries'
# Choose how to format each date ("yyyy-MM-dd") or ("yyyy-MM-dd HH:mm:ss")
$DateTime = (Get-Date).ToString("yyyy-MM-dd")
# List Azure Sunscriptions
Get-Azsubscription | ForEach-Object -Begin { $a = 1 } -Process {"$a $($_.Name)"; $a++}
$SubscriptionChoice = Read-Host -Prompt "Copy/paste the name of the Subscription that you want to investigate. If more than one separate them by a coma, Type `"All`" if you want to target all of them"
# Iterate into subscriptoins and print names
foreach ($gs in $SubscriptionChoice) {
Select-Azsubscription -Subscription "$gs" | Out-Null
Write-Host "Let's browse into Azure Sunscription: " -NoNewline
Write-Host (Get-AzContext).Subscription.Name -ForegroundColor green
# Fins all Azure SQL Server
Get-AzSqlServer | ForEach-Object -Begin { $a = 1 } -Process {"$a $($_.ServerName)"; $a++}
$SqlServerChoice = Read-Host -Prompt "Copy/paste the name of the SQL Server that you want to investigate. If more than one separate them by a coma, Type `"All`" if you want to target all of them"
if ($SqlServerChoice = "All"){
$SqlServerChoice = Get-AzSqlServer
}
Foreach ($server in $SqlServerChoice){
$DatabaseChoice = Get-AzSqlDatabase -ServerName $server.ServerName -ResourceGroupName $server.ResourceGroupName | Where-Object DatabaseName -NE "master"
Foreach ($database in $DatabaseChoice){
(Get-ChildItem $folderPath | sort-object {if (($i = $_.BaseName -as [int])) {$i} else {$_}} ).Foreach{
Invoke-Sqlcmd -ServerInstance $server.FullyQualifiedDomainName -Database $database.DatabaseName -AccessToken $access_token -InputFile $psitem.FullName | Export-Csv -Path ".\Results\$psitem.csv" -Append -NoTypeInformation
write-host "Executing $psitem on $database.DatabaseName"
}
}
}
}
However each time the query is executed against a database the Write-Hosts returns:
Executing DTU_to_vCore.sql on Microsoft.Azure.Commands.Sql.Database.Model.AzureSqlDatabaseModel.DatabaseName
Here a picture:
This Write-Hosts comes from the line:
write-host "Executing $psitem on $database.DatabaseName"
In which you can find the two variables:
$psitem : which is the name of the file that contains the query
$database.DatabaseName : which should be the database name but instead of printing the database name is printing Microsoft.Azure.Commands.Sql.Database.Model.AzureSqlDatabaseModel.DatabaseName
Why one of the two variable is not interpreted?

You need to encapsulate your variable property in a subexpression operator $().
write-host "Executing $psitem on $($database.DatabaseName)"
This is because only simple variables get expanded in an expandable string.
References
Only simple variable references can be directly embedded in an
expandable string. Variables references using array indexing or member
access must be enclosed in a subexpression.
Source: about_Quoting_Rules
Subexpression operator $( )
Returns the result of one or more statements. For a single result,
returns a scalar. For multiple results, returns an array. Use this
when you want to use an expression within another expression. For
example, to embed the results of command in a string expression.
PS> "Today is $(Get-Date)"
Today is 12/02/2019 13:15:20
PS> "Folder list: $((dir c:\ -dir).Name -join ', ')"
Folder list: Program Files, Program Files (x86), Users, Windows
Source: about_Operators

Related

Powershell question about parsing the tag values in Get-AzVm

I'm attempting to load individual tag key and value records per VM using the Get-AzVm cmdlet. The values are stored like:
"Tags : {"Purpose":"SQL Server","Test":"Value"}"
I want to load them like:
VMID, VMName, Key, Value
No amount of searching or testing with ForEach, ForEach-Object or loading in to a hash is working as the results are always null, but what is loaded in to a variable is not. I would be very grateful for any suggestions.
$vm_list = Get-AzVM -Name #######
foreach ($name in $vm_list)
{
$_ = $vm_list.tags.GetEnumerator() |
ForEach-Object{
$k = $_.key
$v = $_.value
Write-Host $tagkeys.VMID, $tagkeys.Name, $k, $v
}
}
There is more to the script, but this is what I have working now. Using enumerator, I would have expected to need to reference the objects as {0} and {1}.

Using Objects in Powershell to do command

What im trying to do is the following:
Im getting a list of all VM`s that have some set values such as being in use and NOT having Azure Benefits turned on.
What i have is that i made a tiny script to get all machines within an subscription and select on the basis mentioned above.
What i want to do with that output is do the command Update-azureVM in bulk.
Could someone help me with this ? do i need to export the values to an excel and use that sheet to do a bulk update-AzureVM
here is the code that i have setup at the moment:
$returnObj = #()
$VMs=Get-AzVm -status
foreach ($VM in $VMs)
{
$obj = New-Object psobject -Property #{
"VmSize" = $VM.HardwareProfile.VmSize;
"VmName" = $vm.Name;
"PowerState" = $vm.PowerState;
"License_Type" = $vm.LicenseType;
}
$returnObj += $obj | select VmSize, VmName, PowerState, License_Type
}
$returnObj |
Where-Object{$_.PowerState -ne "VM deallocated"} |
Where-Object{$_.License_Type -ne "Windows_Server"} |
Where-Object{$_.License_Type -ne "Windows_Client"} |
Export-Csv C:\temp\freek.csv
Thank you all in advance!

How to check for specific text in a variable

I have a script that I have wrote that reaches out to a remote machine or the local machine and grabs the environment variables and puts them into a file.
the issue is I have Internal and External hosts. Each hostname would end in either INT or EXT. if the command runs on any host that has EXT in the name it will need to be supplied with my PSCredential object. all other hosts wont work if credentials are used.
My issue is how to determine if the hostname has "EXT"in the name or not.
if i put the below into ISE it gives me a true/false and works fine,
But if that variable is being populated from a parameter when the script is called $test end up being what ever the hostname that was entered.
$compuername = "HOSTNAME1ext"
$test = $compuername -like "*ext"
if ($test -eq $true) {Write-Host "yes"} else {Write-Host "no"}
yes
But when it is used like this it does not work
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[string[]]$ComputerName = $env:ComputerName,
[string]$Name
)
$test = $ComputerName -like "*ext"
if ($test -eq $true) {
$UNPASSWORD = Get-Credential -UserName "$ComputerName\ACCOUNT" -message "Enter the Password for the ACCOUNT Account";$EnvObj = #(Get-WMIObject -Class Win32_Environment -ComputerName $ComputerName -Credential $UNPASSWORD -EA Stop)
} else {$EnvObj = #(Get-WMIObject -Class Win32_Environment -ComputerName $ComputerName -EA Stop)}
when this is done $test comes back as the hostname entered rather than True or False.
When you apply the -like operator to a collection of objects, in your example an array of strings, if works as a filter operator - ie. it only returns the items that satisfy the condition.
Either change the parameter type:
[Parameter(Mandatory=$true)]
[string]$ComputerName
or connect to each computer one by one:
foreach($Name in $ComputerName){
if($Name -like '*ext'){
# Ask for Credential
}
}

Failure to compare values when I am reading from CSV file

My PowerShell script is as follows, I have got all the sites in farm saved as CSV file using Export-Csv command.
$farmList = Import-Csv "TestFarm.csv"
$farmList1 = Import-Csv "OtherFarm1.csv"
foreach ($site in $farmList)
{
Write-Host "db - ", $site
foreach ($farmsite in $farmList1)
{
if ($site -eq $farmsite) {
Write-Host "matching site found for ", $farmsite
break
}
Write-Host "farm - ", $farmsite
}
}
My Excel files in CSV looks like
Site
/sites/TestSite
/sites/testsite1234
...
The second Excel file in CSV looks like
Site
/sites/TestSite
/sites/testsite1234
...
When I debug the program, I am getting a value of $site and $farmSite as
#{Site=/sites/TestSite} , but when I compare the values using -eq, the values do not match.
I have also tried using Compare-Object without success.
You need to compare the objects' Site properties instead of the objects themselves.
Change this:
if ($site -eq $farmsite) {
into this:
if ($site.Site -eq $farmsite.Site) {
If the files contain just this one property you could also expand it on import:
$farmList = Import-Csv "TestFarm.csv" | Select-Object -Expand Site
$farmList1 = Import-Csv "OtherFarm1.csv" | Select-Object -Expand Site
The latter would also allow you to simplify your code by using a -contains check:
foreach ($farmsite in $farmList1) {
if ($farmList -contains $farmsite) {
Write-Host "matching site found for $farmsite"
}
}

Fill in column into excel with powershell

I'm trying to create a report which will get two sets of information, Group name and domain. The problem is that the information will be output into one column instead of two for example:
Group Member Domain
thisIsGroupMember,Domain
but I want it to be like this:
Group Member Domain
thisIsGroupMember, Domain
I also try export-csv but the created csv file only show
Length
32
Here's my code:
$appName = $findone.properties.name
$domain = (($findone.properties.adspath -split ',')[3].substring(3)
$inputstring = "$appName,$domain"
out-file -FilePath "C:\Test\Result.csv" -append -inputObject $inputstring
If your code iterates through a list of objects pulled from AD you can use something like this:
# your foreach code
{
...
$appName = $findone.properties.name
$domain = (($findone.properties.adspath -split ',')[3].substring(3)
$output += ,(New-Object -TypeName psobject -Property #{"Group Member"=$appName;"Domain"=$domain})
}
$output | Export-Csv "C:\Test\Result.csv"
$output is an array of objects being created on the fly with $appName and $domain values. It will then nicely export to a csv after all AD objects are processed.

Resources