powershellpowershell-4.0powershell-5.0

Powershell Set-Item returns Object reference not set to an object of an instance


I'm running the following commands in a script:

$currentSite = Get-Item IIS:\Sites\$WebSiteName
$currentSite.id = $WebSiteID
$currentSite | Set-Item

where I want to set the id for a website. This script works on some environments and doesn't on others (looking for what's different hoping to post it soon).

Where it doesn't work it returns the following error:

Set-Item : Object reference not set to an instance of an object.
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-Item], NullReferenceException
    + FullyQualifiedErrorId : path,Microsoft.PowerShell.Commands.SetItemCommand

So, looking for a workaround I tried the following code:

$currentSite = Get-Item IIS:\Sites\$WebSiteName
$currentSite | Set-Item

But I get the same error.

So I wonder if there are some parameters that the Set-Item needs but the Get-Item doesn't return when it works with Sites (I specified sites because I'm using the same structure setting an Application pool and I don't get any problem)


Solution

  • Even if this doesn't answer the question, I found a workaround for the problem:

    Instead of use

    $currentSite = Get-Item IIS:\Sites\$WebSiteName
    $currentSite.id = $WebSiteID
    $currentSite | Set-Item
    

    for setting the id for a WebSite can be used the following command:

    Set-ItemProperty -Path IIS:\Sites\$WebSiteName -Name id -Value $WebSiteID