Import VMware Image to Azure - Credentials? - powershell

I try to create a Virtual Computer in Azure Portal from VMWare Image. I worked with this tutorials:
https://azure.microsoft.com/de-de/documentation/articles/virtual-machines-windows-upload-image/#uploadvm
(german)
https://buildwindows.wordpress.com/2015/12/20/how-to-add-a-nic-to-an-azure-virtual-machine-arm/
(english)
In the german tutorial you´ll find
$vm = Set-AzureRmVMOperatingSystem -VM $vmConfig -Windows -ComputerName $computerName -Credential $cred -ProvisionVMAgent -EnableAutoUpdate
To get $cred i used:
$cred = Get-Credentials
a login windows will appear to enter credentials
What kind of credentials i have to enter here? The credentials of the Image or Azure? In what format i have to enter it? I tried Computername\User and password (e.g. ARES\Administrator and the password.
EDIT 1
with the machine credentials MyMachineName\Administrator i got the following error:
PS C:\WINDOWS\system32> $cred = Get-Credential
Cmdlet Get-Credential an der Befehlspipelineposition 1
Geben Sie Werte für die folgenden Parameter an:
Credential
PS C:\WINDOWS\system32> $vm = Set-AzureRmVMOperatingSystem -VM $vmConfig -Windows -ComputerName $computerName -Credential $cred -ProvisionVMAgent -EnableAutoUpdate
PS C:\WINDOWS\system32> $result = New-AzureRmVM -ResourceGroupName $rgName -Location $location -VM $vm
New-AzureRmVM : Windows admin user name cannot be more than 20 characters long, end with a period(.), or contain the following characters: \ / " [ ] : | < > + = ; , ? * #.
StatusCode: 400
ReasonPhrase: Bad Request
OperationID : ''
In Zeile:1 Zeichen:11
+ $result = New-AzureRmVM -ResourceGroupName $rgName -Location $locatio ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureRmVM], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.NewAzureVMCommand
Edit 2
After the tip to read the example of https://msdn.microsoft.com/en-us/library/mt603843.aspx i got this one. My user is Administrator, but i got the message, ist no allowed?!
PS C:\WINDOWS\system32> $SecurePassword = ConvertTo-SecureString "mypassword" -AsPlainText -Force
PS C:\WINDOWS\system32> $Credential = New-Object System.Management.Automation.PSCredential ("Administrator", $SecurePassword);
PS C:\WINDOWS\system32> $AvailabilitySet = Get-AzureRmAvailabilitySet -ResourceGroupName "KGSCloud"
PS C:\WINDOWS\system32> $vmName = "titan"
PS C:\WINDOWS\system32> $computerName = "TITAN"
PS C:\WINDOWS\system32> $vm = Set-AzureRmVMOperatingSystem -VM $vmConfig -Windows -ComputerName $computerName -Credential $Credential -ProvisionVMAgent -EnableAutoUpdate
PS C:\WINDOWS\system32> $result = New-AzureRmVM -ResourceGroupName $rgName -Location $location -VM $vm
New-AzureRmVM : The Admin Username specified is not allowed.
StatusCode: 400
ReasonPhrase: Bad Request
OperationID : ''
In Zeile:1 Zeichen:11
+ $result = New-AzureRmVM -ResourceGroupName $rgName -Location $locatio ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureRmVM], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.NewAzureVMCommand
Can someone help me?
Kind Regards

For Set-AzureRmVMOperatingSystem you will need to enter the credentials of the virtual machine. So the format would be the local administrator account and password at this stage.

Related

Excute Shell Script remotely to Azure Linux VM

