Unable to run command using Azure scale set extension for Windows - azure

I am using terraform to Launch some Azure Scale set for windows. I have wrote below code for updating the dynamic IP of the VM created by the terraform.
publisher = "Microsoft.Compute"
settings = jsonencode({
commandToExecute = "powershell.exe (((Get-Content -path C:\\Nomad\\agent\\agent.hcl -Raw) -replace '108.98.16.4','${data.azurerm_network_interface.main.private_ip_address}'| Set-Content -Path C:\\Nomad\\agent\\agent.hcl) | sc.exe start Nomad"
})
But its throwing below error :
Error: Code="VMExtensionProvisioningError" Message="VM has reported a
failure when processing extension 'joinNomadNodes'. Error message:
\"Command execution finished, but failed because it returned a
non-zero exit code of: '255'. The command had an error output of:
''Set-Content' is not recognized as an internal or external
command,\r\noperable program or batch file.\r\n'\"\r\n\r\nMore
information on troubleshooting is available at
https://aka.ms/VMExtensionCSEWindowsTroubleshoot "
Now if i am running the command manually its running without any error:
powershell.exe (((Get-Content -path C:\\Nomad\\agent\\agent.hcl -Raw) -replace '108.98.16.4','178.98.16.5'| Set-Content -Path C:\\Nomad\\agent\\agent.hcl) | sc.exe start Nomad"

I have added the escape char "^" just before the "|" .. Now its running fine.
publisher = "Microsoft.Compute"
settings = jsonencode({
commandToExecute = "powershell.exe (((Get-Content -path C:\Nomad\agent\agent.hcl -Raw) -replace '108.98.16.4','${data.azurerm_network_interface.main.private_ip_address}'^| Set-Content -Path C:\Nomad\agent\agent.hcl) ^| sc.exe start Nomad)"
})

Related

Azure Pipeline Extract Task 7zip

Unable to extract zip to destination with default usage of Extract Task its fails with error:
##[error]Unable to locate executable file: 'C:\azagent\A5\_work\_tasks\ExtractFiles_5e1e3830-fbfb-11e5-aab1-090c92bc4988\1.200.0\7zip\7z.exe'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.
Stating its fails to locate default 7zip path. Tried to use custom PATH setting but also fails with the same error.
UPDATE
Issue seem to be caused by permissions of agent. Still haven't been able to execute Release with Admin privileges in service mode. When run in interactive mode as Admin the release executes successfully.
Task fails whenever admin permission is required.
From the error message, 7zip seems not installed on your self-hosted agent. Try to install the 7zip before you use the Extract Task.
Take Bash Task as an example:
brew install p7zip
For Windows, use the below PowerShell script to install:
$dlurl = 'https://7-zip.org/' + (Invoke-WebRequest -UseBasicParsing -Uri 'https://7-zip.org/' | Select-Object -ExpandProperty Links | Where-Object {($_.outerHTML -match 'Download')-and ($_.href -like "a/*") -and ($_.href -like "*-x64.exe")} | Select-Object -First 1 | Select-Object -ExpandProperty href)
# modified to work without IE
# above code from: https://perplexity.nl/windows-powershell/installing-or-updating-7-zip-using-powershell/
$installerPath = Join-Path $env:TEMP (Split-Path $dlurl -Leaf)
Invoke-WebRequest $dlurl -OutFile $installerPath
Start-Process -FilePath $installerPath -Args "/S" -Verb RunAs -Wait
Remove-Item $installerPath

Get-AzureADAuditSignInLogs returning $null in Automation Accounts

I have a simple script to get the last sign in details for each user in Azure. When running the script from Visual Studio, it all runs fine with no errors.
After uploading the script to an Azure Automation Account, I am getting the error "Object reference not set to an instance of an object".
I have checked and the command 'Get-AzureADAuditSigninLogs' is returning $null
$users = Get-AzureADUser -All $true
foreach ( $user in $users ) {
$userLogs = Get-AzureADAuditSigninLogs -Filter "startsWith(userPrincipalName, '$( $user.UserPrincipalName )')" -All $true
}
Any ideas on the issue that could be causing this to occur in the Automation account but not visual studio?
As per this issue,-All $true parameter is not working for cmdlet Get-AzureADAuditSignInLogs as expected.
To resolve it, you can try upgrading to AzureADPreview v2.0.2.89.
Alternatively, you can also try as suggested by psignoret:
Format string with -f or [String]::Format():
Write-Host ("startsWith(userPrincipalName ,'{0}')" -f $user.userPrincipalName)
Write-Host [String]::Format("startsWith(userPrincipalName ,'{0}')", $user.userPrincipalName)

The PowerShell code works when run from the PowerShell command prompt but not when run with double-click or turned into an executable

This code:
$username = 'Username'
$password = 'Password'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process -FilePath powershell -WorkingDirectory "$env:ALLUSERSPROFILE" -Credential $credential -WindowStyle Hidden -ArgumentList "-NoProfile -Command `"Start-Process -FilePath wscript -Verb RunAs -ArgumentList '\`"$((Get-Location).Path -replace "'", "''")\test.vbs\`" \`"/CurrentDirectory:$((Get-Location).Path -replace "'", "''")\`" \`"/AppData:$($env:APPDATA -replace "'", "''")\`"'`""
works when I run it line by line from the PowerShell command prompt.
The problem occurs both when I associate the .ps1 extension to "Windows PowerShell" and then double-click on the script, and when I compile the script in .exe through IronMan Software's "PSScriptPad".
A similar problem is present at the following link:
Powershell script executes correctly when I choose "run with powershell", but not when I "open with" powershell or double-click it
but in my case it doesn't even work with "Run with PowerShell" and perhaps the cause of the problem is the same one that also affects executables.
Another useful link is the following:
https://stackoverflow.com/a/58245206/45375
How can I solve the problem?
Windows 10 Pro 64-bit
Powershell Version: 5.1.19041.1237 (Integrated in Windows 10).
The compiled executable works correctly when it is not in a directory containing the apostrophe characters while in the case of double-clicking on a .ps1 script, the directory containing it cannot even contain spaces.
This is a useful link:
https://social.technet.microsoft.com/Forums/en-US/bf3344de-3af6-48e3-9f43-f595bb41c62d/bug-powershell-starts-w-error-when-opened-by-context-menu-in-folder-w-apostrophe-in-its-name?forum=win10itprogeneral
For the apostrophes path problem in .exe files, I sent a bug report to IronMan Software PSScriptPad, which was then taken care of.
For the problem of paths with apostrophes or consecutive whitespaces when double-clicking or doing "Run with PowerShell" on .ps1 scripts, I have solved by fixing the following registry values:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\.ps1]
#="Microsoft.PowerShellScript.1"
[HKEY_CLASSES_ROOT\Directory\Background\shell\Powershell\command]
#="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoExit -Command \"Set-Location -LiteralPath \\\"%V\\.\\\"\""
[HKEY_CLASSES_ROOT\Directory\Shell\Powershell\command]
#="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoExit -Command \"Set-Location -LiteralPath \\\"%V\\.\\\"\""
[HKEY_CLASSES_ROOT\Drive\shell\Powershell\command]
#="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoExit -Command \"Set-Location -LiteralPath \\\"%V\\.\\\"\""
[HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\DefaultIcon]
#="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\",0"
[HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Open\Command]
#="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -Command \"if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force }; & \\\"%1\\\"\""
[HKEY_CLASSES_ROOT\SystemFileAssociations\.ps1\Shell\0\Command]
#="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -Command \"if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force }; & \\\"%1\\\"\""
[HKEY_CLASSES_ROOT\SystemFileAssociations\.ps1\Shell\Edit\Command]
#="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell_ise.exe\" -File \"%1\""
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell]
"ExecutionPolicy"="RemoteSigned"

