positional parameter cannot be found that accepts argument - powershell

if ($mbcb1.Checked -eq $true) {$dgr = "-AutoStart"}
if ($mbcb2.Checked -eq $true) {$dgrc = "-AutoComplete"}
if ($mbcb3.Checked -eq $true) {$dgren = "-NotificationEmails"}
New-MigrationBatch -Name $mbnd -SourceEndpoint $mbcx -TargetDeliveryDomain $mbtdd -CSVData ([System.IO.File]::ReadAllBytes("$cmbcsvfile")) $dgr $dgrc $dgren admin#admin.com
Error :
A positional parameter cannot be found that accepts argument '-Autostart'.
+ CategoryInfo : InvalidArgument: (:) [New-MigrationBatch], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,New-MigrationBatch
+ PSComputerName : ps.outlook.com
if i given direct input its working but passing as variable throwing error.

If you want to optionally specify parameters, use splatting:
$OptionalParameters = #{
AutoStart = $mbcb1.Checked
AutoComplete = $mbcb2.Checked
}
if ($mbcb3.Checked) {
$OptionalParameters["NotificationEmails"] = 'admin#admin.com'
}
New-MigrationBatch -Name $mbnd -SourceEndpoint $mbcx -TargetDeliveryDomain $mbtdd -CSVData ([System.IO.File]::ReadAllBytes("$cmbcsvfile")) #OptionalParameters
We simply build a hashtable with the parameter names and their arguments, and then supply it to the cmdlet as an argument (but like #name instead of $name), and then the parser will turn each entry in the hashtable into a named parameter in the form -key:value.
Finally, the $mbcb3.Checked -eq $true comparison is redundant, since Checked (assuming that $mbcb3 is a checkbox) is already either $true or $false
See the about_Splatting help file for more details about parameter splatting

Related

How to return an Object from a loaded .dll file in powershell

I'm trying to use a Powershell-script to build a connection with Microsoft Dynamics CRM.
In some others scripts I want to use this connection.
If I export the connection-object, I can't use it as connection-object.
I return the object with:
[Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy] $connection = New-Object Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy($organizationUri,$null,$clientCredentials,$null)
[Microsoft.Xrm.Sdk.Entity] $systemUser = $connection.Retrieve("systemuser", $userId, (New-Object Microsoft.Xrm.Sdk.Query.ColumnSet(#("firstname", "lastname"))))
return $connection
And this is, how I call the script above:
[Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy]$connection = (New-CRMConnection -server $connectionjson.server -organization $connectionjson.organization -domain $connectionjson.domain -user $connectionjson.username -password $connectionjson.password)
But I get this error (I translated it from german, so it's not the exact error-message):
The value "System.Object[]" from type "System.Object[]" cannot be converted to "Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy".
In C:\Users\drieke\Documents\git\SNC-CRM\Solution\Import-CRMSolution.ps1:19 Zeichen:5
+ [Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy]$connection = ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : ConvertToFinalInvalidCastException
How do I correctly return my object?
EDIT
My problem was, that my function returned an array.
The first Object in the array is the object i need.
So my solution is the [1] in following code:
[Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy]$connection = (New-CRMConnection -server $connectionjson.server -organization $connectionjson.organization -domain $connectionjson.domain -user $connectionjson.username -password $connectionjson.password)[1]
The error message means that New-CRMConnection returns an array of objects. Conversion from array into some other non-collection object makes no sense, so Powershell complains.
To debug the scenario, first save New-CRMConnection's return value into a variable and work from there.
$connections = (New-CRMConnection -server $connectionjson.server `
-organization $connectionjson.organization -domain $connectionjson.domain `
-user $connectionjson.username -password $connectionjson.password)
# What kind of object is connections?
$connections.GetType()
# If it was an array, let's see its 1st element
$c = $connections[0]
# What kind of object is the first element?
$c.GetType()
# If it looks sensible, try casting
[Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy]$connection = $c

unable to export from powershell to CSV [duplicate]

This question already has answers here:
Writing console output to a file - file is unexpectedly empty
(2 answers)
Closed 3 years ago.
Pls help a poor newby over here...below is my script with the errors at the bottom of the script. The main issue is that i am unable to export to CSV
PS C:\Users\LUPUWANA> $logs = get-eventlog system -ComputerName cafeserver -source Microsoft-Windows-Winlogon -After (Get-Date).AddDays(-7);
$res = #(); ForEach ($log in $logs) {if($log.instanceid -eq 7001) {$type = "Logon"} Elseif ($log.instanceid -eq 7002){$type="Logoff"} Else {Continue} $res += New-Object PSObject -Property #{Time = $log.TimeWritten; "Event" = $type; User = (New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}};
Export-Csv -Path C:\users\lupuwana\desktop\events.csv
oss get-help -detailed
Supply values for the following parameters:
InputObject:
oss : Cannot process argument transformation on parameter 'Width'. Cannot convert value "get-help" to type "System.Int32". Error: "Input string was not in a
correct format."
At line:4 char:5
+ oss get-help -detailed
+ CategoryInfo : InvalidData: (:) [oss], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,oss
Your loop builds an object called $res, so assuming that's the object you wish to export to CSV, you need to supply that object to the Export-Csv Cmdlet:
Export-Csv -InputObject $res -Path C:\users\lupuwana\desktop\events.csv
You may also wish to add the -NoTypeInformation option too otherwise your file will contain an extra header row describing the object type.

New-Mailbox command does not accept the -Equipment argument

I'm attempting to create new resources in Exchange Online via a script and it works if I type the line manually but when I run the script, the command New-Mailbox suddenly can't accept the "-Equipment" argument.
Script fails on the following row:
New-Mailbox -Name "$($Resource)" -$($Type)
Error shows following:
A positional parameter cannot be found that accepts argument '-Equipment'.
+ CategoryInfo : InvalidArgument: (:) [New-Mailbox], ParameterBindingException"
PowerShell interprets -$($Type) as a string argument rather than a parameter name. Use splatting to conditionally pass parameters like this:
$extraParams = #{ $Type = $true }
New-Mailbox -Name "$($Resource)" #extraParams
I'm not sure which other types of mailboxes are available in Exchange Online, but you'll probably want to figure that out and apply some input validation:
param(
[string]$Resource,
[ValidateSet('Equipment','Person','Room')]
[string]$Type
)
# do other stuff here
# If someone passed a wrong kind of `$Type`, the script would have already thrown an error
$extraParams = #{ $Type = $true }
New-Mailbox -Name "$($Resource)" #extraParams

Dynamically created parameter arguments for PowerShell's Get-ChildItem

Long story short, I'm trying to dynamically use a parameter -Directory or -File in PowerShell's Get-ChildItem. Guess what? I'm unable to.
Here's the deal (note: pseudo-code):
Param(
[string]$filter = $(throw "Error: name"),
[string]$type = $(throw "error: file or directory")
)
if( $type -eq "file" ) {
$mode = '-File'
}
elseif( $type -eq "directory" ) {
$mode = '-Directory'
}
Function Find_Plugin_folder {
Write-Host "look for: '$($filter)'"
Invoke-Command -ComputerName (Get-Content servers.txt ) -ScriptBlock {
(Get-ChildItem -Path "z:\www" -Depth 5 $Using:mode -Filter $Using:filter -Recurse ) | %{$_.FullName}
} -ThrottleLimit 80
}
Find_Plugin_folder
$Using:mode is where it throws an error, either:
PS C:\Users\janreilink> v:\test.ps1 vevida-optimizer file
look for: 'vevida-optimizer'
A positional parameter cannot be found that accepts argument '-File'.
+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
+ PSComputerName : webserver-01.example.net
Or
PS C:\Users\janreilink> v:\test.ps1 vevida-optimizer directory
look for: 'vevida-optimizer'
A positional parameter cannot be found that accepts argument '-Directory'.
+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
+ PSComputerName : webserver-01.example.net
I've been reading about Dynamic Parameter sets all afternoon, but can't wrap my head around it yet. Any points are much (much, much) appreciated.
You'll want to use splatting for this instead. Start by creating a hashtable with some or all of the parameters you want to pass:
$dynamicArgs = #{}
if( $type -eq "file" ) {
$dynamicArgs['File'] = $true
}
elseif( $type -eq "directory" ) {
$dynamicArgs['Directory'] = $true
}
Then, inside Invoke-Command, prefix the variable name with # to indicate that you want to "splat" the arguments:
Get-ChildItem -Path "z:\www" -Depth 5 #Using:dynamicArgs -Filter $Using:filter -Recurse
If the splatting table contains the key File with a value of $true, it's the equivalent of adding -File:$true on the command line, and vice versa for the Directory argument

Powershell Script Error-Cannot validate argument on parameter 'Property': Cannot index into a null array

I have run a Powershell script found within this article: How to detect applications using "hardcoded" DC name or IP.
Get-WinEvent -ComputerName dc01.contoso.com -MaxEvents 1000 -FilterHashtable #{LogName="Directory Service" ; ID=1139 } | ForEach-Object `
{
$_info = #{
"Operation" = [string] $_.Properties.Value[0]
"User" = [string] $_.Properties.Value[2]
"IP:Port" = [string] $_.Properties.Value[3]
}
New-Object psobject -Property $_info
}
The error I receive is:
New-Object : Cannot validate argument on parameter 'Property'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.
At C:\scripts\HideDC.ps1:9 char:37
+ New-Object psobject -Property <<<< $_info
+ CategoryInfo : InvalidData: (:) [New-Object],
ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.NewObjectCommand
Cannot index into a null array.
At C:\scripts\HideDC.ps1:5 char:55
+ "Operation" = [string] $_.Properties.Value[ <<<< 0]
+ CategoryInfo : InvalidOperation: (0:Int32) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Can anyone help with this?
tl;dr:
Get-WinEvent -ComputerName dc01.contoso.com -MaxEvents 1000 -FilterHashtable #{
LogName="Directory Service" ; ID=1139 } |
ForEach-Object {
[pscustomobject] #{
"Operation" = try { [string] $_.Properties.Value[0] } catch {}
"User" = try { [string] $_.Properties.Value[2] } catch {}
"IP:Port" = try { [string] $_.Properties.Value[3] } catch {}
}
}
The Cannot index into a null array error message is telling you that $_.Properties.Value is $null rather than an array, so an attempt to access an element of this non-array fails.[1]
The implication is that at least some of the event-log records do not have embedded data values.
(The New-Object : Cannot validate argument on parameter 'Property' is merely a follow-on error that complains about the -Property argument being $null, because the initial error caused $_info to be $null.)
The simplest solution is to use an embedded try { ... } catch {} handler enclosing the $_.Properties.Value[<n>] references, which quietly ignores the case when $_.Properties.Value is $null and causes the overall subexpression to return $null.
Also note how you can cast the hashtable literal (#{ ... }) directly to type accelerator [pscustomobject] in order to convert it to a custom object.
[1] Note that since PSv3, trying to index into a value that is non-$null but is also not an array doesn't fail, but quietly returns $null; e.g.: $v=20; $v[1] # -> $null.
Indexing into a string value is a special case, however: it returns the character at the specified position: $v='hi'; $v[1] # -> 'i'