i'am trying to excute a shell script to an azure linux virtual machine using powershell
Why I'm i using powershell? :
The virtual machine has a Copied VHD from storage account which means it doesn't have Azure VM agent
so i can't use :
azure vm extentions
azure vm Runs
i tried also using an automation runbook with the ssh module and got those errors :
Exception calling "Connect" with "0" argument(s): "Server HMAC algorithm not found" At C:\Modules\User\SSH\SSH.psm1:68 char:5 + $SSHConnection.Connect() + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SshConnectionException
and
Exception calling "RunCommand" with "1" argument(s): "Client not connected." At C:\Modules\User\SSH\SSH.psm1:69 char:5 + $ResultObject = $SSHConnection.RunCommand($ScriptBlock.ToString() ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SshConnectionException
which is based on my understanding caused by the vm that is missing KexAlgorithms to describe which methods are supported by the SSH daemon
What i'm trying to do now is to ssh into the vm and excute the command using powershell
here is what i got now (a Powershell scripot to ssh into the vm and excute a command):
$Password = "pwd"
$User = "pwd"
$ComputerName = "ip adress"
$Command = "touch tst.txt"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
echo 'logging...'
$SessionID = New-SSHSession -ComputerName $ComputerName -Credential $Credentials #Connect Over SSH
echo 'Executing...'
$output = (Invoke-SSHCommand -Index $SessionID -Command $Command).Output
Remove-SSHSession -Name $SessionID | Out-Null
im getting this error :
Invoke-SshCommand : A parameter cannot be found that matches parameter name 'Index'.
At C:\Users\octoadmin\Desktop\sign in.ps1:11 char:30
+ $output = (Invoke-SSHCommand -Index $SessionID -Command $Command).Out ...
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-SshCommand], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Invoke-SshCommand
i looked in the internet but couldn't find anything.
apparently the ssh invoke command can't find a session with the index $SessionID
but i don't know where exactly is the problem
hope someone can guide me to the right direction.
Updating Posh-SSH worked for me with this code :
to install Posh-SSH :
Install-Module -Name Posh-SSH -RequiredVersion 2.1
The Script:
$Command = "fetch $scripturl; sh script.sh"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$ComputerName = Get-AzPublicIpAddress -ResourceGroupName $RG -Name $IPName | Select-Object -ExpandProperty ipAddress
echo 'ip is : '
echo $ComputerName
echo 'logging...'
$SessionID = New-SSHSession -ComputerName $ComputerName -AcceptKey -Credential $Credentials
echo 'Exucuting...'
$Query = (Invoke-SshCommand -SSHSession $SessionID -Command $Command).Output
echo $Query
Remove-SSHSession -Name $SessionID | Out-Null

System Center Configuration Manager - PowerShell Remoting

I have a primary SCCM server - "ABC"
Later I installed SCCM console and PowerShell Module on one more machine - "XYZ"
I am running below script from server - "OPQ" and trying to remote "XYZ" (on which i installed SCCM Console Recently)
Script ::
$Session = New-PSSession -ComputerName "XYZ" -Authentication Kerberos -Credential $Cred -ConfigurationName Microsoft.PowerShell32
Invoke-Command -Session $Session -ScriptBlock {
Import-module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
Set-Location PS1:\
}
ERROR ::
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : OpenError: (PS1:PSDriveInfo) [Import-Module], UnauthorizedAccessException
+ FullyQualifiedErrorId : Drive,Microsoft.PowerShell.Commands.ImportModuleCommand
+ PSComputerName : XYZ
Cannot find drive. A drive with the name '' does not exist.
+ CategoryInfo : ObjectNotFound: (PS1:String) [Set-Location], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
+ PSComputerName : XYZ
Well it appears you have a permissions issue. Here is how I executed a remote command in my SCCM environment, via my PSS:
$device = Invoke-Command -Session $sess -ScriptBlock {
Import-Module (Join-Path (Split-Path $env:SMS_ADMIN_UI_PATH)
ConfigurationManager.psd1)
Push-Location -Path ((Get-WmiObject -Namespace "root\SMS" -Class
"SMS_ProviderLocation" | Select-Object -ExpandProperty SiteCode) + ":")
Get-CMDevice -Name $env:COMPUTERNAME
Pop-Location
}
$device
RunspaceId : cbc7e008-d92c-4ba3-94a3-b75f8005be98
SmsProviderObjectPath : SMS_CM_RES_COLL_SMS00001.ResourceID=16777221
AADDeviceID : 00000000-0000-0000-0000-000000000000
AADTenantID : 00000000-0000-0000-0000-000000000000
ActivationLockBypassState :
ActivationLockState :
ADLastLogonTime : 3/31/2020 11:23:38 PM
ADSiteName : XXXX-XX
...
Note that if you're not remoting to your PSS, you will need to specify your PSS in the Get-WmiObject command, e.g.:
(Get-WmiObject -ComputerName [YOUR PSS] -Namespace "root\SMS" -Class "SMS_ProviderLocation" | Select-Object -ExpandProperty SiteCode) + ":"
I was able to resolve this issue by saving the credentials on the XYZ server and then calling them under my INvoke-Command.
Like This :
$Session = New-PSSession -ComputerName "XYZ"
Invoke-Command -Session $Session -ScriptBlock {
$password = Get-Content -Path D:\Creds\creds.txt | ConvertTo-SecureString
$Cred = New-Object System.Management.Automation.PSCredential ("domain\UserId", $password)
Then the rest of the code. ... .. . . .
}

A positional parameter cannot be found that accepts argument-System.Management.Automation.PSCredential'-Error

I have a script which needs to run from remote by passing on credentials in the script as as below:-
$UserName = Read-Host "Enter User Name:"
$Password = Read-Host -AsSecureString "Enter Your Password:"
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserName , $Password
Set-Service -Name HiTrust -StartupType Automatic -ComputerName ServerName -credential $Credential
(Get-Service -Name "HiTrust" -credential $Credential -ComputerName ServerName).Start()
Exit
However I keep on getting error as below:-
Set-Service : A positional parameter cannot be found that accepts argument 'System.Management.Automation.PSCredential'.
At C:\Users\ucub\Desktop\Test.ps1:9 char:15
+ ... Set-Service -Name HiTrust -StartupType Automatic -Compute ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
If you are on this PSVersion and below, here is your root cause of why this fails on Set-Service...
$PSVersionTable.PSVersion
<#
Major Minor Build Revision
----- ----- ----- --------
5 1 17763 503
#>
(Get-Command -Name Set-Service).Parameters.Keys
# Results
ComputerName
Name
DisplayName
Description
StartupType
Status
InputObject
PassThru
Verbose
Debug
ErrorAction
WarningAction
InformationAction
ErrorVariable
WarningVariable
InformationVariable
OutVariable
OutBuffer
PipelineVariable
WhatIf
Confirm
You have unneeded stuff in the script as well.
I suggest refactoriung to this
(Get-Command -Name Invoke-Command).Parameters.Keys
# Results
Session
ComputerName
Credential
...
$ServerName = Read-Host 'Enter a target server name:'
$ServiceName = Read-Host 'Enter a target service name:'
Invoke-Command -ComputerName $ServerName -ScriptBlock {
"Executing service actions on $env:COMPUTERNAME"
Set-Service -Name $ServiceName -StartupType Automatic
Start-Service -Name $ServiceName
} -Credential (Get-Credential -Credential "$env:USERDOMAIN\$env:USERNAME")
The Problem is, that set-service doesn't have a credential parameter. Look here
Try something like this:
Enter-PSSession -ComputerName $computername -Credential $credentials
Set-Service -Name HiTrust -StartupType Automatic
or
Invoke-Command -ComputerName $computername -Credential $credential -ScriptBlock {Set-Service -Name HiTrust -StartupType Automatic}

Setting Windows local admin password remotely using PowerShell & [ADSI]

So close but so far...
I am trying to change a local administrator password on a Windows server using [ADSI] & PowerShell but I cannot find a way to pass a string variable when invoking and get the following error:
Exception calling "Invoke" with "2" argument(s): "Number of parameters specified does not match the expected number."
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodTargetInvocation
+ PSComputerName : vmdeploytest1
This works, with the string in the statement:
$vmName = "vmdeploytest1"
Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke("setpassword","Password123")
}
This doesn't:
$vmName = "vmdeploytest1"
$password = '"Password123"'
$invoke = '"setpassword",'
$invokeStr = $invoke + $password
Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke($invokeStr)
}
This doesn't
$vmName = "vmdeploytest1"
$password = '"Password123"'
Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke("setpassword",$password)
}
This doesn't:
$vmName = "vmdeploytest1"
$password = 'Password123'
Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke("setpassword",$password)
}
All giving the same error. I need to be able to use a variable because I am going to generate a random password.
Jeroen Mostert is Correct
When you pass variables into a ScriptBlock you need to prefix them with $using:
For example:
$vmName = "vmdeploytest1"
$password = 'Password123'
Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke("setpassword",$using:password)
}