Downloading a file from Adls gen1 using powershell is not working

I am trying a download a file from azure data lake store using powershell script. The code is triggered from a runbook in azure cloud. Looks like Export-AdlStoreItem is not working as expected.I dont get any error messages or compilation errors. In fact when this command is executed a zero byte file is generated in the destination.The name of that file is TemporaryFile2020-06-02_14-56-57.datc18371c2-d39c-4588-9af0-93aa3e136b01Segments
what is happening?.Please help!.
$LocalDwldPath = "T:\ICE_PROD_DATA_SOURCING\FILE_DOWNLOAD_PATH\TemporaryFile$($TimeinSec).dat"
$SourcePath = "Dataproviders/Landing/GCW/HPIndirect/Orders/AMS/gcw_hp_indirect_orders_ams_745_20200601_04_34_01.dat"
$PRODAdlsName = "itgdls01"
Export-AdlStoreItem -Account $PRODAdlsName -Path $("/" + $SourcePath.Trim()) -Destination $LocalDwldPath -Force -ErrorAction Stop
if( Test-Path $LocalDwldPath.Trim() )
{
Get-Content -Path $LocalDwldPath.Trim() -ReadCount 1000 |% { $FileCount += $_.Count }
Remove-Item $LocalDwldPath.Trim()
Set-Content -Path $cntCaptureFile -Value $FileCount
$TimeinSec = TimeStamp2
Add-Content -Value "$TimeinSec Log: Identified file for getting count is $($SourcePath.Trim()) and the count is $FileCount" -Path $logfile
}
else
{
$TimeinSec = TimeStamp2
Add-Content -Value "$TimeinSec Error: Identified file for getting count is $($SourcePath.Trim()) and the count capture failed as local file is not found!" -Path $logfile
}
According to my research, if you want to download a file from azure data lake with PowerShell, we can use the PowerShell command Export-AzDataLakeStoreItem.
For example
Export-AzDataLakeStoreItem -Account <> -Path '/test/test.csv' -Destination 'D:\myDirectory\test.csv'
For more details, please refer to the document
The issue was with the local download path/destination
("T:\ICE_PROD_DATA_SOURCING\FILE_DOWNLOAD_PATH\TemporaryFile$($TimeinSec).dat").
The T:\ drive is a virtual drive/network drive connected as Azure Fileshare.
Instead of T:\ , I have pointed the destination location to a local drive ("F:\ICE_PROD_DATA_SOURCING\FILE_DOWNLOAD_PATH\TemporaryFile$($TimeinSec).dat") and it worked fine.
Its surprising that Powershell didn't give any error messages when it was not able to save the file in a network path pointed to azure fileshare.

