Issue with System.Windows.Forms.ListViewItem / NullReferenceException - powershell

I am getting the following error when I try to get a Listview of Applications in Powershell
Exception calling "Add" with "1" argument(s): "Object reference not set to an instance of an object."
At D:\scripts\AWSA.ps1:527 char:79
+ ... ?{$_.Index -ne 0})){$Field = $Col.Text;$Item.SubItems.Add($_.$Field)}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NullReferenceException
The code that is rendering the result is
...
$btnApplications = New-Object System.Windows.Forms.Button
$lvMain = New-Object System.Windows.Forms.ListView
...
$btnApplications_Click={
Get-ComputerName
Initialize-Listview
$SBPStatus.Text = "Retrieving Applications..."
Update-ContextMenu (Get-Variable cmsApp*)
$XML.Options.Applications.Property | %{Add-Column $_}
Resize-Columns
$Col0 = $lvMain.Columns[0].Text
$Info = Get-WmiObject win32_Product -ComputerName $ComputerName -ErrorVariable SysError | Sort Name,Vendor
Start-Sleep -m 250
if($SysError){$SBPStatus.Text = "[$ComputerName] $SysError"}
else{
$Info | %{
$Item = New-Object System.Windows.Forms.ListViewItem($_.$Col0)
ForEach ($Col in ($lvMain.Columns | ?{$_.Index -ne 0})){$Field = $Col.Text;$Item.SubItems.Add($_.$Field)}
$lvMain.Items.Add($Item)
}
$SBPStatus.Text = "Ready"
}
}
Do I need to add a null variable such as if($SubItem -ne $null){$Item.SubItems.Add($SubItem)} ?

Related

Getting error when connecting two Azure Analysis Services from child scripts

