Publishing results in NUnit tests - powershell

I am writing a PowerShell script for multithreading NUnit tests. My problem is that I take test categories from the file category.txt, and I have to write which categories have been done into my output file file 1.txt. I also need to output an XML report after all tests have been performed. How can I do this in NUnit?
$Groups=Get-Content d:\test\category.txt | Select-Object -Last 10
Write-Host $Groups
if ($Groups -ne $null)
{Write-Host "true"}
else
{write-host "false"}
###Multithreading###
$ThreadNumber =$Groups.Count
$ScriptBlock = {
function Nunit {
$Connection = #{"server" = ""; "username" = ""; "password" = ""}
write-verbose $Connection
$serv = $connection.Get_Item("server")
$user = $connection.Get_Item("username")
$pass = $connection.Get_Item("password")
$securePassword = ConvertTo-SecureString -AsPlainText $pass -Force
#Create connection credentials object for Invoke-Command
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user, $securePassword
$Output = "C:\"
$scriptBlock = {
CMD.EXE /C "C:\testNunit\bin\nunit-console.exe /xml:c:\console-test.xml C:\testNunit\dll\Tests.dll /include:TestTypeSmoke> c:\1.txt"
}
Invoke-Command -ComputerName $serv -ScriptBlock $scriptBlock -credential $cred
}
Nunit
}

I will try to get back to you on NUnit after trying some things at my end, but as a suggestion you could also try PowerShell Workflow for Multi-Threading. They work like functions.
Workflow NUnit
{
Param
(
$server,
$username,
$password,
)
foreach -parallel -throttlelimit 2($group in $groups)
try{
//NUnit Code here
}
}
Catch
{
$_.Exception.Message
}
}
}
NUnit-server "" -username "" -password ""

Related

Try different credentials PS script SSH

I have this script and cannot work correctly .. I try to connect with 2 users ; if one doesn't work try other one.
#1. Try user and pass1 if is not good try #2. user and pass2.
*problem is with winscp users ; I really don't know how to implement 2 try connection
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" +$myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
$db = import-csv -Path "C:\Program Files (x86)\WinSCP\db.csv"
$inputID = Read-Host -Prompt "ID"
$entry = $db | where-Object {$_.HostName -eq $inputID}
if ($inputID -eq $entry.HostName){
"$inputID Ok!"
}
else{
"$inputID nu exista in baza de date!"
$title = 'Title'
$question = 'Doriti sa introduceti un ID nou in Baza de Date?'
$choices = '&Yes', '&No'
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'confirmed'
$ID = Read-Host -Prompt "Introduceti ID"
$IP = Read-Host -Prompt "Introduceti IP"
$wrapper = New-Object PSObject -Property #{ HostName = $ID; IP = $IP }
Export-Csv -Append -InputObject $wrapper -Path "C:\Program Files (x86)\WinSCP\db.csv" -NoTypeInformation -Force
$dbTrimmer = Get-Content -Path "C:\Program Files (x86)\WinSCP\db.csv"
$dbTrimmer.Replace('","',",").TrimStart('"').TrimEnd('"') | Out-File "C:\Program Files (x86)\WinSCP\db.csv" -Force -Confirm:$false
Exit
}
else{
Write-Host 'No'
Exit
}
}
Write-Host "IP:" $entry.IP
$User = "user"
$Password = "pass"
$Command = "C:\Info.exe"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials -AcceptKey:$true
Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = $entry.IP
UserName = "$User"
Password = "$Password"
GiveUpSecurityAndAcceptAnySshHostKey = "true"
}
$session = New-Object WinSCP.Session
$file = "Dev.log", "Info.dat"
$localPath = "E:\Arhive\*"
$remotePath = "/C:/Program Files/Dev.log", "/C:/Program File/Info.dat"
try {
# Connect
$session.Open($sessionOptions)
# Check exists files
foreach ($remotePath in $remotePath)
{
if ($session.FileExists($remotePath))
{
Write-Host "Fisierul $remotePath exista"
# Transfer files
$session.GetFiles($remotePath, $localPath).Check()
}
else
{
Write-Host "Fisierul $remotePath NU exista"
}
}
}
finally {
$session.Dispose()
}
foreach ($file in "E:\loguri\Dev.log", "E:\loguri\Info.dat") {
if (Test-Path $file) {
Compress-Archive $file -DestinationPath "E:\Arhive\$inputID.zip" -Update
Remove-Item $file
}
}
# Stergere fisiere din Arhive mai vechi de 60 minute
$Files = get-childitem 'E:\Arhive' | Where-Object PSIsContainer -eq $false
$LimitTime = (Get-Date).AddMinutes(-60)
$Files | ForEach-Object {
if ($_.CreationTime -lt $LimitTime -and $_.LastWriteTime -lt $LimitTime) {
Remove-Item -Path $_.FullName -Force
Write-Host "Am sters $Files pentru ca sunt mai vechi de $LimitTime !"
}
}
Here is all my script. In this moment all works very well , just I want to add 2 users for auth. If 1 fail try other one.
Any ideea ? Thank you
I couldn't test this myself, but I think I would go about it like below:
$User = "SameUser"
$Password = "Pass1"
$sPassword = "Pass2"
$Command = "C:\Info.exe"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$ssecpasswd = ConvertTo-SecureString $sPassword -AsPlainText -Force
Get-SSHTrustedHost | Remove-SSHTrustedHost
try {
# try the first credentials
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials -AcceptKey:$true -Verbose -ErrorAction Stop
}
catch {
# first one failed, try second credentials
$Credentials = New-Object System.Management.Automation.PSCredential($User, $ssecpasswd)
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $sCredentials -AcceptKey:$true -Verbose
}
try {
Invoke-SSHCommand -SessionId $SessionID.SessionId -Command $Command -ErrorAction Stop
}
catch {
throw
}
# create a hashtable with the first password
$options = #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = $entry.IP
UserName = $User
Password = $Password
GiveUpSecurityAndAcceptAnySshHostKey = $true
}
try {
# Set up session options using first password
$sessionOptions = New-Object WinSCP.SessionOptions -Property $options
$session = New-Object WinSCP.Session
# Try Connect
$session.Open($sessionOptions)
}
catch {
# Set up session options using second password
$options['Password'] = $sPassword
try {
$sessionOptions = New-Object WinSCP.SessionOptions -Property $options
$session = New-Object WinSCP.Session
# Try Connect
$session.Open($sessionOptions)
}
catch {
Write-Error "Could not open WinSCP session: $($_.Exception.Message)"
throw
}
}
try {
# Check if exists files.
# Make sure variables $remotePath and $localPath are defined on top of the script
foreach ($remoteFile in $remotePath) {
if ($session.FileExists($remoteFile)) {
$session.GetFiles($remotePath, $localPath).Check()
}
else {
Write-Warning "File '$remoteFile' not found"
}
}
}
catch {
Write-Error "Could not open WinSCP session: $($_.Exception.Message)"
}
finally {
if ($session) { $session.Dispose() }
}

Connect-MsolService - providing credentials without exposing password in script

I wish to run the below PowerShell script as a scheduled task to pull provisioning logs from Azure AD. However, I do not wish to embed the password. I appreciate this is not a problem specific to PowerShell or Microsoft Online. What technique can I use to not have the password stored as clear text? Thanks
Script credits go to: Pawel Janowicz
$AzureUsername = 'log.reader#tenant.net'
$Password = "xxxxxx"
$SecureString = ConvertTo-SecureString -AsPlainText $Password -Force
$SecuredCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AzureUsername,$SecureString
$OutputCSV = "$Env:USERPROFILE\desktop\DirSyncProvisioningErrors_$(Get-Date -Format "yyyyMMdd").csv"
###### Connecting ############################################################################################################
Try{
[void] (Connect-MsolService -Credential $SecuredCreds)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $SecuredCreds -Authentication Basic -AllowRedirection
[void] (Import-PSSession $Session -DisableNameChecking)
}
Catch{
$_.Exception.Message
Read-Host 'Press enter to close the window'
Remove-PSSession $Session
Exit
}
###### Getting errors ########################################################################################################
If(Get-MsolHasObjectsWithDirSyncProvisioningErrors){
Try{
$Errors = Get-MsolDirSyncProvisioningError -All | select DisplayName,ObjectID,ObjectType,ProvisioningErrors
$Results = Foreach ($i in $Errors){
$AllErrors = $i.ProvisioningErrors
$AllErrors | %{
$ErrorItem = $_
Get-AzureADObjectByObjectId -ObjectIds $i.objectid | Foreach{
New-Object PSObject -Property ([ordered]#{
'Displayname' = $i.displayname
'ObjectType' = $i.ObjectType
'Attribute' = $ErrorItem.propertyname
'Conflicting value' = $ErrorItem.propertyvalue
})
}
}
}
}
Catch{
$_.Exception.Message
Read-Host 'Press enter to close the window'
Remove-PSSession $Session
Exit
}
}
###### Results ###############################################################################################################
If($Results){
$Results | Format-Table -AutoSize
#Exporting CSV
$Results | Export-CSV $OutputCSV -NoTypeInformation -Force
}
Remove-PSSession $Session
Thank You Theo for providing your suggestion as a comment. Making this as answer to help other community member.
I have executed the command and getting a display to enter the password rather than it was manually provided in script itself.
$SecuredCreds = Get-Credential -UserName 'log.reader#tenant.net' -Message "Please enter credentials"
$OutputCSV = "$Env:USERPROFILE\desktop\DirSyncProvisioningErrors_$(Get-Date -Format "yyyyMMdd").csv"
###### Connecting ############################################################################################################
Try{
[void] (Connect-MsolService -Credential $SecuredCreds)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $SecuredCreds -Authentication Basic -AllowRedirection
[void] (Import-PSSession $Session -DisableNameChecking)
}
Catch{
$_.Exception.Message
Read-Host 'Press enter to close the window'
Remove-PSSession $Session
Exit
}
###### Getting errors ########################################################################################################
If(Get-MsolHasObjectsWithDirSyncProvisioningErrors){
Try{
$Errors = Get-MsolDirSyncProvisioningError -All | select DisplayName,ObjectID,ObjectType,ProvisioningErrors
$Results = Foreach ($i in $Errors){
$AllErrors = $i.ProvisioningErrors
$AllErrors | %{
$ErrorItem = $_
Get-AzureADObjectByObjectId -ObjectIds $i.objectid | Foreach{
New-Object PSObject -Property ([ordered]#{
'Displayname' = $i.displayname
'ObjectType' = $i.ObjectType
'Attribute' = $ErrorItem.propertyname
'Conflicting value' = $ErrorItem.propertyvalue
})
}
}
}
}
Catch{
$_.Exception.Message
Read-Host 'Press enter to close the window'
Remove-PSSession $Session
Exit
}
}
###### Results ###############################################################################################################
If($Results){
$Results | Format-Table -AutoSize
#Exporting CSV
$Results | Export-CSV $OutputCSV -NoTypeInformation -Force
}
Remove-PSSession $Session

Find the exact matched string from the variable

In the below code, $Result variable has the following information. I need to iterate below each line in $Result variable and get the <APPPOOL NAME> that is, "DefaultAppPool","Classic .NET AppPool" & ".NET v2.0 Classic" as an input to the second Invoke-Command saved in $Result2. Please advise how this can be accomplished.
$Result output:
APPPOOL "DefaultAppPool" (MgdVersion:v4.0,MgdMode:Integrated,state:Started)
APPPOOL "Classic .NET AppPool" (MgdVersion:v2.0,MgdMode:Classic,state:Started)
APPPOOL ".NET v2.0 Classic" (MgdVersion:v2.0,MgdMode:Classic,state:Started)
$Username = '<username>'
$Password = '<Password>'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $pass
$input_file_path = "servers.txt"
$output_path = "result.txt"
foreach ($server in Get-Content $input_file_path) {
$Result = Invoke-Command -ComputerName $server -Credential $Cred -ScriptBlock {
C:\Windows\system32\inetsrv\appcmd.exe list apppools
}
$Result | Add-Content $output_path
$Result2 = Invoke-Command -ComputerName #server -Credential $Cred -ScriptBlock {
C:\Windows\system32\inetsrv\appcmd.exe list apppools <APPPOOL NAME> /text:processmodel.username
}
}

How to pass param value to the Invoke-Command cmdlet?

I wrote a simple powershell script to modify hosts file on remote machines but something goes wrong.
Script:
param(
[string]$value
)
$username = 'username'
$password = 'password'
$hosts = "172.28.30.45","172.28.30.46"
$pass = ConvertTo-SecureString -AsPlainText $password -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$pass
ForEach ($x in $hosts){
echo "Write in $x , value: $value"
Invoke-Command -ComputerName $x -ScriptBlock {Add-Content -Path "C:\Windows\system32\drivers\etc\hosts" -Value $value} -Credential $cred
echo "Finish writing."
}
echo "End of PS script."
When run, it writes a new empty line for each hosts file. This line echo "Write in $x , value: $value" displays $value value.
What I'm doing wrong?
You have to pass the parameter to the scriptblock by defining a param section within your scriptblock and pass the parameters using -ArgumentList :
Invoke-Command -ComputerName $x -ScriptBlock {
param
(
[string]$value
)
Add-Content -Path "C:\Windows\system32\drivers\etc\hosts" -Value $value
} -Credential $cred -ArgumentList $value
Or you leverage the using: variable prefix:
Invoke-Command -ComputerName $x -ScriptBlock {
Add-Content -Path "C:\Windows\system32\drivers\etc\hosts" -Value $using:value
} -Credential $cred

invoke-parallel in Powershell - data sharing inside script with global variable

Using invoke-parallel in Powershell, I'm trying to get a list of hosts where a certain command works vs. does not. How can I write to a global variable inside of invoke-parallel?
$creds = Get-Credential -UserName $username -Message 'Password?'
$servers = get-content .\hosts.txt
$success = #()
$failure = #()
Invoke-Parallel -InputObject $servers -throttle 20 -runspaceTimeout 30 -ImportVariables -ScriptBlock {
try
{
$result = Invoke-Command $_ -Credential $creds -Authentication "Negotiate" -ErrorAction Stop {hostname}
$success += $result
}
catch
{
$failure += $_
}
}
write-host $success
write-host $failure
Try this:
$Results = Invoke-Parallel -InputObject $servers -throttle 20 -runspaceTimeout 30 -ImportVariables -ScriptBlock {
try
{
$Output = Invoke-Command $_ -Credential $creds -Authentication "Negotiate" -ErrorAction Stop {hostname}
}
catch
{
$Output = $_
}
#($Output)
}
Final code sample for what I ended up using.
$username = "myuser"
$creds = Get-Credential -UserName $username -Message 'Password?'
$servers = get-content .\hosts.txt
$Results = Invoke-Parallel -InputObject $servers -throttle 20 -runspaceTimeout 30 -ImportVariables -ScriptBlock {
$arr = #{}
try
{
$Output = Invoke-Command $_ -Credential $creds -Authentication "Negotiate" {hostname} -ErrorAction Stop
$arr[$_] = "successful"
}
catch
{
$arr[$_] = "failed"
}
$arr
}
$Results