properties wrong in Powershell - powershell

i have a problem with my PS code, i have to start my tests on browsers every tuesday in teamcity! and i wrote the function which goes on my server with credentials and try to make my tests on it
function HTTP-GetRequest($url, $username, $password)
{
$properties = Resolve-Path "C:\Users\Uladzimir_Vaitsiakho\Documents\CI\Build\CI_2.0\vsphere\properties.ps1"
Write-Host $properties
. $properties
$webRequest = [System.Net.WebRequest]::Create($url)
$webRequest.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $username, $password
$webRequest.PreAuthenticate = $true
$webRequest.Headers.Add("AUTHORIZATION", "Basic");
[System.Net.WebResponse] $resp = $webRequest.GetResponse();
$rs = $resp.GetResponseStream();
[System.IO.StreamReader] $sr = New-Object System.IO.StreamReader -argumentList $rs;
[string] $results = $sr.ReadToEnd();
return $results
}
if (($today.DayOfWeek) -eq "Tuesday")
{
if ($env:Browser -eq "Firefox"){
$url = "http://1111111/httpAuth/action.html?add2Queue=bt6&&env.name=Browser&env.value=Chrome"
HTTP-GetRequest $url, $teamcity_username, $teamcity_password
Write-Host $teamcity_password
Write-Host $teamcity_username
}
if ($env:Browser -eq "Chrome"){
$url = "http://11111/httpAuth/action.html?add2Queue=bt6&&env.name=Browser&env.Value=InternetExplorer"
HTTP-GetRequest $url, $teamcity_username, $teamcity_password
}
}
And have got the next output with troubles, but file with properties and credentials i gave to my function, what's can be wrong?!
Cannot convert argument "0", with value: "System.Object[]", for "Create" to type "System.Uri": "Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Uri"."
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:6 char:47
+ $webRequest = [System.Net.WebRequest]::Create <<<< ($url)
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
Property 'Credentials' cannot be found on this object; make sure it exists and is settable.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:7 char:14
+ $webRequest. <<<< Credentials = New-Object System.Net.NetworkCredential -ArgumentList $username, $password
+ CategoryInfo : InvalidOperation: (Credentials:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Property 'PreAuthenticate' cannot be found on this object; make sure it exists and is settable.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:10 char:14
+ $webRequest. <<<< PreAuthenticate = $true
+ CategoryInfo : InvalidOperation: (PreAuthenticate:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
You cannot call a method on a null-valued expression.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:11 char:25
+ $webRequest.Headers.Add <<<< ("AUTHORIZATION", "Basic");
+ CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:13 char:58
+ [System.Net.WebResponse] $resp = $webRequest.GetResponse <<<< ();
+ CategoryInfo : InvalidOperation: (GetResponse:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:14 char:31
+ $rs = $resp.GetResponseStream <<<< ();
+ CategoryInfo : InvalidOperation: (GetResponseStream:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
New-Object : Constructor not found. Cannot find an appropriate constructor for type System.IO.StreamReader.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:15 char:43
+ [System.IO.StreamReader] $sr = New-Object <<<< System.IO.StreamReader -argumentList $rs;
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:16 char:35
+ [string] $results = $sr.ReadToEnd <<<< ();
+ CategoryInfo : InvalidOperation: (ReadToEnd:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

Currently the call to HTTP-GetRequest is passing an array of objects ($url, $teamcity_username , $teamcity_password) to the function. Remove the commas from your function call:
HTTP-GetRequest $url $teamcity_username $teamcity_password

Related

PowerShell remoting to execute Windows update

I need to modify the below script to execute the Windows Update so it downloads and updates the remote server:
Invoke-RemoteExecution($computername){
$cred = get-credential
invoke-command -computername $computername -Credential $cred -scriptblock {
Function Search-Updates
{
$Criteria = "IsInstalled=0 and Type='Software'"
#Search for relevant updates.
$Searcher = New-Object -ComObject Microsoft.Update.Searcher
$SearchResult = $Searcher.Search($Criteria).Updates
return [System.MarshalByRefObject]$SearchResult
}
Function Download-Updates
{
Param ($SearchResult)
$Session = New-Object -ComObject Microsoft.Update.Session
$Downloader = $Session.CreateUpdateDownloader()
$Downloader.Updates = $SearchResult
$Downloader.Download()
}
[System.MarshalByRefObject]$SearchResult = Search-Updates
Download-Updates -SearchResult $SearchResult
}
}
Invoke-RemoteExecution -computername yourcomputername
The error I am facing is like the below:
Invoke-RemoteExecution -computername PRD-SVR01-VM
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : OperationStopped: (:) [], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException
+ PSComputerName : PRD-SVR01-VM
The property 'Updates' cannot be found on this object. Verify that the property exists and can be set.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
+ PSComputerName : PRD-SVR01-VM
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName : PRD-SVR01-VM
I have tried to use the remoting but it is still failed as above.

How to write to worksheet.range with system.collections.ArrayList by Powershell?

when I try to write to worksheet.range with system.collections.ArrayList, It was failed, but because it was an One-dimensional array when I transfer it to be system.Array, it was been an One-dimensional array, How can I transfer it into a two-dimensional array? or how to write to worksheet?
Error:
[DBG]: PS C:\Users\xxxxxxxxx>>
Missing parameter does not have a default value.
Parameter name: parameters
At C:\Users\xxxxxxxxx\Desktop\txt2excel.ps1:148 char:1
$ws.Range($startCell,$endCell).Value2 = $target_columns
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
[DBG]: PS C:\Users\xxxxxxxxx>> $ws.Range($startCell,$endCell).Value2 = [System.Array]$target_columns
Exception from HRESULT: 0x800A03EC
At line:1 char:1
$ws.Range($startCell,$endCell).Value2 = [System.Array]$target_columns
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
main code:
$original_file = Get-Content $originalTXT[1]
$target_columns = New-Object System.Collections.ArrayList
foreach ($ss in $original_file) {
[System.Collections.ArrayList]$target_row_temp = $ss.Split("|")
$string_temp = $target_row_temp.GetRange(0,2)
$target_columns.Add($string_temp) | Out-Null
$target_row_temp.RemoveRange(0,2)
$target_range.Add($target_row_temp) | Out-Null
}
$startCell = ws.Cells.Item(11,2)
$endCell = $ws.Cells.Item(10 + $excelHigh,3)
$ws.Range($startCell,$endCell).Value2 = [System.Array]$target_columns

Adding empty line in powershell script creates errors

I have just encountered a very weird error: whenever I just add an empty line in a ps1 file which is otherwise working really fine, my script generates errors.
Here is the setup:
Because I had dependencies issues, I now have an Includes.ps1 file with that content:
$ScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
. ("$ScriptDirectory\HelperFunctions.ps1")
. ("$ScriptDirectory\BuildParameters.ps1")
. ("$ScriptDirectory\Platform.ps1")
. ("$ScriptDirectory\Configuration.ps1")
. ("$ScriptDirectory\Action.ps1")
. ("$ScriptDirectory\Backup.ps1")
I have a Package.ps1 file which includes that file, and does the stuff of instanciating the needed classes and make them work together:
$ScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
. ("$ScriptDirectory\Includes.ps1")
Clear-Host
$Parameters = New-Object -TypeName "BuildParameters"
$user_variables_path = "./UserVariables.ps1"
if ( Test-Path $user_variables_path )
{
. $user_variables_path
}
$Parameters.ValidateParameters()
$PlatformClass = $PlatformFactory.MakePlatform( $Parameters.Platform )
$PlatformClass.ValidateParameters( $Parameters )
$ConfigurationClass = $ConfigurationFactory.MakeConfiguration( $Parameters.Configuration )
$ConfigurationClass.ValidateParameters( $Parameters )
$ActionClass = $ActionsFactory.MakeAction( $Parameters.Action, $PlatformClass, $ConfigurationClass, $Parameters )
$ActionClass.ValidateParameters()
$Backup = [ Backup ]::new( $Parameters, $PlatformClass )
$Backup.ValidateParameters();
$ActionClass.Execute()
if ( $Parameters.BackupVersion )
{
$Backup.BackupVersion()
}
Here is the Platforms.ps1 file which gives me errors when I edit it:
class Platform
{
[Boolean] $CanBePatched
[Boolean] $CanCompressData
Platform()
{
$this.CanBePatched = $false
$this.CanCompressData = $true
}
[void] ValidateParameters( [BuildParameters] $Parameters )
{
}
}
class PlatformWin64 : Platform
{
PlatformWin64()
{
}
}
class PlatformXboxOne : Platform
{
PlatformXboxOne()
{
}
}
class PlatformSwitch : Platform
{
PlatformSwitch()
{
$this.CanBePatched = $true
}
[void] ValidateParameters( [BuildParameters] $Parameters )
{
if ( [string]::IsNullOrEmpty( $Parameters.Region ) )
{
WriteErrorAndExit( "You need to specify a region for the PS4" )
}
}
}
class PlatformPS4 : Platform
{
PlatformPS4()
{
$this.CanBePatched = $true
$this.CanCompressData = $false
}
[void] ValidateParameters( [BuildParameters] $Parameters )
{
if ( [string]::IsNullOrEmpty( $Parameters.Region ) )
{
WriteErrorAndExit( "You need to specify a region for the PS4" )
}
}
}
class PlatformFactory
{
[Platform] MakePlatform( [String] $name )
{
return (New-Object -TypeName "Platform$name")
}
}
$PlatformFactory = [PlatformFactory]::new()
When I change the contents of that file, even by adding empty lines, running the script gives me those errors:
Cannot convert argument "Platform", with value: "PlatformWin64", for
"MakeAction" to type "Platform": "Cannot convert the "PlatformWin64" value
of type "PlatformWin64" to type "Platform"."
At F:\Projects\RWC\BuildScripts\Utils\Package.ps1:55 char:1
+ $ActionClass = $ActionsFactory.MakeAction( $Parameters.Action, $Platf ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
You cannot call a method on a null-valued expression.
At F:\Projects\RWC\BuildScripts\Utils\Package.ps1:56 char:1
+ $ActionClass.ValidateParameters()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Cannot convert argument "Platform", with value: "PlatformWin64", for
".ctor" to type "Platform": "Cannot convert the "PlatformWin64" value of
type "PlatformWin64" to type "Platform"."
At F:\Projects\RWC\BuildScripts\Utils\Package.ps1:58 char:1
+ $Backup = [ Backup ]::new( $Parameters, $PlatformClass )
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
You cannot call a method on a null-valued expression.
At F:\Projects\RWC\BuildScripts\Utils\Package.ps1:59 char:1
+ $Backup.ValidateParameters();
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At F:\Projects\RWC\BuildScripts\Utils\Package.ps1:61 char:1
+ $ActionClass.Execute()
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At F:\Projects\RWC\BuildScripts\Utils\Package.ps1:65 char:5
+ $Backup.BackupVersion()
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Well it turns out I had to close the powershell command line and run it again to have my modifications not generate any errors.
That post helped me find the cause...

error "You cannot call a method on a null-valued expression" when selecting option from drop down list after logging into weblink using IE

I am trying to automate the IE link where I am logging into the webpage and selecting some dropdown option on that. I am able to login to the link but not able to select the option from dropdown.
while ($ie.Busy -eq $true -or $ie.Document -eq $null ){Start-Sleep -seconds 1;}
$dropDown = $ie.Document.getElementById("state-area").contentDocument.getElementById("state-status")[1].selected = $true
Write-Host("Trying to select the dropdown")
$dropDown = $ie.Document.getElementById("state-area").contentDocument.getElementById("state-status").FireEvent("Ready")
Output:
You cannot call a method on a null-valued expression.
At C:\Documents\TestScript4.ps1:51 char:13
+ $dropDown = $ie.Document.getElementById("state-area").contentDocument.getElement ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Trying to select the dropdown
You cannot call a method on a null-valued expression.
At C:\Documents\TestScript4.ps1:59 char:1
+ $dropDown = $ie.Document.getElementById("state-area").contentDocument.getElement ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

connecting to sharepoint oniline using Powershell : Cannot find an appropriate constructor for type Microsoft.SharePoint.Client.ClientContext

Hi I am trying to connect to sharepoint online and publish calender using the data from a SQL Table and I am getting the following exception , please advise.The same code works fine with slight modification on a on prem sharepoint server I have added sharepointonline for the authentication but it is failing with the error.
[System.Reflection.Assembly]::LoadFile ("C:\MOSSLibrary\Microsoft.SharePoint.Client.dll") | Out-Null
[System.Reflection.Assembly]::LoadFile("C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
$username = "XXXXXX"
$url = "XXXXXX"
$pass= cat C:\text.txt | ConvertTo-SecureString
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username,$Pass)
$Context.Credentials = $Creds
$web = $Context.Web
$Context.Load($web)
$Context.Load($splist)
$splist = $Context.web.Lists.GetByTitle("XXXX")
$ItemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
####Some Data coming from SQL Server DB into $table########
$table = $result.Tables[0];
foreach ($row in $table)
{
Write-Host $row.Item("changetitle") $row.Item("status");
$Item1 = $splist.AddItem($ItemCreateInfo)
$Item1["Title"] = "test"
Write-host $date
$Item1.Update()
$Context.ExecuteQuery()
}
Exception
New-Object : A constructor was not found. Cannot find an appropriate
constructor for type Microsoft.SharePoint.Client.ClientContext. At
C:\MOSSLibrary\testingpublish.ps1:15 char:12 + $Context = New-Object
Microsoft.SharePoint.Client.ClientContext($site ... +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
The property 'Credentials' cannot be found on this object. Verify
that the property exists and can be set. At
C:\MOSSLibrary\testingpublish.ps1:17 char:1 + $Context.Credentials =
$Creds + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:20 char:1 + $Context.Load($web) +
~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:21 char:1 + $Context.Load($splist)
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:22 char:1 + $splist =
$Context.web.Lists.GetByTitle("XXXXXXX") +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
It seems Assemblies are not loading correctly.
[System.Reflection.Assembly]::LoadFile ("C:\MOSSLibrary\Microsoft.SharePoint.Client.dll") | Out-Null
[System.Reflection.Assembly]::LoadFile("C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
Instead of above, try following
Add-Type -Path "C:\MOSSLibrary\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll"
PS: Make sure that C:\MOSSLibrary\ contains following two .dll's
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll