Azure Powershell Script: Parse Error - powershell

Trying to setup a new VM via PowerShell. Works fine when I copy & paste commands step by step to PowerShell ISE but, fails when I try to run them in one rush.
I have removed other parts of the script, it is also failing with only this lines:
$VM_NAME = "VMNAME"
$VM_SIZE = "Small"
$VM_IMAGE = "5112500ae3b842c8b9c604889f8753c3__OpenLogic-CentOS-71-20150605"
$LOCATION = "West Europe"
$STORAGE_ACCOUNT = "disktest"
$CLOUD_SERVICE = "disktest"
$SSH_USER = "azureuser"
$SSH_PASSWORD = "324w##eANC"
$VIRTUAL_NETWORK = "Playground"
$SUBNET = "P"
$BOOTSTRAP_CHEF = $FALSE
$PATH_PUBLIC_CONFIG = "publicconfig.json"
$PATH_PRIVATE_CONFIG = "privateconfig.json"
$DISK_CREATE = $TRUE
$DISK_SIZE = 500
$DISK_COUNT = 2
$DISK_LABEL = "datadisk"
$DISK_LUN = 0
$REMOVE_SSH_ENDPOINT = $FALSE
$HTTP_ENDPOINT = $FALSE
$SHUTDOWN = $FALSE
Select-AzureSubscription -SubscriptionName "SUB" -Current;
if (!(Test-AzureName -Storage $STORAGE_ACCOUNT)) {
New-AzureStorageAccount -StorageAccountName $STORAGE_ACCOUNT -Location $LOCATION
}
if (!(Test-AzureName -Service $CLOUD_SERVICE)) {
New-AzureService -ServiceName $CLOUD_SERVICE -Location $LOCATION
}
Set-AzureSubscription -SubscriptionName "SUB" -CurrentStorageAccountName $STORAGE_ACCOUNT
$existing = Get-AzureVM -ServiceName $CLOUD_SERVICE -Name $VM_NAME
Error message:
In Zeile:36 Zeichen:1
+ $existing = Get-AzureVM -ServiceName $CLOUD_SERVICE -Name $VM_NAME
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Ausführbarer Skriptcode wurde im Signaturblock gefunden.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TokenAfterEndOfValidScriptText
If i first set the variables, remove them from script window, and run again it works like a charm.

Issue is "Solved" - after some hours talking to Microsoft: It is a bug in PowerShell 3.0 in combination with Windows 7!
To solve this, install PowerShell 4.0, Re-Install Azure PowerShell and reboot the workstation.

Related

Error Message when Running Azure Automation Runbook

