Not able to initialize Namespace Manager in Powershell - powershell

When I am initializing the Namespace manager, I am getting an error message that the constructor was not found.
I am trying to run $XmlNSManager = New-Object System.Xml.XmlNamespaceManager -ArgumentList $xml.NameTable and received below error:
New-Object : A constructor was not found. Cannot find an appropriate constructor for type System.Xml.XmlNamespaceManager.
At line:1 char:17
+ ... NSManager = New-Object System.Xml.XmlNamespaceManager -ArgumentList $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
$XmlNSManager = New-Object System.Xml.XmlNamespaceManager -ArgumentList $xml.NameTable

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 load multiple DLL in PowerShell and invoke a function?

This is my PowerShell script where I am loading the assembly and invoking a function from one of the assemblies.
$dllpath1 = "D:\Adhoc_Testing\AdhocDataServices\AdhocDataServices\bin\AdhocDataServices.dll"
$dllpath2 = "D:\Adhoc_Testing\QueryExpressDataServices\QueryExpressDataServices\bin\Microsoft.IdentityModel.Tokens.dll"
$dllpath3 = "D:\Adhoc_Testing\QueryExpressDataServices\QueryExpressDataServices\bin\System.IdentityModel.Tokens.Jwt.dll"
$lib3 = [Reflection.Assembly]::LoadFile("$dllpath3")
$lib2 = [Reflection.Assembly]::LoadFile("$dllpath2")
$lib1 = [Reflection.Assembly]::LoadFile("$dllpath1")
$obj = New-Object "AdhocDataServices.Controllers.TokenController"
$result = $obj.Fact()
Write-Host $result
Read-Host -Prompt “Press Enter to exit”
I'm getting below error.
New-Object : Cannot find type
[AdhocDataServices.Controllers.TokenController]: verify that the
assembly containing this type is loaded. At line:1 char:8 + $obj =
New-Object AdhocDataServices.Controllers.TokenController +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +
CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException +
FullyQualifiedErrorId :
TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

Object reference not set to an instance of an object. Error when running command Get-AzureRmRecoveryServicesAsrRecoveryPlan

Object reference not set to an instance of an object.
Error when running command Get-AzureRmRecoveryServicesAsrRecoveryPlan...
PS C:\WINDOWS\system32> $rpname = "myrecoveryplan"
$recoplan = Get-AzureRmRecoveryServicesAsrRecoveryPlan -Name $rpname
Get-AzureRmRecoveryServicesAsrRecoveryPlan : Operation failed.
Object reference not set to an instance of an object.
At line:2 char:13
+ $recoplan = Get-AzureRmRecoveryServicesAsrRecoveryPlan -Name $rpname
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureRmReco...AsrRecoveryPlan], Exception
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.GetAzureRmRecoveryS
ervicesAsrRecoveryPlan
I have updated My powershell and it seems moving on. But I got another blocker. $Context= Set-AzureRmRecoveryServicesAsrVaultContext -Vault $Vault
$recoplan = Get-AzureRmRecoveryServicesAsrRecoveryPlan -Name $rpname
Start-AzureRmSiteRecoveryTestFailoverJob -RecoveryPlan $recoplan -Direction "PrimaryToRecovery" -VMNetwork "asrtestfailtarget"
Start-AzureRmSiteRecoveryTestFailoverJob : Cannot bind parameter 'RecoveryPlan'. Cannot convert the
"Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.ASRRecoveryPlan" value of type
"Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.ASRRecoveryPlan" to type
"Microsoft.Azure.Commands.SiteRecovery.ASRRecoveryPlan".
At line:5 char:56
+ ... rt-AzureRmSiteRecoveryTestFailoverJob -RecoveryPlan $recoplan -Direct ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-AzureRmSiteRecoveryTestFailoverJob], Parameter
BindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Azure.Commands.SiteRecovery.Start
AzureRmSiteRecoveryTestFailoverJob

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

properties wrong in 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