Fixing Powershell Params “The input to an assignment operator must be an object that is able to accept assignments”

Problem: The input to an assignment operator must be an object that is able to accept assignments

Write-Host "Ahoy hoy!"
param(
    [Parameter(Mandatory=$true)][string]$path,
    [Parameter(Mandatory=$true)][string]$environment="example" # error here
)

Solution: You’ve got a problem with your params. In my case I had a statement before declaring the params section. Params should be at the start of the file, or at the start of a function.

param(
    [Parameter(Mandatory=$true)][string]$path,
    [Parameter(Mandatory=$true)][string]$environment="example" # error here
)
Write-Host "Ahoy hoy!"

More information:

Wrapping using statement with dispose in powershell

Today I’m working with zip archives for lambda functions. I needed to take the zip file and add deployment configuration. Lambdas are currently packaged up with their configuration so I need to inject in a file into the zip.

It’s relatively trivial to work with compressed zip files in Powershell, however you need to dispose the handle when you’ve finished with it.

[System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")
$disposeMe = [System.IO.Compression.ZipFile]::Open($path, "Update");
# ...
$disposeMe.dispose();

A using statement is really just a try catch that calls dispose if the object isn’t null. Dave Wyatt’s Using-Object: PowerShell version of C#’s “using” statement post has a good example function of where this is all taken care of and uses a $ScriptBlock to execute it.

So instead of manually calling dispose, we can now write a using lookalike, and the handle will be disposed for us. Lovely!

Using-Object ($zip = [System.IO.Compression.ZipFile]::Open($path, "Update")) {
    # ... 
}

If you don’t want to add the function, you can always just wrap a try catch around it.

try { $disposeMe = [System.IO.Compression.ZipFile]::Open($path, "Update"); }
finally
{
  if ($null -ne $disposeMe -and $disposeMe -is [System.IDisposable]) { $disposeMe.Dispose() }
}