Powershell Workflow not able to use -parameters to create a VM - powershell

I am having a problem with my Powershell Workflow that I am authoring in Windows Azure Pack Admin Site. In Powershell ISE, the following works but in Service Management Portal Admin Site Runbook Authoring, it does not work. Where it is getting stuck is that it is saying that it cannot validate the arguments passed -Name. I remove -Name out and now -FullName doesnt work. It seems like all the switch parameters for the command is not working. Can anyone help me out?
param (
[string]$DomainAdminAcct,
[string]$DomainAdminPass,
[string]$ServerName
)
InlineScript {
Add-PSSnapin VMWare.VimAutomation.Core
$vCenter = "test300"
Connect-ViServer -server $vCenter -ErrorAction Stop
$myCluster = Get-Cluster -Name "DC Test"
$myTemplate = Get-Template -Name "2012dc" -Location "our company"
$OSCustomizationSpec = New-OSCustomizationSpec –Name “$ServerName” –FullName “$ServerName” –OrgName “our company” –Domain “our.domain.com” –DomainUsername “$DomainAdminAcct” –DomainPassword "$DomainAdminPass" -AdminPassword "changeme" -ChangeSid
New-VM -Name $ServerName -ResourcePool $myCluster -Template $myTemplate -OSCustomizationSpec $OSCustomizationSpec
}
}

Sounds like you have Hyper-V and PowerCLI modules loaded and the commands are conflicting. It is trying to run New-VM from the Hyper-V module. You can confirm this by running:
get-command New-VM -all
You should see two commands one from the Hyper-V module and one from the Vmware module.
To get past the problem you can add the module name to the command name:
VMware.VimAutomation.Core\New-VM

for using parameters inside INLINESTRING structure, you must use $using:<>

Related

Rundeck output as clickable link

Does anyone know if there is a way to have the output of an executed job be a clickable link?
I have a script that gets a link for a virtual environment in vCenter via powercli and I wanted to simplify the process in which the user got the vmdk console brought up. They currently have to select->copy->paste to search bar for it to work.
Here is my script:
Echo "Your Virtual Machine is now created and is being retrieved now."
$vcenter_password= "#option.vcenter_password#"
$Template_Name= "#option.Template_Name#"
if(-not (Get-Module -Name VMware.PowerCLI -ListAvailable)){
Install-Module -Name VMware.PowerCLI -AllowClobber -Force -Confirm:$false
}
Connect-VIServer -Server {{vcenter}} -User Administrator#DEPLOY.COMMS -Password $vcenter_password -Force
Get-VM $Template_Name | Select-Object #{N="IP Address";E={#($_.guest.IPAddress[0])}}
Echo "Your VM is available at the following URL for the next 30 seconds:"
Open-VMConsoleWindow -VM "$Template_Name" -urlonly
If your app supports HTML links like appname://, you can generate an HTML anchor element output in your Rundeck job. Take a look at this.

Connect-AzAccount : The term 'Connect-AzAccount' is not recognized as the name of a cmdlet, function, script file, or operable program

I am trying to execute the following PowerShell script in Azure DevOps pipeline by using PowerShell task with inline mode.
$clientId= "xxxxxxxxx"
$clientSecret= "xxxxxxx"
$subscriptionId= "xxxxxxxx"
$tenantId= "xxxxxxxxxxxxx"
# sign in
Write-Host "Logging in...";
$SecurePassword = $clientSecret | ConvertTo-SecureString -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $clientId, $SecurePassword
Connect-AzAccount -ServicePrincipal -Credential $cred-Tenant $tenantId
# set azure context with subscriptionId
Set-AzContext -SubscriptionId $subscriptionId
# select subscription
Write-Host "Selecting subscription '$subscriptionId'";
Select-AzSubscription -SubscriptionId $subscriptionId;
But I am getting the following error:
Connect-AzAccount : The term 'Connect-AzAccount' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
It is possible that the module this command belongs to - 'Az' isn't present/have to be imported. In which case,
Case-1
Open Powershell as Administrator
Install module - Install-Module Az
Import-Module Az
Your command - Connect-AzAccount should work now.
For case-2
Import module using - Import-Module Az.Accounts
For me this was the issue - AzureRM and AZ both were installed.
In Windows PowerShell, check that you have AzureRM installed:
Get-InstalledModule -name AzureRM
use command Uninstall-AzureRM to remove it.
If above command doesn't work use below one
Get-Module -ListAvailable | Where-Object {$_.Name -like 'AzureRM*'} | Uninstall-Module
Next ->
Set executionPolicy to RemoteSigned for powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Next ->
Install the Az PowerShell Module in Windows PowerShell
Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force
Next ->
type Connect-AzAccount and complete the signing flow.
I would recommend you to switch to AzurePowershellTask as you find there preinstalled modules:
You can also try install modules on your own as it is shown here but this is pointless since you can leverage existing task.
In my case, AZ wasn't successfully installed because some AZ modules were already installed with AzureRM. I added the parameter -AllowClobber and now all the AZ modules are now installed.
Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -AllowClobber
Uninstalling AzureRM with command Uninstall-AzureRM may also be a great solution, because you're not going to use AzureRM anymore. Microsoft is going to stop supporting it sometimes in February 2024.
Try using
Login-AzAccount
instead of
Connect-AzAccount

