i'm trying to create with powershell and and command new-AzResources some object, like probe, rules etc.. inside an application gateway. I'm using following snippet:
### Get properties
$get = Get-AzResource -ResourceType Microsoft.Network/applicationGateways -Name appgw -ResourceGroupName rgappgw
$user.Properties.probes.Properties
$properties = #{
protocol = 'Http';
path = '/';
interval = '30';
timeout = '30';
unhealthyThreshold = '3';
pickHostNameFromBackendHttpSettings = $true;
minServers = '0';
match = '200-399';
}
$SlotParams = #{
ResourceName = "appGwName"
Location = "West Europe"
ResourceGroupName = "AppGwRg"
ResourceType = "Microsoft.Network/applicationGateways/probes/probename" ####name of probes
PropertyObject = $properties
}
$execution = New-AzResource #SlotParams -Force
but i'm getting following error:
New-AzResource:
Line |
23 | $getSlotApse = New-AzResource #SlotParams -Force
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| {
"Message": "No HTTP resource was found that matches the request URI 'https://westeurope.network.azure.com:30058/123-124-14-4444-4444444/444444444444/subscriptions/mysubs/resourceGroups/AppGwRg/providers/Microsoft.Network/applicationGateways/appGwName/probes/probename?api-version=2022-07-01'."
}
CorrelationId: 12939812312831983
i use same logic to create app service but i'm not understand what i'm doing wrong with application gateway. Can you please give me an advice?
Thanks
I have reproduced in my environment and taken below commands from the Microsoft-Document:
The command or script which you provided are giving errors for me so, I have used below script for creating application gateway.
Firstly, I have created Subnet then Vnet and all the other required resources using below commands:
Update-Module Az.Network
Connect-AzAccount
$subnet = New-AzVirtualNetworkSubnetConfig -Name subnet01 -AddressPrefix 10.0.0.0/24 -WarningAction Ignore
$vnet = New-AzVirtualNetwork -Name appgwvnet -ResourceGroupName "rithwik-resources" -Location 'East US' -AddressPrefix 10.0.0.0/16 -Subnet $subnet
$subnet = $vnet.Subnets[0]
$publicip = New-AzPublicIpAddress -ResourceGroupName "rithwik-resources" -Name publicIP01 -Location 'East US' -AllocationMethod Dynamic
$gipconfig = New-AzApplicationGatewayIPConfiguration -Name rithwikgatewayIP -Subnet $subnet -WarningAction Ignore
$pool = New-AzApplicationGatewayBackendAddressPool -Name pool01 -BackendIPAddresses 134.170.185.46, 134.170.188.221, 134.170.185.50 -WarningAction Ignore
$probe = New-AzApplicationGatewayProbeConfig -Name probe01 -Protocol Http -HostName 'test.com' -Path '/path/path.htm' -Interval 30 -Timeout 120 -UnhealthyThreshold 8 -WarningAction Ignore
$poolSetting = New-AzApplicationGatewayBackendHttpSettings -Name rithwikapps -Port 80 -Protocol Http -CookieBasedAffinity Disabled -Probe $probe -RequestTimeout 80 -WarningAction Ignore
$fp = New-AzApplicationGatewayFrontendPort -Name frontendport01 -Port 80 -WarningAction Ignore
$fipconfig = New-AzApplicationGatewayFrontendIPConfig -Name fipconfig01 -PublicIPAddress $publicip -WarningAction Ignore
$listener = New-AzApplicationGatewayHttpListener -Name listener01 -Protocol Http -FrontendIPConfiguration $fipconfig -FrontendPort $fp -WarningAction Ignore
$rule = New-AzApplicationGatewayRequestRoutingRule -Name rule01 -RuleType Basic -BackendHttpSettings $poolSetting -HttpListener $listener -BackendAddressPool $pool -WarningAction Ignore
$sku = New-AzApplicationGatewaySku -Name Standard_Small -Tier Standard -Capacity 2 -WarningAction Ignore
$appgw = New-AzApplicationGateway -Name appgwtest -ResourceGroupName "rithwik-resources" -Location 'East US' -BackendAddressPools $pool -Probes $probe -BackendHttpSettingsCollection $poolSetting -FrontendIpConfigurations $fipconfig -GatewayIpConfigurations $gipconfig -FrontendPorts $fp -HttpListeners $listener -RequestRoutingRules $rule -Sku $sku -WarningAction Ignore
Output:
Once ran the above commands in powershell then the resources are created in Portal
Related
Getting an error on my Terraform deployment for the following. I think it's because it's using a mixture of Terraform variables and Powershell I may have confused myself on the syntax.
Here is the Code:
data "template_file" "ad-join-template" {
template = <<EOF
<powershell>
# Set-DefaultAWSRegion -Region eu-west-2
# Set-Variable -name instance_id -value (Invoke-Restmethod -uri http://169.254.169.254/latest/meta-data/instance-id)
# # New-SSMAssociation -target key=InstanceIds,Values=$instance_id -Name "${aws_ssm_document.ad-join-domain.name}"
# New-SSMAssociation `
# -Name ad-join-domain `
# -Target #{
# "Key"="InstanceIds"
# "Values"="$($instance_id)"
# }
$apiurl = "${var.API}"
$tajdns = #("${taj_dns_server[0]}","[${taj_dns_server[1]}")
$count = 0
foreach ($dns in $tajdns){
$returnedRecords = (Resolve-DnsName -Name $apiurl -Server $dns).IPAddress
New-Variable -Name "dnsRecords$count" -Value $returnedRecords -Force
$count++
}
$allDNSrecords += $dnsRecords0
$allDNSrecords += $dnsRecords1
$allDNSrecords = $allDNSrecords | Select-Object -Unique
Add-Content C:\windows\system32\drivers\etc\hosts "`n***.**.*.* ssm.eu-west-2.amazonaws.com `
`n***.**.*.* ssm.eu-west-2.amazonaws.com `
`n***.**.*.* ssm.eu-west-2.amazonaws.com `
`n***.**.*.* ssmmessages.eu-west-2.amazonaws.com `
`n***.**.*.* ssmmessages.eu-west-2.amazonaws.com `
`n***.**.*.* ssmmessages.eu-west-2.amazonaws.com `
`n$allDNSrecords[0] ${var.API}`
`n$allDNSrecords[1] ${var.API}"
$nicDetails = Get-NetAdapter
Set-DnsClientServerAddress -InterfaceIndex $nicDetails.ifIndex -ServerAddresses (${local.concat_dns_servers_join})
$domain = "${aws_directory_service_directory.ad.name}"
$password = "${aws_directory_service_directory.ad.password}" | ConvertTo-SecureString -asPlainText -Force
$username = "admin#$($domain)"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
Add-Computer -DomainName $domain -Credential $credential
Restart-Computer -Force
</powershell>
EOF
}
In the [${taj_dns_server[0]}]" this is pulling a Terraform variable out of list and populating it in to the script. Can you see if my syntax is correct?
Here is the Error:
│ Error: Invalid reference
136│
137│ on asg.tf line 19, in data "template_file" "ad-join-template":
138│ 19: $tajdns = #("[${taj_dns_server[0]}]","[${taj_dns_server[1]}]")
139│
140│ A reference to a resource type must be followed by at least one attribute
141│ access, specifying the resource name.
142╵
143╷
144│ Error: Invalid reference
145│
146│ on asg.tf line 19, in data "template_file" "ad-join-template":
147│ 19: $tajdns = #("[${taj_dns_server[0]}]","[${taj_dns_server[1]}]")
148│
149│ A reference to a resource type must be followed by at least one attribute
150│ access, specifying the resource name.
151╵
I am trying to use PowerShell to set up an Event Hub with Capture set. However, I am experiencing problems when trying specify the capture settings with Set-AzEventHub. I have the following script commands:
$ehResourceGroup = 'kv-audit-resource'
$location = 'eastus'
$ehNameSpace = 'kv-audit-eh'
$ehName = 'security-logs'
$partitions = 1
$week = 7
# Creat resource group for hub
New-AzResourceGroup -Name $ehResourceGroup -Location $location
# Create namespace for hub
New-AzEventHubNamespace -ResourceGroupName $ehResourceGroup -NamespaceName $ehNameSpace -Location $location
# Make the hub
New-AzEventHub -ResourceGroupName $ehResourceGroup -NamespaceName $ehNameSpace -Name $ehName -PartitionCount $partitions -MessageRetentionInDays $week
# Get hub info
$loggingEventHub = Get-AzEventHub -ResourceGroupName $ehResourceGroup -NamespaceName $ehNameSpace -Name $ehName
# Add capture info
$loggingEventHub.CaptureDescription = New-Object -TypeName Microsoft.Azure.Commands.EventHub.Models.PSCaptureDescriptionAttributes
$loggingEventHub.CaptureDescription.Enabled = $true
$loggingEventHub.CaptureDescription.IntervalInSeconds = 60
$loggingEventHub.CaptureDescription.Encoding = "Avro"
$loggingEventHub.CaptureDescription.SizeLimitInBytes = 10485763
$loggingEventHub.CaptureDescription.Destination.Name = "EventHubArchive.AzureBlockBlob"
$loggingEventHub.CaptureDescription.Destination.BlobContainer = "cyberstorageaccount2"
$loggingEventHub.CaptureDescription.Destination.ArchiveNameFormat = "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}"
$loggingEventHub.CaptureDescription.Destination.StorageAccountResourceId = "/subscriptions/{SubscriptionId}/resourceGroups/$ehResourceGroup/providers/Microsoft.ClassicStorage/cyberstorageaccount2"
# Now update the hub with capture info
Set-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehNameSpace -Name $ehName -InputObject $loggingEventHub
I execute the first three commands to create the Event Hub without problems. The storage account, cyberstorageaccount2, already exists. I wait until the Azure dashboard shows that the Event Hub is successfully made and active, which takes several minutes. When I execute the last two commands to modify the capture settings, I get:
PS C:\> $loggingEventHub = Get-AzEventHub -ResourceGroupName $ehResourceGroup -NamespaceName $ehNameSpace -Name $ehName
>> $loggingEventHub.CaptureDescription = New-Object -TypeName Microsoft.Azure.Commands.EventHub.Models.PSCaptureDescriptionAttributes
>> $loggingEventHub.CaptureDescription.Enabled = $true
>> $loggingEventHub.CaptureDescription.IntervalInSeconds = 60
>> $loggingEventHub.CaptureDescription.Encoding = "Avro"
>> $loggingEventHub.CaptureDescription.SizeLimitInBytes = 10485763
>> $loggingEventHub.CaptureDescription.Destination.Name = "EventHubArchive.AzureBlockBlob"
>> $loggingEventHub.CaptureDescription.Destination.BlobContainer = "cyberstorageaccount2"
>> $loggingEventHub.CaptureDescription.Destination.ArchiveNameFormat = "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}"
>> $loggingEventHub.CaptureDescription.Destination.StorageAccountResourceId = "/subscriptions/{SubscriptionId}/resourceGroups/$ehResourceGroup/providers/Microsoft.ClassicStorage/cyberstorageaccount2"
>> Set-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehNameSpace -Name $ehName -InputObject $loggingEventHub
Set-AzEventHub : Operation returned an invalid status code 'BadRequest'
At line:11 char:1
+ Set-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehName ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (Microsoft.Azure...ExecuteCmdlet():ErrorResponseException) [Set-AzEventHub],
ErrorResponseException
+ FullyQualifiedErrorId : SubCode=40000. StorageAccountResourceId. TrackingId:ea7e4590-486a-4597-9351-b5e8508857b8
_M6CH3_M6CH3_G28, SystemTracker:kv-audit-eh.servicebus.windows.net:security-logs, Timestamp:2020-12-08T12:37:56 Co
rrelationId: 4b1edeed-6585-47f0-b14e-476614404a23,Microsoft.Azure.Commands.EventHub.Commands.EventHub.SetAzureEven
tHub
What am I doing wrong? It looks like it's griping about the storage account, but when I display the contents of $loggingEventHub.CaptureDescription.Destination.StorageAccountResourceId, the path appears correct.
Thanks in advance for any info.
Storage resource-id seems malformed. It is missing 'storageaccounts' segment.
"/subscriptions/{SubscriptionId}/resourceGroups/$ehResourceGroup/providers/Microsoft.ClassicStorage/storageAccounts/cyberstorageaccount2"
I got this to work. My code was based on an example provided by Microsoft, but their example assumed you had set up a lot of things previously. What follows is my PowerShell code that fills in some of the gaps in their example. The code is commented (slightly) and has debug output that you can delete. It assumes that you have already made an Event Hub with the prerequisite resource group and namespace.
$ehResourceGroup = 'kv-audit-resource'
$location = 'eastus'
$ehNameSpace = 'kv-audit-eh'
$ehName = 'security-logs'
$partitions = 1
$week = 7
$kvStorageAccount = 'cybersecurityaccount2'
$kvContainer = 'security-container'
# Create the storage account for the Event Hub
Write-Output("Create storage account $kvStorageAccount")
$storageAcct = New-AzStorageAccount -ResourceGroupName $ehResourceGroup -AccountName $kvStorageAccount -Location $location -SkuName Standard_GRS -Kind BlobStorage -AccessTier Cool
# Get the "context" required for the container
$accountContext = $storageAcct.Context
# Create a container for the storage account
Write-Output("Create storage account container $kvContainer")
New-AzStorageContainer -Name $kvContainer -Context $accountContext -Permission 'Container'
# Get the storage account ID for the Event Hub
Write-Output("Get ID of storage account $kvStorageAccount")
$kvStorageAccountId = (Get-AzStorageAccount -ResourceGroupName $ehResourceGroup -Name $kvStorageAccount).Id
# Get Event Hub object
Write-Output("Get Event Hub object")
$loggingEventHub = Get-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehNameSpace -Name $ehName
# Update Event Hub capture description
Write-Output("Update Event Hub object")
$loggingEventHub.CaptureDescription = New-Object -TypeName Microsoft.Azure.Commands.EventHub.Models.PSCaptureDescriptionAttributes
$loggingEventHub.CaptureDescription.Enabled = $true
$loggingEventHub.CaptureDescription.IntervalInSeconds = 60
$loggingEventHub.CaptureDescription.Encoding = "Avro"
$loggingEventHub.CaptureDescription.SizeLimitInBytes = 10485763
$loggingEventHub.CaptureDescription.Destination.Name = "EventHubArchive.AzureBlockBlob"
$loggingEventHub.CaptureDescription.Destination.BlobContainer = $kvContainer
$loggingEventHub.CaptureDescription.Destination.ArchiveNameFormat = "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}"
$loggingEventHub.CaptureDescription.Destination.StorageAccountResourceId = $kvStorageAccountId
Set-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehNameSpace -Name $ehName -InputObject $loggingEventHub
Write-Output($loggingEventHub)
I am trying to create an auto shutdown policy with Powershell for my Azure VM, but keep running into this error:
New-AzureRmResource : MissingRequiredProperty : Missing required property TargetResourceId.
At C:\Users\home\Documents\CreateAzureVM.ps1:167 char:1
+ New-AzureRmResource -Location $Loc -ResourceId $ScheduledShutdownReso ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureRmResource], ErrorResponseMessageException
+ FullyQualifiedErrorId : MissingRequiredProperty,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceCmdlet
I am at a lost on how to fix this error, this is my script piece so far:
$SubscriptionId = $AzContext.Context.Subscription.Id;
$VMResourceId = (Get-AzureRmVM).id
$ScheduledShutdownResourceId = "/subscriptions/$SubscriptionId/resourceGroups/$RSGName/providers/microsoft.devtestlab/schedules/shutdown-computevm-$VMName"
$Properties = #{}
$Properties.Add('status', 'Enabled')
$Properties.Add('taskType', 'ComputeVmShutdownTask')
$Properties.Add('dailyRecurrence', #{'time'= 1159})
$Properties.Add('timeZoneId', "Eastern Standard Time")
$Properties.Add('notificationSettings', #{status='Disabled'; timeInMinutes=15})
$Properties.Add('targetResourceId', $VMResourceId)
#Error
New-AzureRmResource -Location $Loc -ResourceId $ScheduledShutdownResourceId -Properties $Properties -Force
The cause:
This script $VMResourceId = (Get-AzureRmVM).id is not for a specific VM. You should get a specific VM.
Try to use following Powershell scripts:
$SubscriptionId = $AzContext.Context.Subscription.Id
$VM = Get-AzureRmVM -ResourceGroupName $RGName -Name VMName
$VMResourceId = $VM.Id
$ScheduledShutdownResourceId = "/subscriptions/$SubscriptionId/resourceGroups/wayneVMRG/providers/microsoft.devtestlab/schedules/shutdown-computevm-$VMName"
$Properties = #{}
$Properties.Add('status', 'Enabled')
$Properties.Add('taskType', 'ComputeVmShutdownTask')
$Properties.Add('dailyRecurrence', #{'time'= 1159})
$Properties.Add('timeZoneId', "Eastern Standard Time")
$Properties.Add('notificationSettings', #{status='Disabled'; timeInMinutes=15})
$Properties.Add('targetResourceId', $VMResourceId)
#Error
New-AzureRmResource -Location eastus -ResourceId $ScheduledShutdownResourceId -Properties $Properties -Force
Here is the result:
here a loop to read the current configured value for Auto-shutdown of AZ vms (can easy add update/change/set based on Wayne Yang example above)
Example will loop thru many subscription.
:
###################
##:List all subs which are enabled
#$AllSubID = (Get-AzureRmSubscription | Where {$_.State -eq "enabled"}).SubscriptionId
### above might not work depends on account, just get all below.
$AllSubID = (Get-AzureRmSubscription).SubscriptionId
Write-Output "$(Get-Date -format s) :: List of Subscription below"
$AllSubID
$AllVMList = #()
Foreach ($SubID in $AllSubID) {
Select-AzureRmSubscription -Subscriptionid "$SubID"
##list all VMs
$VMs = Get-AzureRmVM
Foreach ($VM in $VMs) {
$VM = New-Object psobject -Property #{`
"Subscriptionid" = $SubID;
"ResourceGroupName" = $VM.ResourceGroupName;
"VMName" = $VM.Name}
$AllVMList += $VM | select Subscriptionid,ResourceGroupName,VMName
}
}
$AllVMList
## Get AutoShutdown info
Foreach ($VM in $AllVMList) {
Write-Output "$(Get-Date -format s) :: VM: $($VM.VMName) :: $($VM.ResourceGroupName) :: $($VM.Subscriptionid)"
$ScheduledShutdownResourceId = "/subscriptions/$($VM.Subscriptionid)/resourceGroups/$($VM.ResourceGroupName)/providers/microsoft.devtestlab/schedules/shutdown-computevm-$($VM.VMName)"
## Write-Output "$ScheduledShutdownResourceId"
$VMShutdownInfo = get-AzureRmResource -ResourceId $ScheduledShutdownResourceId
Write-Output "$(Get-Date -format s) :: VM: $($VM.VMName) :: status: $($VMShutdownInfo.properties.status) ; taskType: $($VMShutdownInfo.properties.taskType) ; timeZoneId: $($VMShutdownInfo.properties.timeZoneId) ; dailyRecurrence: $($VMShutdownInfo.properties.dailyRecurrence) ; "
}
###Done
I have hunted around for an answer to this, but I am not having much luck. All the articles I can find are either setting up a Point-to-Site or are instructions for classic Azure, not Azure 2.0 (Resource Group)
Currently, we are dialing up a whole new resource group everytime we do a new built. This consists of Web apps and SQL DBs. When we have a new build we start up the new and del the old resource group. Simple. To minimize the start-up time we have a static resource group that isn't deleted that houses the VPN connection to our on Prem resources.
The problem I'm having is when I add the new websites using AzureRM Powershell cmd's to the Point-to-site it says it's successful. The Azure Portal says its good but it does let me communicate. If I remove and add it from one of the 8 WebApps they all start working.
I am out of ideas. Any help would be greatly appreciated.
Azure VPN
Below is the function I have put togeather from what I can find out there.
function AddExistingVnet{
param(
[string] $subscriptionId,
[string] $resourceGroupName,
[string] $webAppName
)
$Vnet = Get-AzureRmVirtualNetwork | Where-Object {$_.ResourceGroupName -like "*Static*"}
IF($Vnet.Name.count -gt 1) {write-host 'Two or networks have been returned. Unable to continue ' return}
$gatewaySubnet = $vnet.Subnets | Where-Object { $_.Name -eq "GatewaySubnet" }
$vnetName = $vnet.Name
$uriParts = $gatewaySubnet.IpConfigurations[0].Id.Split('/')
$gatewayResourceGroup = $uriParts[4]
$gatewayName = $uriParts[8]
$gateway = Get-AzureRmVirtualNetworkGateway -ResourceGroupName $vnet.ResourceGroupName -Name $gatewayName
Write-Host "Creating App association to VNET"
$propertiesObject = #{
"vnetResourceId" = "/subscriptions/$($subscriptionId)/resourceGroups/$($vnet.ResourceGroupName)/providers/Microsoft.Network/virtualNetworks/$($vnetName)"
}
$virtualNetwork = New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnet.Name)" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName -Force
# Now finish joining by getting the VPN package and giving it to the App
Write-Host "Retrieving VPN Package and supplying to App"
$packageUri = Get-AzureRmVpnClientPackage -ResourceGroupName $vnet.ResourceGroupName -VirtualNetworkGatewayName $gateway.Name -ProcessorArchitecture Amd64
# Put the VPN client configuration package onto the App
$PropertiesObject = #{
"vnetName" = $vnet.Name; "vpnPackageUri" = $packageUri
}
New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnet.Name)/primary" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections/gateways" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName -WarningAction silentlyContinue -Force
}
So after 2 weeks of going back and forth with Microsoft (had a really good guy Charles) we managed to find the problem.
When requesting
$packageUri = Get-AzureRmVpnClientPackage -ResourceGroupName $vnet.ResourceGroupName -VirtualNetworkGatewayName $gateway.Name -ProcessorArchitecture Amd64
It was giving me an output of:
"https://mdsbrketwprodsn1prod.blob.core.windows.net/cmakexe/xxx~xxx/amd64/xxxx~xxxx&sp=r&fileExtension=.exe"
For some reason (that Microsoft could explain) why it kept adding in " to the beginning and end of the variable.
I find it odd that it lets the script work with " and allows the WebApps to join to the VPN.
Any why here is the fix which basicly removes the " from the begining and end of $packageUri :
$packageUri = $packageUri.ToString();
$packageUri = $packageUri.Substring(1, $packageUri.Length-2);
So hope that helps someone else out there who is banging there head agaist the same problem.
Here is the complete function if any one is intrested:
function AddExistingVnet{
param(
[string] $subscriptionId,
[string] $resourceGroupName,
[string] $webAppName
)
$Vnet = Get-AzureRmVirtualNetwork | Where-Object {$_.ResourceGroupName -like "*Static*"}
IF($Vnet.Name.count -gt 1) {write-host 'Two or networks have been returned. Unable to continue ' return}
$gatewaySubnet = $vnet.Subnets | Where-Object { $_.Name -eq "GatewaySubnet" }
$vnetName = $vnet.Name
$uriParts = $gatewaySubnet.IpConfigurations[0].Id.Split('/')
$gatewayResourceGroup = $uriParts[4]
$gatewayName = $uriParts[8]
$gateway = Get-AzureRmVirtualNetworkGateway -ResourceGroupName $vnet.ResourceGroupName -Name $gatewayName
$webApp = Get-AzureRmResource -ResourceName $webAppName -ResourceType "Microsoft.Web/sites" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName
$location = $webApp.Location
Write-Host "Creating App association to VNET"
$propertiesObject = #{
"vnetResourceId" = "/subscriptions/$($subscriptionId)/resourceGroups/$($vnet.ResourceGroupName)/providers/Microsoft.Network/virtualNetworks/$($vnetName)"
}
$virtualNetwork = New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnet.Name)" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName -Force
# Now finish joining by getting the VPN package and giving it to the App
Write-Host "Retrieving VPN Package and supplying to App"
$packageUri = Get-AzureRmVpnClientPackage -ResourceGroupName $vnet.ResourceGroupName -VirtualNetworkGatewayName $gateway.Name -ProcessorArchitecture Amd64
$packageUri = $packageUri.ToString();
$packageUri = $packageUri.Substring(1, $packageUri.Length-2);
# Put the VPN client configuration package onto the App
$PropertiesObject = #{
"vnetName" = $vnet.Name; "vpnPackageUri" = $packageUri.ToString()
}
$date = Get-Date -format "HH:mm tt"
New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnet.Name)/primary" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections/gateways" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName -WarningAction silentlyContinue -Force
}
Enjoy
powershell script
Set-ExecutionPolicy Unrestricted
## NEEDED FOR IIS CMDLETS
Import-Module WebAdministration
## CREATE FTP SITE AND SET C:\inetpub\ftproot AS HOME DIRECTORY
New-WebFtpSite -Name "test" -Port "21" -Force
cmd /c \Windows\System32\inetsrv\appcmd set SITE "test" "-virtualDirectoryDefaults.physicalPath:C:\inetpub\ftproot"
## SET PERMISSIONS
## Allow SSL connections
Set-ItemProperty "IIS:\Sites\test" -Name ftpServer.security.ssl.controlChannelPolicy -Value 0
Set-ItemProperty "IIS:\Sites\test" -Name ftpServer.security.ssl.dataChannelPolicy -Value 0
## Enable Basic Authentication
Set-ItemProperty "IIS:\Sites\test" -Name ftpServer.security.authentication.basicAuthentication.enabled -Value $true
## Set USer Isolation
Set-ItemProperty "IIS:\Sites\test" -Name ftpserver.userisolation.mode -Value 3
#Set-ItemProperty "IIS:\Sites\test" -Name ftpServer.security.userIsolation. -Value $true
## Give Authorization to Administrators and grant "read"/"write" privileges
Add-WebConfiguration "/system.ftpServer/security/authorization" -value #{accessType="Allow";roles="";permissions="Read,Write";users="*"} -PSPath IIS:\ -location "test"
## Give Authorization to All Users
#appcmd set config %ftpsite% /section:system.ftpserver/security/authorization /+[accessType='Allow',permissions='Read,Write',roles='',users='*'] /commit:apphost
## Restart the FTP site for all changes to take effect
Restart-WebItem "IIS:\Sites\test"
that I want to run it with lua
I make that script
function Create_iis()
tl1="Set-ExecutionPolicy Unrestricted"
tl2="Import-Module WebAdministration"
tl3="New-WebFtpSite -Name \"test\" -Port \"21\" -Force"
tl4="cmd \/c \\Windows\\System32\\inetsrv\\appcmd set SITE \"test\" \"-virtualDirectoryDefaults.physicalPath:C:\\inetpub\\ftproot\""
tl5="Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpServer.security.ssl.controlChannelPolicy -Value 0"
tl6="Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpServer.security.ssl.dataChannelPolicy -Value 0"
tl7="Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpServer.security.authentication.basicAuthentication.enabled -Value $true"
tl8="Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpserver.userisolation.mode -Value 3"
tl9="Add-WebConfiguration \"\/system.ftpServer\/security\/authorization\" -value \#\{accessType=\"Allow\";roles=\"\";permissions=\"Read\,Write\";users=\"*\"} -PSPath IIS:\ -location \"test\""
tl10="Restart-WebItem \"IIS:\\Sites\\test\""
file = io.open("c:\\testiis.ps1","w");
file:write(tl1.."\n"..tl2.."\n"..tl3.."\n"..tl4.."\n"..tl5.."\n"..tl6.."\n"..tl7.."\n"..tl8.."\n"..tl9.."\n"..tl10.."\n"..);
file:close("c:\\testiis.ps1");
result = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe", "open", "c:\\testiis.ps1", "", SW_HIDE,true);
if result ~=0 then
Dialog.Message("Error", "Error ", MB_OK, MB_ICONSTOP, MB_DEFBUTTON1);
end
end
and work well
but I need to check for every line in this script if return error then exit
and give me the line that make the error
so I make stupid script that
function Create_iis()
result1 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Set-ExecutionPolicy Unrestricted")
result2 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Import-Module WebAdministration")
result3 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","New-WebFtpSite -Name \"test\" -Port \"21\" -Force" )
result4 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","cmd \/c \\Windows\\System32\\inetsrv\\appcmd set SITE \"test\" \"-virtualDirectoryDefaults.physicalPath:C:\\inetpub\\ftproot\"")
result5 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpServer.security.ssl.controlChannelPolicy -Value 0")
result6 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpServer.security.ssl.dataChannelPolicy -Value 0")
result7 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpServer.security.authentication.basicAuthentication.enabled -Value $true")
result8 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpserver.userisolation.mode -Value 3")
result9 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Add-WebConfiguration \"\/system.ftpServer\/security\/authorization\" -value \#\{accessType=\"Allow\";roles=\"\";permissions=\"Read\,Write\";users=\"*\"} -PSPath IIS:\ -location \"test\"" )
result10 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Restart-WebItem \"IIS:\\Sites\\test\"")
end
and check for every result
but there are some commands that depend on each so it make error
it is impossible to make that ?
sorry for poor English
Thanks in advance
You can use io.popen to call a command in Lua:
local file = assert(io.popen('/bin/ls -la', 'r'))
local output = file:read('*all')
file:close()
print(output) -- > Prints the output of the command.
source: https://stackoverflow.com/a/5243210/1069083