Powershell v3 Instantiate classes - powershell

I've tried two ways to instantiate a class in Powershell v3:
$regex = New-Object -Type System.Text.RegularExpressions.Regex -ArgumentList '\/\/.*' | Get-Member
$regex::Replace("//hey", "")
And:
$netregex = [regex]::new('\/\/.*') | Get-Member
$nosingleline = $netregex::Replace("//hey", '')
The first way yields this:
Unable to cast object of type 'System.Object[]' to type 'System.Type'.
At line:2 char:1
$regex::Replace("//hey", "")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : OperationStopped: (:) [], InvalidCastException
FullyQualifiedErrorId : System.InvalidCastException
The second way yields this:
Method invocation failed because
[System.Text.RegularExpressions.Regex] doesn't contain a method named
'new'. At line:4 char:1
$netregex = [regex]::new('//.*') | Get-Member
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : MethodNotFound

Remove | Get-Member from both commands. It is changing the ultimate object type being output on those lines.
Also use . to access the method:
$netregex = [regex]::new('\/\/.*')
$nosingleline = $netregex.Replace("//hey", '')
$regex = New-Object -Type System.Text.RegularExpressions.Regex -ArgumentList '\/\/.*'
$regex.Replace("//hey", "")

Related

Error while execution powershell code on System Center Virtual Machine Manager

I'm facing an issue of getting all vms configuration ( using Get-ScVirtualMachine command) into an array from an input file.
The code is this one below
$VmsList = Get-Content C:\VmsList.txt
foreach($vm in $VmsList){
$Result += Get-SCVirtualMachine -Name $vm
}
And I have this error
Method invocation failed because [Microsoft.SystemCenter.VirtualMachineManager.VM] does not contain a method named 'op_Addition'.
At line:3 char:1
$Result += Get-SCVirtualMachine -Name $vm
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [Microsoft.SystemCenter.VirtualMachineManager.VM] does not contain a method named 'op_Addition'.
At line:3 char:1
$Result += Get-SCVirtualMachine -Name $vm
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Get-SCVirtualMachine : Cannot validate argument on parameter 'Name'. The character length (0) of the argument is too short. Specify an argument with a length that
is greater than or equal to "1", and then try the command again.
At line:3 char:39
$Result += Get-SCVirtualMachine -Name $vm
~~~
CategoryInfo : InvalidData: (:) [Get-SCVirtualMachine], ParameterBindingValidationException
FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.GetVMCmdlet
I forgot to declare the array $result = #()
I resolved the issue.

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

Powershell: pass system key as a argument

I want to pass -Unique as parameter for select-string
param(
$y="CAR"
$parameter=""
)
get-childitem -r -i "*.txt"| select-string "TABLE FILE $y" | Select-Object filename,path $parameter
But whenever i try to pass the parameter, i get the following error
powershell : Select-Object : A positional parameter cannot be found that accepts argument '-Unique'.
At line:1 char:1
+ powershell -ExecutionPolicy ByPass -File x.ps1 -parameter '-Unique'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Select-Object :...ment '-Unique'.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
At C:\Users\aravikumar\Downloads\x.ps1:5 char:62
+ ... elect-string "TABLE FILE $y" | Select-Object filename,path $parameter
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Select-Object], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SelectObjectCommand
Also want to pass multiple system key if possible such as -unique -simplesearch -casesensitive
You can't pass a switch as a string parameter like that. You need to use a technique called 'splatting'. See help about_splatting or https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_splatting

Showing error while adding element in List[int] in powershell?

$sumList= New-Object System.Collections.Generic.List[int]
$eventList = New-Object System.Collections.Generic.List[string]
$preSumList= New-Object System.Collections.Generic.List[int]
$threadInitDelay = [int]$commaSplit[++$eventIndex].Split(':')[1].Trim()
$preProcessTime = [int]$commaSplit[++$eventIndex].Split(':')[1].Trim()+[int]$commaSplit[++$eventIndex].Split(':')[1].Trim()+$commaSplit[[int]++$eventIndex].Split(':')[1].Trim()
$respTime = [int]$commaSplit[++$eventIndex].Split(':')[1].Trim();
$index =$eventList.FindIndex({param([string]$s) return $s -like 'hi'})
if($index -eq -1){
$eventList.Add($eventName)
$sumList.Add($threadInitDelay)
$respSumList.Add($respTime)
Getting this error:
Method invocation failed because [System.Int32[]] doesn't contain a method named 'Add'.
At D:\Powercel\PowershellPractice.ps1:151 char:19
+ $sumList.Add <<<< ($threadInitDelay)
+ CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [System.Int32[]] doesn't contain a method named 'Add'.
At D:\Powercel\PowershellPractice.ps1:152 char:23
+ $respSumList.Add <<<< ($respTime)
+ CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [System.Int32[]] doesn't contain a method named 'Add'.
At D:\Powercel\PowershellPractice.ps1:153 char:23
+ $respMaxTime.Add <<<< ($respTime)
+ CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [System.Int32[]] doesn't contain a method named 'Add'.
At D:\Powercel\PowershellPractice.ps1:155 char:19
+ $minTime.Add <<<< ($threadInitDelay)
+ CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Could you please help me out?
A possible scenario is that you were testing and actually casted those variables like the error states. The error is not wrong. Those variables are not the list types that you have in your code. I can almost reproduce this issue:
PS M:\Scripts\Inno\Output> [int[]]$sumlist = 5,5
PS M:\Scripts\Inno\Output> $sumlist.GetType().Fullname
System.Int32[]
PS M:\Scripts\Inno\Output> $sumlist.Add(5)
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
At line:1 char:1
+ $sumlist.Add(5)
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NotSupportedException
PS M:\Scripts\Inno\Output> $sumlist = New-Object System.Collections.Generic.List[int]
While I didn't get the same error as you the point is the type of the variable didn't change even though I tried to recasted it. That is because of property of the variable explained in this answer by PetSerAl. Have a look at the command Get-Variable sumlist | ft Name,Attributes and you should see System.Management.Automation.ArgumentTypeConverterAttribute. Removing the variable and starting again I get your expected behavior.
PS M:\Scripts\Inno\Output> Remove-Variable sumlist
PS M:\Scripts\Inno\Output> $sumlist = New-Object System.Collections.Generic.List[int]
PS M:\Scripts\Inno\Output> $sumlist.Add(5)
PS M:\Scripts\Inno\Output> $sumlist.GetType().FullName
System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

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