File System Mapping on Azure Server - azure

I have a windows Azure server where I want to mount a file mapping. Below code works fine when I try it on my local windows machine. But it says Access Denied when try the same on Azure Windows Server. What am I missing here?
$acctKey = ConvertTo-SecureString -String "<account_key>" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList "Azure\<account_username>", $acctKey
New-PSDrive -Name Z -PSProvider FileSystem -Root "\\server.name\files" -Credential $credential -Persist
P.S. It says here that I do have the access.

Could you please try to mount azure file share with command prompt:
net use Z: \\jasonvmdisks304.file.core.windows.net\jasonshare yjya1gkE0TK0lqx/OUh1kD4fxdhCLDjcOW6XPSF6Y4jyCxxMd45eFEvYRzKp8CMRjRpuz38RISA49qXWw3wKA== /user:Azure\jasonvmdisks304
If it still not work, could you please check the event view to find the log, and post it here.

Not sure if resolved so will chime in. One question, if the client is in a different Azure region (e.g. on premise or elsewhere) then SMB3.0 is required, else, SMB2.1 (if in the same region) is allowed. This is a security feature.

Related

PS Azure automation runbook ; How to Mount Azure File Share?

Trying to mount Azure FS from Powershell runbook in Azure Automation.
Via username and key
$UserName = "localhost\trex4xfs"
$Key = "Zav---mykey-----1Tdw=="
$RemotePath = "\\myshare.file.core.windows.net\mainfs"
$MapDrive = "z:"
Get-Command -Name *SmbMapping* | ft
[securestring]$pass = ConvertTo-SecureString $key -AsPlainText -Force
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserName, $pass
new-psdrive -name T -PsProvider FileSystem -root $RemotePath -credential $credential
Get-PSDrive | ft
echo "--------now import smb"
Import-Module smbshare
echo "--------now smb"
New-SmbMapping -LocalPath $MapDrive -RemotePath $RemotePath -UserName $UserName -Password $Key
Above works great on "plain Powershell on Windows"
Tried
Runbook with 5.1 and 7.1 PS version
new-psdrive (error: This function is not supported on this system )
New-SmbMapping (error 7.1: The 'New-SmbMapping' command was found in the module 'SmbShare', but the module could not be loaded. For more information, run 'Import-Module SmbShare'
New-SmbMapping (error 5.1: Cannot connect to CIM server. The specified service does not exist as an installed service. )
Import-Module smbshare (error Failed to generate proxies for remote module 'smbshare'. Cannot overwrite the item C:\Users\Client\Temp\tmp_5t22mi1k.oh0\remoteIpMoProxy_smbshare_2.0.0.0_localhost_f29e4e95-e8cf-4256-a4db-fc9381c6563c.format.ps1xml with itself.)
New-CimSession (error: The specified service does not exist as an installed service.)
Seem to be related to New-CimSession not available on Azure Automation runbook
other questions related to this:
Azure Runbook - Get a file from Azure File System Storage
Not able to access Azure FileShare Storage container from Azure Automation Runbook
Map a Azure Fileshare to Azure Runbook local drive to use as temporary storage
One of the related question which you have shared already provides the answer (i.e., this one) which basically says to use hybrid runbook worker in your use case scenario.

Add onprem AD group while provisioning Azure VM with ARM template -Azure virtual desktop

I have a requirement of provisioning a Azure VM with ARM template, which consists of creating machine, add domain join, register hostpool, enable Azure disk encryption. we will be using image.
I tried to use Custom exten script at last to run a ps1 which can add the machine object to ad group.
Script1
$SysInfo = New-Object -ComObject "ADSystemInfo"
$ComputerDN = $SysInfo.GetType().InvokeMember("ComputerName",
"GetProperty", $Null, $SysInfo,
$Null)
#$ComputerDN =
([ADSISEARCHER]"sAMAccountName=$($env:COMPUTERNAME)$").FindOne().Path
$ComputerDN
$Group = "groupname"
$group1dn= ([ADSISEARCHER]"sAMAccountName=$($Group)").FindOne().Path
$Groupdn = [ADSI]"$group1dn"
// Check if computer already a member of the group.
If ($Groupdn.IsMember("LDAP://$ComputerDN") -eq $False)
{
# Add the computer to the group.
$Groupdn.Add("LDAP://$ComputerDN")
}
Script2
$credential= "domain/user & password"
Start-Process
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Credential
$credential -ArgumentList "-file <path of script1>"
**OR**
Invoke-Command -FilePath <path of script1>-Credential $credential -
ComputerName localhost
Both ps1 downloaded via CSE to machine and trigger the second script2
For start process it says access denied (because the CSE runs system account and may be unable to change the domain user.)
Invoke command can impersonate, however, it requires the domain/user to be added to localadmin users group and enable psremoting on the machine, inspite of doing this still having issues.
Exception calling "InvokeMember" with "5" argument(s): "Access is denied.
The following exception occurred while retrieving member "IsMember": "An operations error occurred.
"
How to get this done with CSE?
To simplify script1 a bit, you can try using the WinNT names and skip searching AD:
$Group = "Domain Computers"
$Domain = 'CONTOSO' # NETBIOS name
$ADGroup = [ADSI]"WinNT://$Domain/$Group"
# Check if computer already a member of the group. Computer accounts get $ at the end
If (-not ($ADGroup.isMember("WinNT://$Domain/$env:COMPUTERNAME$"))) {
# Add the computer to the group.
$Groupdn.Add("LDAP://$ComputerDN")
}
script2's Start-Process should be fine as long as the VM is already joined to the domain, and the cred username is in DOMAIN\user format. You could try testing the command below for example - no variables, just fill in the names.
It can be a pain to get the output of started processes. I added ;Read-Host 'waiting' to test true/false output in a shell window. If you can't run it interactively, you could use -RedirectStandardOutput 'c:\folder\result.out' and check the file
$Credential = Get-Credential CONTOSO\user
Start-Process powershell.exe -Cred $Credential -Wait -Arg `
"-C ([ADSI]'WinNT://CONTOSO/Domain Computers').isMember('WinNT://CONTOSO/MyHostname$')"
On my PC, this returns an error start-process : Access is denied, but does successfully impersonate my domain user and start the process... so I'm not exactly sure what its deal is.
Invoke-Command works well for anything local to the machine, but it still counts as remoting. isMember() is not able to authenticate to your AD service because of second-hop restrictions. This behavior can be changed, but it's not recommended.
I figured out.. thanks for suggestions Cpt.Whale.
I used only script1 (with expecting parameters of domain password) in CSE- that downloads on the machine after domain join.
then used the protected settings in CSE to run the ps1 and pass the keyvault references.
"commandToExecute": "[concat('powershell.exe -file Scrip1.ps1',' -password(param in the script1) ,parameters('keyvaultpass'))]"
/Naveen

Login-AzureRmAccount from VS Code terminal

When I try to login to Azure RM from VS Code terminal it just hangs. No prompt with login / password is shown.
Is there any way to get logged in from that terminal? Otherwise running / debugging Azure PS scripts becomes more complicated than it should be :)
The login window pops-up in the background... if you minimize all your windows you'll eventually find it.
You need to wait for a moment, then you could see the login page.
According to your description, I suggest you could select Non-interactive login. You could create a service principal that can access resource. Please refer to this link:Use portal to create an Azure Active Directory application and service principal that can access resources. You will get clientid and client secret. You could use the following code to login your Azure account.
$subscriptionId=""
$tenantid=""
$clientid=""
$password=""
$userPassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$userCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $clientid, $userPassword
Login-AzureRmAccount -TenantId $tenantid -ServicePrincipal -SubscriptionId $subscriptionId -Credential $userCredential

New-PSSession in an Azure-runbook: Access denied (ARM)

With the advice provided in this answer I was able to set up the winrm on a Azure VM(1).
Right now, I can open a PS-Session with New-PSSession from
any Azure VM(2) to the Azure VM(1)
my local machine which to the Azure VM(1)
But if I do exactly the same within an Azure runbook,
$cred = Get-AutomationPSCredential -Name "admin"
InlineScript
{
$vmSession = New-PSSession -ConnectionUri 'https://xxx.yyy.cloudapp.azure.com:5986' -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
}
it fails with the error message:
New-PSSession : [xxx.yyy.cloudapp.azure.com] Connecting to remote server
xxx.yyy.cloudapp.azure.com failed with the following error message : Access is denied.
As user I use `localhost\admin" and I'm positiv, the password is correct (double-checked it).
Q How can I overcome the Access denied?
Update
PS-workflow got the best of me. So, there is only a minor syntactical problem in the code above. If somebody shares the right answer I'm happy to up-vote and accept it.
According to this official documents.
By default, the variables that are defined in a workflow are not
visible to the commands in the InlineScript script block. To make
workflow variables visible to the InlineScript, use the $Using scope
modifier. The $Using scope modifier is required only once for each
variable in the InlineScript.
So, you need modify your script as below:
$cred = Get-AutomationPSCredential -Name "admin"
InlineScript
{
$vmSession = New-PSSession -ConnectionUri 'https://xxx.yyy.cloudapp.azure.com:5986' -Credential $Using:cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
}

Setting script to run at user login on Azure VM via ARM

I have generalized a windows Azure image and I am using it in an ARM (Azure resoure manager) template to create a new VM. At the time of VM creation I am doing some bootstrapping work using Custom Script extension that runs a Powershell script. It works fine except for few things that are specific to a user that will log on to machine. For example, I can't map a network drive or set powershell exection policty to remotesigned for the user who will log in to the machine via Custom Script Extension.
Is there a way to accomplish user specific tasks in the ARM template or set some scripts to run when user will log in?
Maybe a bit late, but I am using sth similar to this:
However, we can’t directly hand this script to Custom Script Extension yet. Custom Script Extension uses NTAUTHORITY\SYSTEM account to execute scripts, but the account doesn’t have necessary privileges to execute the SQL configuration commands. To work around this, we’ll create a separate bootstrap script, which impersonates an administrator account before invokes the script.
Here is the code used:
$password = ConvertTo-SecureString "[your admin account user password]" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("$env:COMPUTERNAME\[your admin account]", $password)
$command = $file = $PSScriptRoot + "\CustomScriptSQLPS.ps1"
Enable-PSRemoting –force
Invoke-Command -FilePath $command -Credential $credential -ComputerName $env:COMPUTERNAME
Disable-PSRemoting -Force
I don't know if remoting is relevant for this though ...
Credits to Haishi Bai

Resources