Recycle an application pool using a PowerShell script

I want to recycle my application pool using one-liner command which I can put in my PowerShell script. I added the following code in my PowerShell script:
Import-Module WebAdministration
$site = "Default Web Site"
$pool = (Get-Item "IIS:\Sites\$site"| Select-Object applicationPool).applicationPool
Restart-WebAppPool $pool
But I am getting an error that name IIS doesn't exist. How can I fix it?
Short and simple, like this...
Restart-WebAppPool (Get-Website -Name <YourSiteName>).applicationPool
You can use appcmd.exe:
appcmd recycle apppool /apppool.name:'MyAppPool'
You can also retrieve the corresponding WMI instance and invoke the Recycle() method:
$myAppPool = Get-WmiObject -Namespace root\WebAdministration -Class ApplicationPool -Filter "Name = 'MyAppPool'"
$myAppPool.Recycle()
The following command works for me
invoke-command -computername servername -scriptblock {C:\Windows\System32\inetsrv\appcmd.exe recycle apppool "apppoolname"}
This may work:
Write-Host "App Pool Recycling Started...."
& $env:windir\system32\inetsrv\appcmd list apppools /state:Started /xml | & $env:windir\system32\inetsrv\appcmd recycle apppools /in
Write-Host "App Pool Recycling Completed"
It works for me in AWS through the Run command.
Use:
Import-Module WebAdministration
$site = "MySite"
$pool = (Get-Item "IIS:\Sites\$site"| Select-Object applicationPool).applicationPool
#Recycle the application pool:
Restart-WebAppPool $pool
Since WebAdministration is old and badly supported under PowerShell 7, here's an updated answer using the fresher IISAdministration module:
Import-Module IISAdministration
$pool = Get-IISAppPool -Name "DefaultAppPool"
$pool.Recycle()
You can also do this as a two-liner, or even one-liner if you import the module in your profile:
Import-Module IISAdministration
(Get-IISAppPool("DefaultAppPool")).Recycle()
Do note that accessing the IISServerManager object requires administrative permissions.
I don't run all PowerShell scripts as administrator - it's dangerous.
But appcmd.exe is not available unless running in an administrator prompt.
This command line will prompt for elevation if you're running in a regular, un-elevated prompt:
Start-Process c:\windows\System32\inetsrv\appcmd.exe "recycle apppool /apppool.name:MyAppPool" -Verb RunAs
In case you need to recycle all the Application Pools:
Import-Module IISAdministration
Get-IISAppPool | ForEach-Object{ if($_.State -eq "Started"){ $_.Recycle() } }
If the AppPool is stopped it will throw an exception
Use the -Name option:
IIS:\> Restart-WebAppPool -Name "DefaultAppPool"

Cmdlets not found in command line but available in ISE