I'm trying to create an Azure Automation Runbook to write messages to an existing Azure Storage Queue using information from a SQL Query. The below works perfectly in Powershell ISE on my Windows 10 machine, but I'm getting an error when testing it in Azure the Automation.
The script is:
Connect-AzureRmAccount
Get-AzureRmSubscription
Set-AzureRmContext -SubscriptionId <our subscription id>
$resourceGroup = "our resource group"
$storageAccountName = "our storage account name"
$queueName = "our queue name"
$queue = Get-AzureRmStorageQueueQueue -resourceGroup $resourceGroup -storageAccountName $storageAccountName -queueName $queueName
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "our Azure SQL connection string"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $("SELECT SourceId FROM dbo.batches GROUP BY SourceId HAVING SourceId > 101")
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$Table = new-object system.data.datatable
$SqlAdapter.Fill($Table) | out-null
$SqlConnection.Close()
$compArray = #($Table | select -ExpandProperty SourceId)
foreach ($array in $compArray) {
Add-AzureRmStorageQueueMessage -queue $queue -message #{"SourceId"=$array;"RetryCount"=0;}
}
Again, this works perfectly in Powershell on my local machine, but in Azure Automation, I get this error:
Failed
Queue <our queue name> could not be retrieved/created from Storage Account <our storage account> on resource group (Queue <our queue name> could not be retrieved/created from Storage Account <our storage account> on resource group )
Set-AzureRmContext : Run Connect-AzureRmAccount to login.
At line:3 char:1
+ Set-AzureRmContext -SubscriptionId <our subscription id> ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Set-AzureRmContext], PSInvalidOperationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.SetAzureRMContextCommand
Get-AzureRmStorageAccount : No subscription found in the context. Please ensure that the credentials you provided are
authorized to access an Azure subscription, then run Connect-AzureRmAccount to login.
At C:\Modules\User\AzureRmStorageQueue\AzureRmStorageQueueCoreHelper.psm1:86 char:19
+ ... aContext = (Get-AzureRmStorageAccount -ResourceGroupName $resourceGro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureRmStorageAccount], ApplicationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Management.Storage.GetAzureStorageAccountCommand
Get-AzureStorageQueue : Could not get the storage context. Please pass in a storage context or set the current storage
context.
At C:\Modules\User\AzureRmStorageQueue\AzureRmStorageQueueCoreHelper.psm1:88 char:94
+ ... ue]$queue = Get-AzureStorageQueue -Name $queueName -Context $saContex ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureStorageQueue], InvalidOperationException
+ FullyQualifiedErrorId :
InvalidOperationException,Microsoft.WindowsAzure.Commands.Storage.Queue.GetAzureStorageQueueCommand
New-AzureStorageQueue : Could not get the storage context. Please pass in a storage context or set the current storage
context.
At C:\Modules\User\AzureRmStorageQueue\AzureRmStorageQueueCoreHelper.psm1:92 char:95
+ ... ue]$queue = New-AzureStorageQueue -Name $queueName -Context $saContex ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureStorageQueue], InvalidOperationException
+ FullyQualifiedErrorId :
InvalidOperationException,Microsoft.WindowsAzure.Commands.Storage.Queue.NewAzureStorageQueueCommand
Could someone assist me in what I'm missing here? (I have confirmed that the AzureRmStorageQueue module is installed in Azure Automation.)
In the azure runbook, no need to use the interactive login, if you create an automation account, it will create a service principal and add it to your subscription as a contributor role automatically. So you just need to use the service principal to do what you need.
The command should be like as below, you could try it.
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
$resourceGroup = "our resource group"
$storageAccountName = "our storage account name"
$StorageAccountKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroup -AccountName $storageAccountName).Value[1]
$context=New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
$queueName = "our queue name"
$queue = Get-AzureRmStorageQueueQueue -resourceGroup $resourceGroup -storageAccountName $storageAccountName -queueName $queueName -Context $context
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "our Azure SQL connection string"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $("SELECT SourceId FROM dbo.batches GROUP BY SourceId HAVING SourceId > 101")
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$Table = new-object system.data.datatable
$SqlAdapter.Fill($Table) | out-null
$SqlConnection.Close()
$compArray = #($Table | select -ExpandProperty SourceId)
foreach ($array in $compArray) {
Add-AzureRmStorageQueueMessage -queue $queue -message #{"SourceId"=$array;"RetryCount"=0;}
}

Powershell script not authenticating TFS connection

I'm having an issue with powershell connecting to VTFS(cloud base). My script has been working for years. Not sure what happened, other than updates that I ran from Microsoft which I think is the issue. This script just ran in april without issue before the Microsoft updates.
I get the following error trying to connect, which generally makes a popup appear for my credentials to Online Visual Studios.
if ( (Get-PSSnapin -Name Microsoft.TeamFoundation.PowerShell) -eq $null )
{
Add-PSSnapin Microsoft.TeamFoundation.PowerShell
}
# Variables - CHECK EACH TIME
[string] $tfsServerLocationPath = "https://name.visualstudio.com/DefaultCollection"
[string] $ProjectLocationToSearch = "$/Project/blabla/"
[string] $outputFile = "c:\temp\RetrievedFiles.txt"
[string] $dateRange = "D2018-04-18 00:00:00Z~"
[bool] $openOutputFile = $true
$AutoDeployDir = "$/Project/blabla/"
$deployDirectory = "C:\Temp\ReleaseTest\DeployFiles\"
$tfsCollection = New-Object -TypeName Microsoft.TeamFoundation.Client.TfsTeamProjectCollection -ArgumentList $tfsServerLocationPath
$tfsVersionControl = $tfsCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
**AFTER THIS LINE IS WHEN THE ERROR APPEARS.**
[Microsoft.TeamFoundation.Client.TfsTeamProjectCollection] $tfs = get-tfsserver $tfsServerLocationPath
get-tfsserver : Key not valid for use in specified state.
At line:31 char:67
+ [Microsoft.TeamFoundation.Client.TfsTeamProjectCollection] $tfs = get-tfsserver ...
+ ~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-TfsServer], CryptographicException
+ FullyQualifiedErrorId : GetTfsServer,Microsoft.TeamFoundation.PowerTools.PowerShell.GetTf
sServerCommand
Thank You in Advance.
WOW - my lucky day, for all of you that have the same issue as I did. Here is the fix. I had to delete this registry key.
HKEY_CURRENT_USER\Software\Microsoft\VSCommon\12.0\ClientServices\TokenStorage.
I found here at the following Post.
http://blogs.msdn.microsoft.com/dstfs/2014/01/10/

Cannot start Azure VM from PowerShell

I'm trying to start an Azure VM using the following PowerShell script:
$subscriptionId = "00000000-0000-0000-0000-000000000000"
$azureVM = "VS2017"
$resourceGroup = "VS2017ResourceGroup"
Add-AzureRmAccount # here start interactive login
Select-AzureSubscription -SubscriptionId $subscriptionId
Start-AzureRmVM - -ResourceGroupName $resourceGroup -Name $azureVM
When executing the script, I receive the following response:
Start-AzureRmVM : A positional parameter cannot be found that accepts argument '-'.
At C:\Users\ralbano\Desktop\Senza nome7.ps1:11 char:1
+ Start-AzureRmVM - -ResourceGroupName "VS2017ResourceGroup" -Name $azu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-AzureRmVM], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.Azure.Commands.Compute.StartAzureVMCommand
I am using Windows PowerShell ISE to run the script.
Am I doing something wrong?
I checked the subscription id and the resource group name and are correct (of course in the sample above the subscription id is a fake). The VM is in "Stopped (deallocated)" state on Azure.
Start-AzureRmVM - -ResourceGroupName $resourceGroup -Name $azureVM
According to your error message, we should use this command like this:
Start-AzureRmVM -ResourceGroupName $resourceGroup -Name $azureVM

"Pipeline Stopped" error while setting up Azure VM DSC Extension via Powershell

PowerShell version: 5
I've uploaded a DSC ps1 file in a zip to Azure storage using the command:
publish-azurermvmdscconfiguration
With the appropriate parameters and arguments. Then I enter:
Set-AzureRmVmDSCExtension -ResourceGroupName Pollers -VmName <VmName> -ArchiveBlobName Run-DSCPython.zip -ArchiveStorageAccountName <storageAccountName> -Version 2.2 -Verbose
And I get the following (generally opaque) error message in PowerShell:
Set-AzureRmVmDSCExtension : The pipeline has been stopped.
At line:1 char:1
+ Set-AzureRmVmDSCExtension -ResourceGroupName Pollers -VmName Download ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Set-AzureRmVMDscExtension], PipelineStoppedException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.Extension.DSC.SetAzureVMDscExtensionCommand
Set-AzureRmVmDSCExtension : Long running operation failed with status 'Failed'.
At line:1 char:1
+ Set-AzureRmVmDSCExtension -ResourceGroupName Pollers -VmName Download ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidResult: (:) [Set-AzureRmVMDscExtension], CloudException
    + FullyQualifiedErrorId : InvalidResult,Microsoft.Azure.Commands.Compute.Extension.DSC.SetAzureVMDscExtensionCommand
In the Azure Portal though, I dig up a more detailed log, it's very long so I'll post here only the part I believe is connected to the error itself:
[ERROR] An error occurred while executing script or module 'Run-DSCPython':
 The specified module 'Run-DSCPython' was not loaded because no valid module file