How does one convert PSVirtualMachineObjects?

I'm trying to deploy Azure VM's thru a workflow so it could be done in parallel. The code works fine outside of a workflow. But getting this error when trying to do it thru a workflow.
I'm importing the VM parameters thru a csv file.
Are there additional considerations for deploying Azure VM's thru a Workflow?
Workflow Deploy-VMs {
$cred1= New-Object System.Management.Automation.PSCredential "User",$(ConvertTo-SecureString "Password" -asplaintext -force)
$b=Import-Csv Y:\NLG\vms1.csv -Verbose|? type -eq 'VM'
foreach ($c in $b) {
AzureRM.Resources\Login-AzureRmAccount -Credential $cred1 -SubscriptionId subscription id
$nic = New-AzureRmNetworkInterface -Name $c.Name -ResourceGroupName nlg -Location $c.Location -SubnetId $c.SubnetID
$cred= New-Object System.Management.Automation.PSCredential "nladmin",$(ConvertTo-SecureString $c.Password -asplaintext -force)
$vmConfig = New-AzureRmVMConfig -VMName $c.Name -VMSize "Standard_D1"
$vmConfig = Set-AzureRmVMOperatingSystem -VM $vmConfig -Windows -ComputerName $c.Name -Credential $cred
$vmConfig = Set-AzureRmVMSourceImage -VM $vmConfig -PublisherName "MicrosoftWindowsServer" -Offer "WindowsServer" -Skus "2012-R2-Datacenter-smalldisk" -Version "latest"
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $nic.Id
$vmConfig = Set-AzureRmVMOSDisk -VM $vmConfig -Name $c.Name -CreateOption FromImage
New-AzureRmVM -ResourceGroupName $c.RG -Location $c.Location -VM $vmConfig
}
}
and getting this error
Cannot bind parameter 'VM'. Cannot convert value
"Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine" to type
"Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine". Error:
"Cannot convert the
"Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine" value of
type
"Deserialized.Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine"
to type "Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine"."
+ CategoryInfo : InvalidArgument: (:) [Set-AzureRmVMOperatingSystem], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Azure.Commands.Compute.SetAzureVMOperatingSystemCommand
+ PSComputerName : [localhost]
Resolved using inline script for the incompatible cmdlets.
Workflow Deploy-VMs {
$cred1 = New-Object System.Management.Automation.PSCredential "User", $(ConvertTo-SecureString "Password" -AsPlainText -Force)
$b = Import-Csv Y:\NLG\vms1.csv -Verbose|? type -eq 'VM'
foreach -Parallel ($c in $b) {
AzureRM.Resources\Login-AzureRmAccount -Credential $cred1 -SubscriptionId c2d7e81b-ed6a-4de9-a4cd-36e679ec4259
$nic = New-AzureRmNetworkInterface -Name $c.Name -ResourceGroupName nlg -Location $c.Location -SubnetId $c.SubnetID
$cred = New-Object System.Management.Automation.PSCredential "nladmin", $(ConvertTo-SecureString $c.Password -AsPlainText -Force)
InlineScript {
$vmConfig = New-AzureRmVMConfig -VMName $using:c.Name -VMSize "Standard_D1"
$vmConfig = Set-AzureRmVMOperatingSystem -VM $vmConfig -Windows -ComputerName $using:c.Name -Credential $using:cred
$vmConfig = Set-AzureRmVMSourceImage -VM $vmConfig -PublisherName "MicrosoftWindowsServer" -Offer "WindowsServer" -Skus "2012-R2-Datacenter-smalldisk" -Version "latest"
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $using:nic.Id
$vmConfig = Set-AzureRmVMOSDisk -VM $vmConfig -Name $using:c.Name -CreateOption FromImage
New-AzureRmVM -ResourceGroupName $using:c.RG -Location $using:c.Location -VM $vmConfig
}
}
}