PowerShell 7 Remoting from Azure DevOps Pipeline - powershell-7.0

We were using Azure DevOps Pipelines and PowerShell Remoting to execute PS1 scripts:
trigger: none
jobs:
- job: PSRemoting
timeoutInMinutes: 5760
pool:
name: 'DevOps-Agent2-VM'
steps:
- checkout: none
- task: PowerShellOnTargetMachines#3
displayName: 'PSRemoting'
inputs:
Machines: '$(VM-PublicIP)'
UserName: '$(VM-UserName)'
UserPassword: '$(VM-Password)'
InlineScript: |
. C:\Scripts\Test-Parallel.ps1
We have added -parallel feature that requires PowerShell 7 and our scripts are failing now:
2022-11-02T13:37:18.3246154Z ForEach-Object : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ & 'C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe' -NoLogo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (ForEach-Object ...med parameters.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
At C:\Scripts\Test-Parallel.ps1:3 char:10
+ $items | ForEach-Object -Parallel {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [ForEach-Object], ParentContainsErrorRecordExcep
tion
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.ForEachObjectCo
mmand
##[error]Non-Zero exit code: '1' for ComputerName: 'VM1'
##[error]Atleast one remote job failed. Consult logs for more details. ErrorCodes(s): 'RemoteDeployer_NonZeroExitCode'
##[section]Finishing: PSRemoting
Here is Test-Parallel.ps1:
$items = 1..100
$items | ForEach-Object -Parallel {
Write-Host "$(Get-Date) | Sleeping for 1 second..."
Start-Sleep 1
} -ThrottleLimit 10
How can we force PowerShell to run version 7 with our Azure DevOps Pipeline task?

Try this in your Test-Parallel.ps1 script:
workflow Test-PipelineDeploy {
$items = 1..100
foreach -parallel ($item in $items) {
Write-Host "$(Get-Date) | Sleeping for 1 second..."
Start-Sleep 1
} -ThrottleLimit 10
}
Then call Test-PipelineDeploy

Related

Do Azure workflows need additional authentication considerations?

I'm unable to deploy availability sets in parallel from a simple table from Powershell ISE onto my MSDN subscription.
Table
Type RG Name Loc
AvSet NLG NLGUTCDCPWFEAVL01 eastus2
AvSet NLG NLGUTCDCPAPPAVL01 eastus2
AvSet NLG NLGUTCDCPCCDBAVL01 eastus2
This works when executed without a workflow.
$c=Import-Csv C:\Users\ayanm\Downloads\NLG.csv|? type -eq 'AVSet'
foreach ($b in $c)
{New-AzureRmAvailabilitySet -ResourceGroupName $b.RG -Name $b.name -Location $b.loc}
But when I try to put it in a workflow, it doesn't
Workflow Deploy-AVSet
{$c=Import-Csv C:\Users\ayanm\Downloads\NLG.csv|? type -eq 'AVSet'
foreach -Parallel ($b in $c)
{New-AzureRmAvailabilitySet -ResourceGroupName $b.RG -Name $b.name -Location $b.loc}
}
Error:
Microsoft.PowerShell.Utility\Write-Error : Run Login-AzureRmAccount to login.
At Deploy-AVSet:4 char:4
+ CategoryInfo : NotSpecified: (:) [Write-Error], RemoteException
+ FullyQualifiedErrorId : System.Management.Automation.RemoteException,Microsoft.PowerShell.Commands.WriteErrorCommand
Checked Powershell version; 5.1. Updated all modules. Rebooted computer. Is this an unsupported workflow activity?
https://blogs.technet.microsoft.com/heyscriptingguy/2013/01/02/powershell-workflows-restrictions/
The `Login-AzureRmAccount' cmdlet doesn't MSDN crediantial object. So I added an O365 account as an owner of the subscription and am able to deploy in parallel.
Workflow Deploy-AVSet
{$c=Import-Csv C:\Users\ayanm\Downloads\NLG.csv|? type -eq 'AVSet'
$cred= New-Object System.Management.Automation.PSCredential "name#domain.onmicrosoft.com",$(ConvertTo-SecureString "Password" -asplaintext -force)
foreach ($b in $c)
{AzureRM.Resources\Login-AzureRmAccount -Credential $cred
New-AzureRmAvailabilitySet -ResourceGroupName $b.RG -Name $b.name -Location $b.loc -PlatformFaultDomainCount $b.faultdomain -PlatformUpdateDomainCount $b.UpdateDomain
}
}

Importing Bulk user CSV file

Been trying all day to import my CSV file to my AD on Windows Server 2012.
But keep getting all kind of errors.
The error I get is this:
"New-ADUser : Cannot validate argument on parameter 'Name'. The argument is null
or empty. Provide an argument that is n ot null or empty, and then try the
command again.
At line:3 char:90
+ ... ipalname -Name $_.name -DisplayName $_.name -GivenName $_.cn -SurName $_.sn -Dep ...
+ ~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.NewADUsery
Can't seem to find any solution to this, so some help would be great. Here is my files.
This is my script:
Import-Csv .\nb1.csv | ForEach-Object {
$userprincipalname = $_.SamAccountName + "#hirethistire.local"
New-ADUser -SamAccountName $_.SamAccountName -UserPrincipalName $userprincipalname -Name $_.name -DisplayName $_.name -GivenName $_.cn -SurName $_.sn -Department $_.Department -Path "CN_Users,DC=HireThisTire,DC=local"-AccountPassword (ConvertTo-SecureString "Microsoft~1;" -AsPlainText -force) -Enabled $true -PasswordNeverExpires $true -PassThru
}
Sample Of the CSV File:

merging two Jsons in powershell

I have the following two Objects , which have been got from 2 Json file using:
$Env = ConvertFrom-Json "$(get-content "C:\chef\environments.json")"
$Roles = ConvertFrom-Json "$(get-content "C:\chef\roles.json")"
Heres the out put after conversion :
PS C:\chef> $Env
run_list
--------
{recipe[djin_chef-max_any::default]}
PS C:\chef> $Roles
7-zip : #{home=%SYSTEMDRIVE%\7-zip}
cookbook_versions :
default : #{env=development}
modmon : #{env=dev}
paypal : #{artifact=%5BINTEGRATION%5D}
seven_zip : #{url=https://djcm-zip-local/djcm/chef}
task_sched : #{credentials=XN$q}
windows : #{password=K1N5}
I need to merge these two Json objects in powershell and I tried the following:
PS C:\chef> $Roles+$Env
Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
At line:1 char:1
+ $Roles+$Env
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Is there another elegant way of doing it if I am doing it wrong or why am I getting this error ?
$Env only has one property, so you could add a new member to $Roles:
$Roles | Add-Member -NotepropertyName run_list -NotePropertyValue $Env.run_list
This syntax work in PowerShell v3, but you listed v2 and v2 in your tags.. so for v2:
$Roles | Add-Member -MemberType NoteProperty -Name run_list -Value $Env.run_list

Problems in reading a commandline json object using powershell

I have a powershell script "test.ps1" which takes a json string as a command line input & tries to parse it.
The powershell script is as below -
param(
[string]$json = $(throw 'test')
)
$currentPath = Get-Location
[Reflection.Assembly]::LoadFile("$currentPath\Newtonsoft.Json.dll")
$result = [Newtonsoft.Json.Linq.JObject]::Parse($json)
foreach($unit in $result["DevResults"]) {Write-Host $unit.TechnologyName.ToString()}
But it is giving me the below error -
PS C:\Users\aghosh.RJFDEV\Documents> ./test.ps1 '{"DevResults":[{"TechnologyName":"TFS","RuleName":"Alt CI ID for ESB","OutputValue":"ESClientCenter"},{"TechnologyName":"TFS","RuleName":"TFS Team Project Name","OutputValue":"ClientCenter"}],"QaResults":[{"TechnologyName":"TFS","RuleName":"Alt CI ID for ESB","OutputValue":"ESClientCenter"},{"TechnologyName":"TFS","RuleName":"TFS Team Project Name","OutputValue":"ClientCenter"}],"PreProdResults":[{"TechnologyName":"TFS","RuleName":"Alt CI ID for ESB","OutputValue":"ESClientCenter"},{"TechnologyName":"TFS","RuleName":"TFS Team Project Name","OutputValue":"ClientCenter"}],"ProdResults":[{"TechnologyName":"TFS","RuleName":"Alt CI ID for ESB","OutputValue":"ESClientCenter"},{"TechnologyName":"TFS","RuleName":"TFS Team Project Name","OutputValue":"ClientCenter"},{"TechnologyName":"TFS","RuleName":"Process Template","OutputValue":"Raymond James CMMI V3.5"}]}'
GAC Version Location
--- ------- --------
False v2.0.50727 C:\Users\aghosh.RJFDEV\documents\Newtonsoft.Json.dll
You cannot call a method on a null-valued expression.
At C:\Users\aghosh.RJFDEV\Documents\test.ps1:13 char:82
+ foreach($unit in $result["DevResults"]) {Write-Host $unit.TechnologyName.ToString <<<< ()}
+ CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\aghosh.RJFDEV\Documents\test.ps1:13 char:82
+ foreach($unit in $result["DevResults"]) {Write-Host $unit.TechnologyName.ToString <<<< ()}
+ CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
My powershell version is 2.0 & the Json.Net library version is 3.5.
Please help me with the error or please suggest any other suitable approach.
Thanking in advance.
Change this line:
foreach($unit in $result["DevResults"]) {Write-Host $unit.TechnologyName.ToString()}
To this:
foreach($unit in $result["DevResults"]) {Write-Host $unit["TechnologyName"].ToString()}

Powershell: cannot call a method on a null-valued expression error

I am trying to login to a website via powershell.
Here is PS code
$username = "userhere"
$password = "passhere"
$ie = New-Object -com InternetExplorer.Application
$ie.visible=$false
$ie.navigate("http://www.desistream.tv/en/login.shtml")
while($ie.ReadyState -ne 4) {start-sleep -m 100}
$ie.document.getElementById("username").value= "$username"
$ie.document.getElementById("pass").value = "$password"
$ie.document.getElementById("loginform").submit()
start-sleep 20
$ie.Document.body | Out-File -FilePath c:\web.txt
Here is Error I get when I run script.
PS C:\Users\myname\Desktop> .\new.ps1
You cannot call a method on a null-valued expression.
At C:\Users\myname\Desktop\new.ps1:9 char:1
+ $ie.document.getElementById("loginform").submit()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PS C:\Users\myname\Desktop> http://www.desistream.tv/en/index.shtml
The page doesn't have an element with the ID "loginform".