I am working on PowerShell scripts. I have two scripts in those scripts I am connecting with two Azure Analysis Servers one by one. And these scripts are calling by the main script. I am getting errors
"Exception calling "Connect" with "1" argument(s): "Object reference not set to an instance of an object."
My Scripts code is below
Child1.ps1
param(
[String]
$envName1,
[String]
$toBeDisconnect1
)
$loadInfo1 = [Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")
$server1 = New-Object Microsoft.AnalysisServices.Server
if($toBeDisconnect1 -eq "No")
{
$server1.Connect($envName1)
return $server1
}
elseif($toBeDisconnect1 -eq "Yes")
{
$server1.Disconnect()
Write-Host $server1 " has been disconnected."
}
Child2.ps1
param(
[String]
$envName1,
[String]
$toBeDisconnect1
)
$loadInfo1 = [Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")
$server1 = New-Object Microsoft.AnalysisServices.Server
if($toBeDisconnect1 -eq "No")
{
$server1.Connect($envName1)
return $server1
}
elseif($toBeDisconnect1 -eq "Yes")
{
$server1.Disconnect()
Write-Host $server1 " has been disconnected."
}
MainParent.ps1
param(
$filePath = "C:\Users\user1\Desktop\DBList.txt"
)
$command = "C:\Users\User1\Desktop\test1.ps1 –envName1
asazure://aspaaseastus2.asazure.windows.net/mydevaas -toBeDisconnect1 No"
$Obj1 = Invoke-Expression $command
Start-Sleep -Seconds 15
$command1 = "C:\Users\User1\Desktop\test2.ps1 –envName2
asazure://aspaaseastus2.asazure.windows.net/myuataas -toBeDisconnect2 No"
$Obj2 = Invoke-Expression $command1
Error is below in MainParent.ps1
Exception calling "Connect" with "1" argument(s): "Object reference not set to an instance of an
object."
At C:\Users\User1\Desktop\test1.ps1:13 char:5
+ $server1.Connect($envName1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NullReferenceException
Exception calling "Connect" with "1" argument(s): "Object reference not set to an instance of an
object."
At C:\Users\User1\Desktop\test2.ps1:13 char:5
+ $server2.Connect($envName2)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NullReferenceException
My AzureAnalysis Services dll version is 13.0.4495.10. I am sharing this info, may be it can be a issue.
It seems Invoke-Expression is not passing the param envName1. I would rather call the child script normally like below:
$Obj1 = &"C:\Users\User1\Desktop\test1.ps1" -envName1 "asazure://aspaaseastus2.asazure.windows.net/mydevaas" -toBeDisconnect1 No | select -Last 1
$Obj2 = &"C:\Users\User1\Desktop\test2.ps1" -envName2 "asazure://aspaaseastus2.asazure.windows.net/myuataas" -toBeDisconnect2 No | select -Last 1
$command = "C:\Users\User1\Desktop\test1.ps1 –envName1 asazure://aspaaseastus2.asazure.windows.net/mydevaas -toBeDisconnect1 No"
Look closely at the hyphen before envName1. It's actually – (en-dash) instead of - (hyphen). That's the reason envName1 is not being passed. The second param toBeDisconnect1 has it correct.
How to know the difference? - (hyphen) is shorter than – (en-dash) :)

Upload file to SharePoint

I would like to create a program in PowerShell to upload files to Sharepoint on schedule (using Task Scheduler)
I was looking for solution and I found this interesting article.
Based on this I wrote this script below:
Import-Module Microsoft.Online.Sharepoint.Powershell -DisableNameChecking;
(System.Reflection.Assembly)::LoadWithPartialName("System.IO.MemoryStream")
Clear-Host
$cred = Get-Credential "emailaddress#domain.com"
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($cred.Username, $cred.Password)
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext("https://")
$clientCOntext.Credentials = $credentials
if (!$clientContext.ServerObjectIsNull.Value) {Write-host "Connected to site" -ForegroundColor Green}
Function UploadFileToLibrary(){
$docLib - $clientContext.Web.Lists.GetByTitle("IT Documents");
$clientContext.Load($docLib);
$clientContext.ExecuteQuery();
$rootFolder = $docLib.RootFolder
$Folder = "\\10.x.x.x\xpbuild$\IT\Level0\scresult\Upload";
$FilesInRoot = Get-ChildItem - Path $Folder | ? {$_.psIsContainer -eq $False}
Foreach ($File in ($FilesInRoot))
{
$startDTM = (Get-Date)
}Write-Host "Uploading File" $File.Name "to" $docLib.Title -ForegroundColor Blue
UploadFile $rootFolder $File $false
$endDTM = (Get-Date)
Write-Host "Total Elapsed Time : $(($endDTM-$startDTM).totalseconds) seconds"
}
Function UploadFile ($SPListFolder, $File, $CheckInRequired){
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $True
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.Url = $File
$UploadedFile = $SPListFolder.Files.Add($FileCreationInfo)
If($CheckInRequired){
$clientContext.Load($UploadedFile)
$clientContext.ExecuteQuery()
If($uploadedFile.CheckOutType -ne "none"){
$UploadedFile.CheckIn("Checked in by Administrator", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
}
}
$clientContext.Load($UploadedFile)
$clientContext.ExecuteQuery()
}
UploadFileToLibrary
When I tried to execute this I see that connection is active but I got an error:
Method invocation failed because [Microsoft.SharePoint.Client.List] does not contain a method named 'op_Subtraction'.
At C:\PowerShell\UploadSharepoint.ps1:11 char:1
+ $docLib - $clientContext.Web.Lists.GetByTitle("IT Documents");
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Subtraction:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Cannot find an overload for "Load" and the argument count: "1".
At C:\PowerShell\UploadSharepoint.ps1:12 char:1
+ $clientContext.Load($docLib);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Exception calling "ExecuteQuery" with "0" argument(s): "List 'IT Documents' does not exist at site with URL 'https://'."
At C:\PowerShell\UploadSharepoint.ps1:13 char:1
+ $clientContext.ExecuteQuery();
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ServerException
I cannot tell if any new problem occur once you fix that one, but given that the 2nd and 3rd error is caused by incorrect assignment of $docLib variable, changing - to =should resolve these three:
HERE |
$docLib = $clientContext.Web.Lists.GetByTitle("IT Documents");
# Below uses $docLib so it cannot be executed properly unless $docLib is assigned correct value
$clientContext.Load($docLib);
# And below fails as the above is not executed successfully
$clientContext.ExecuteQuery();

Adding multiple users to AD

This script was working just fine today while testing. I made a few changes and started getting an error. I then went back to the very original script I got from the internet and now even it does not work. The errors are:
Exception calling "SetInfo" with "0" argument(s): "A constraint violation
occurred."
At C:\Scripts\CreateTest2.ps1:51 char:2
+ $LABUser.SetInfo()
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
Exception calling "Invoke" with "2" argument(s): "There is no such object on the
server."
At C:\Scripts\CreateTest2.ps1:55 char:2
+ $LABUser.psbase.invoke("setPassword", $Pwrd)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodTargetInvocation
Exception calling "InvokeSet" with "2" argument(s): "The directory property
cannot be found in the cache"
At C:\Scripts\CreateTest2.ps1:56 char:2
+ $LABUser.psbase.invokeSet("AccountDisabled", $false)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodTargetInvocation
Exception calling "CommitChanges" with "0" argument(s): "A constraint violation
occurred."
At C:\Scripts\CreateTest2.ps1:57 char:2
+ $LABUser.psbase.CommitChanges()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Here is the script. What am I doing wrong?
function Select-FileDialog {
param(
[string]$Title,
[string]$Directory,
[string]$Filter = "CSV Files(*.csv)|*.csv"
)
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$objForm = New-Object System.Windows.Forms.OpenFileDialog
$objForm.InitialDirectory = $Directory
$objForm.Filter = $Filter
$objForm.Title = $Title
$objForm.ShowHelp = $true
$Show = $objForm.ShowDialog()
if ($Show -eq "OK") {
return $objForm.FileName
} else {
exit
}
}
$FileName = Select-FileDialog -Title "Import an CSV file" -Directory "c:\"
$SelectOU = "OU=Test2,OU=Users,OU=Domain Controllers"
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()
$DomainDN = (([System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()).Domains | ? {$_.Name -eq $domain}).GetDirectoryEntry().distinguishedName
$final = "LDAP://$DomainDN"
$DomainPath = [ADSI]"$final"
$UserInformation = Import-Csv $FileName
$OUPath = "LDAP://$SelectOU,$DomainDN"
$UserPath = [ADSI]"$OUPath"
foreach ($User in $UserInformation) {
$CN = $User.samAccountName
$SN = $User.Surname
$Given = $User.givenName
$samAccountName = $User.samAccountName
$Display = $User.DisplayName
$LABUser = $UserPath.Create("User", "CN=$CN")
Write-Host "Please Wait..."
$LABUser.Put("samAccountName", $samAccountName)
$LABUser.Put("sn", $SN)
$LABUser.Put("givenName", $Given)
$LABUser.Put("displayName", $Display)
$LABUser.Put("userPrincipalName", "$samAccountName#$domain")
$LABUser.SetInfo()
$Pwrd = $User.Password
$LABUser.psbase.invoke("setPassword", $Pwrd)
$LABUser.psbase.invokeSet("AccountDisabled", $false)
$LABUser.psbase.CommitChanges()
}
Write-Host "Script Completed"
Can you please try Removing the Quotes from
1) LABUser assignment i.e. CN = $CN.
2) Remove the CN = from that line.
Try it one by one i hope you get your answer.

Run remote PowerShell Office uninstallation script

KB2956128 is causing headache for users in my network. I do not run WSUS in this environment so I was going to employ PS script to take care of uninstallation.
By all means the script below should work
$comp = 'PC03'
$scrblock =
{
$TitlePattern = 'KB2956128'
$Session = New-Object -ComObject Microsoft.Update.Session
$Collection = New-Object -ComObject Microsoft.Update.UpdateColl
$Installer = $Session.CreateUpdateInstaller()
$Searcher = $Session.CreateUpdateSearcher()
$Searcher.QueryHistory(0, $Searcher.GetTotalHistoryCount()) |
Where-Object { $_.Title -match $TitlePattern } |
ForEach-Object {
Write-Verbose "Found update history entry $($_.Title)"
$SearchResult = $Searcher.Search("UpdateID='$($_.UpdateIdentity.UpdateID)' and RevisionNumber=$($_.UpdateIdentity.RevisionNumber)")
Write-Verbose "Found $($SearchResult.Updates.Count) update entries"
if ($SearchResult.Updates.Count -gt 0) {
$Installer.Updates = $SearchResult.Updates
$Installer.Uninstall()
$Installer | Select-Object -Property ResultCode, RebootRequired, Exception
# result codes: http://technet.microsoft.com/en-us/library/cc720442(WS.10).aspx
}
}
}
Invoke-Command -ComputerName $comp -ScriptBlock $scrblock -Credential 'myDomain\administrator'
Instead I get this error
Exception calling "CreateUpdateInstaller" with "0" argument(s): "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : PC03
Exception calling "QueryHistory" with "2" argument(s): "Exception from HRESULT: 0x80240007"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : PC03
I don't quite understand why the access is denied. Any ideas?
Short answer is that the ComObject does not allow the CreateUpdateInstaller to be called remotely. You can only do this locally, not over sessions or any other remoting. You can however use psexec to remotely execute your script as system.

Error when trying to do a search with Powershell towards LDAP

The above gives:
PS C:\EndurAutomation\powershell\bin> C:\EndurAutomation\powershell\bin\ets_update_constring.ps1
Exception calling "FindAll" with "0" argument(s): "An operations error occurred.
"
At C:\EndurAutomation\powershell\bin\ets_update_constring.ps1:20 char:30
+ $result = $ldapSearch.FindAll <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
$ldapDN = "dc=<masked>,dc=<masked>"
$ldapURI = "ldap://<masked>/$ldapDN"
$env = "sqlplus -S <masked> ``#env.sql > env.list"
Invoke-Expression $env
$envData = (Get-Content "env.list")
$envFilter = "(|"
foreach ($env in $envData) {
$envFilter += "(cn=$env)"
}
$envFilter += ")"
$ldapEntry = New-Object System.DirectoryServices.DirectoryEntry($ldapUR, $null, $null, [System.DirectoryServices.AuthenticationTypes]::Anonymous)
$ldapSearch = New-Object System.DirectoryServices.DirectorySearcher($ldapEntry)
$ldapSearch.PageSize = 1000
$ldapSearch.Filter = $envFilter
$result = $ldapSearch.FindAll($envFilter)
You already set $ldapSearch.Filter = $envFilter so you don't need to call FindAll by passing in the filter again. Try doing this instead as your very last line of code, as it will still have your filter built into it:
$result = $ldapSearch.FindAll()
I think it's a typo:
$ldapEntry = New-Object System.DirectoryServices.DirectoryEntry(
**$ldapUR**, $null, $null,
[System.DirectoryServices.AuthenticationTypes]::Anonymous
)
Try
$ldapURI
instead of
$ldapUR