was found in any module directory.
Any idea what I need here? What module is it looking for?
While not exactly an answer to your question, I would propose you compile mofs in Azure Automation and register your VM's as nodes to Azure Automation, the process is a bit lengthy to write out here, I'll write a short guide:
# You can compile mof on your own PC and import, or compile in Azure Automation (preferred way)
<#
Import-AzureRmAutomationDscNodeConfiguration -Path "C:\localhost.mof" -ConfigurationName $configurationName `
-ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Force
#>
$AutomationAccountName = "Automation"
$ResourceGroupName = "Azure"
$Location = "West Europe"
$VnetName = "VNet"
$configurationName = "Configuration-1"
$credName = "Name of credential asset in Azure Automation"
$nodeName = "localhost"
$StorageAccountName = "something"
# Import Configuration
$sourcePath = "C:\DSC.ps1"
Import-AzureRmAutomationDscConfiguration -SourcePath $sourcePath `
-ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Published -Force
# Compile mof
$ConfigurationData = #{
AllNodes = #(
#{
NodeName = $nodeName
PSDscAllowPlainTextPassword = $true
RebootNodeIfNeeded = $true
DebugMode = "All"
}
)
}
$Parameters = #{
"storageAccountName" = $storageAccountName
"nodeName" = $nodeName
"credential" = $credName
}
Start-AzureRmAutomationDscCompilationJob -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName `
-ConfigurationName $configurationName -Parameters $Parameters -ConfigurationData $ConfigurationData
# Register VM and apply mof
$VmName = "VM-Name";
Register-AzureRmAutomationDscNode -AutomationAccountName $AutomationAccountName -AzureVMName $VmName `
-ResourceGroupName $ResourceGroupName -NodeConfigurationName "$configurationName.localhost"
Edit: forgot to tell you the reasoning, I've wasted 2-3 weeks trying to make DSC extension to work RELIABLY. I failed miserably, Azure Automation on the other hand was far more reliable, although really tricky at the beginning.

Creating Azure SQL Database Server connection context New-AzureSqlDatabaseServerContext

I am trying to create an Azure SQL Database connection context e.g.
$cred = Get-Credential
$ctx = New-AzureSqlDatabaseServerContext -ServerName “mydatabasename” -credential $cred
or
$pwd = ConvertTo-SecureString "[password1234]" -AsPlainText -Force;
$cred1 = New-Object System.Management.Automation.PSCredential -ArgumentList "databaseadmin", $pwd
New-AzureSqlDatabaseServerContext -ServerName "myservername" -Credential $cred1
And the response is:
New-AzureSqlDatabaseServerContext : Object reference not set to an instance of an object.
At line:2 char:8
+ $ctx = New-AzureSqlDatabaseServerContext -ServerName “myservername” - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureSqlDatabaseServerContext], NullReferenceException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet.NewAzureSqlDatabaseServerContext
I've been through the docs and google searches but to no avail.
https://msdn.microsoft.com/en-us/library/dn546736.aspx
http://sqlmag.com/powershell/manage-azure-sql-databases-powershell
Thanks
Pavel
I recently ran into this issue in a PS runbook. After doing some searching, I found a solution that worked for me. Hopefully it will help you.
The error message isn't particularly helpful (big surprise), but the null object being referenced is the Azure subscription; I'm assuming the exception bubbles up from within the cmdlet rather than being thrown by your own code. By adding these three lines to my code:
$cert = Get-AutomationCertificate -Name $automationCertificateName;
Set-AzureSubscription -SubscriptionName $subName -Certificate $cert -SubscriptionId $subID;
Select-AzureSubscription -Current $subName;
I was able to get past the exception. Above, $automationCertificateName is a variable asset that I added to the automation account. See https://github.com/Microsoft/sql-server-samples/tree/master/samples/manage/azure-automation-automated-export for details about how to set that up.
Here is how I successfully created connection context:
$sqlServerUser = "test-user"
$sqlServerUserPassword = "P#$$w0rd"
$sqlServerName = "mysqlserver"
$sqlCred = New-Object System.Management.Automation.PSCredential($sqlServerUser, ($sqlServerUserPassword | ConvertTo-SecureString -asPlainText -Force))
$sqlContext = New-AzureSqlDatabaseServerContext -ServerName $sqlServerName -Credential $sqlCred
Please see this for more details.