I'm trying to create an IIS application and app pool using PowerShell on a Windows Server 2008 R2 VM. The powershell script is as follows:
Param(
[string] $branchName,
[string] $sourceFolder
)
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "You do not have Administrator rights to run this script. `nPlease re-run this script as an Administrator."
Exit
}
$appPool = $branchName
$site = "Default Web Site"
#Add APPPool
New-WebAppPool -Name $appPool -Force
#Create Applications
New-WebApplication -Name $branchName -Site $site -PhysicalPath $sourceFolder - ApplicationPool $appPool -Force
If I run the script in the PowerShell ISE it works fine but if I run it from a command line (or a batch file using the command line) I get the error
The term New-WebAppPool is not recognized as the name of a cmdlet... etc.
Is there a way that the web administration cmdlets could be installed in the ISE but not the command line?
Assuming that you're using PowerShell v2 (the default version installed with Server 2008 R2) it's as #jisaak suspected: you need to import the module WebAdministration explicitly in your code:
Import-Module WebAdministration
ISE seems to do that automatically.
Another option would be to upgrade to PowerShell v4, which also automatically imports modules when one of their exported cmdlets is used.
For anyone interested, the answer was painfully simple. As suggested, the solution was to import the module, but there was an issue was that it wasn't available after closing the console and reopening it. To solve this I simply had to add the line into the powershell itself so it imports the module at every runtime.
Param(
[string] $branchName,
[string] $sourceFolder)
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "You do not have Administrator rights to run this script.`nPlease re-run this script as an Administrator."
Exit
}
$appPool = $branchName
$site = "Default Web Site"
*Import-Module WebAdministration*
#Add APPPool
New-WebAppPool -Name $appPool -Force
#Create Applications
New-WebApplication -Name $branchName -Site $site -PhysicalPath $sourceFolder - ApplicationPool $appPool -Force

Iterate through a list of VMs in Azure

i have about 10 VMs hosted on Auzre, i need to iterate through each of them and then execute a powershell script on each of them, lets say 'Set-Date'
whats the best way to connect to each VM, execute the ps script and then disconnect?
You can use PowerShell Remoting or custom scripts via extensions to execute PowerShell code on the remote VM.
For both solutions you get your list of VMs with the PowerShell command Get-AzureVM. Use a loop to iterate those VMs. I skip that part here because iterating are PowerShell basics.
1. PowerShell Remoting
For this you need PowerShell Remoting enabled on the remote VM and have an open port for PowerShell Remoting. Both is a default setting for new VMs.
Advantage: this solution is very handy for interactive sessions with a remote VM. Disadvantage of this solution is, that you need to authenticate to each VM and have to keep connected while execution.
With each VM you can do something like this. This is a shortened example where I have installed ADDS on the remote VM.
# Prepare credentials for remote session.
$secpasswd = ConvertTo-SecureString $AdminPassword -AsPlainText -Force
$credentialDC1 = New-Object System.Management.Automation.PSCredential ($AdminUsername, $secpasswd)
$EndpointDC = Get-AzureWinRMUri -ServiceName testlab-dc -Name dc1
#$EndpointDC = Get-AzureVM -ServiceName testlab-dc -Name dc1 | Get-AzureEndpoint -Name WinRmHTTPs
$psso = New-PSSessionOption -SkipCACheck
$sessionDC = New-PSSession -ComputerName testlab-dc.cloudapp.net -Port $EndpointDC.Port -Credential $credentialDC1 -UseSSL -SessionOption $psso
Invoke-Command -Session $sessionDC -ScriptBlock {
# Set-Date or other command
# or for example
# Install-WindowsFeature AD-Domain-Services
}
Remove-PSSession -Session $sessionDC
2. Custom Scripts via Extensions
Here you can upload a PowerShell file into your BLOB storage and then let execute that file on your VMs. Requirement is that the VM agent has to be installed on the VM. (Default for new VMs from the gallery.)
Advantage: you do not need to authenticate to each VM and you do not need to keep connect while execution.
Disadvantage: you have to prepare a separate PowerShell file to upload. Getting results is asynchronous.
Example:
# Upload PowerShell file
Set-AzureStorageBlobContent -Container extensions -File "Install-ADForest.ps1" -Blob "Install-ADForest.ps1"
# Install AD services and forrest
Get-AzureVM -ServiceName demoext -Name demoext |
Set-AzureVMCustomScriptExtension -ContainerName extensions -FileName "Install-ADForest.ps1" |
Update-AzureVM
The container has to exist. Create that container before you upload the file.