IIS: how to undeploy/delete/remove a webapp from command line?

Suppose there's a webapp deployed on local IIS server. When I need to remove/undeploy it, I can go to IIS Manager, right-click on the app, and then select "Delete application and content" - et voila. But, I need to do the same from the command line - how? It can be assumed that the name of the application is known.
Maybe this can be done via MSDeploy somehow?
If you just want to remove the application from the Web Site in IIS without physically deleting the files (like msdeploy does) or if you don't have the WebDeploy-extension installed, you can use the following command:
C:\Windows\System32\inetsrv\appcmd.exe delete app "Default Web Site/MyAppName"
This is what did it:
"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy" -verb:delete -dest:apphostconfig="Default Web Site/<webapp_name>"
I know the question says "command line", but you can use PowerShell and the IIS Administration Cmdlets to do this task. I provide all of the functions and explain the process of how to automate this on my blog. Also, you can easily swap out the IIS Administration Cmdlet calls with calls to msdeploy, appcmd, IIsVdir.vbs, etc.
For your specific question, this PowerShell code should do the trick:
$block = {
Import-Module WebAdministration
$website = "YourWebsiteName"
$applicationName = "PathUnderWebsite\ToYourApplication"
$fullPath = Join-Path $website $applicationName
Write-Host "Checking if we need to remove '$fullPath'..."
if (Get-WebApplication -Site "$website" -Name "$applicationName")
{
Write-Host "Removing '$fullPath'..."
Remove-WebApplication -Site "$website" -Name "$applicationName"
}
Write-Host "Deleting the directory '$fullPath'..."
Remove-Item -Path "IIS:\Sites\$fullPath" -Recurse -Force
}
$session = New-PSSession -ComputerName "Your.WebServer.HostName"
Invoke-Command -Session $session -ScriptBlock $block
Remove-PSSession -Session $session
iisweb /delete WebSite [/s Computer [/u [Domain ]User /p Password ]]

Resources