Powershell集合项返回未设置为实例对象的对象引用

Powershell集合项返回未设置为实例对象的对象引用,powershell,powershell-4.0,powershell-5.0,Powershell,Powershell 4.0,Powershell 5.0,我正在脚本中运行以下命令: $currentSite = Get-Item IIS:\Sites\$WebSiteName $currentSite.id = $WebSiteID $currentSite | Set-Item 我想为网站设置id的位置。 此脚本适用于某些环境,而不适用于其他环境(寻找不同之处,希望尽快发布) 如果不起作用,则返回以下错误: Set-Item : Object reference not set to an instance of an object.

我正在脚本中运行以下命令:

$currentSite = Get-Item IIS:\Sites\$WebSiteName
$currentSite.id = $WebSiteID
$currentSite | Set-Item
我想为网站设置id的位置。 此脚本适用于某些环境,而不适用于其他环境(寻找不同之处,希望尽快发布)

如果不起作用,则返回以下错误:

Set-Item : Object reference not set to an instance of an object.
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-Item], NullReferenceException
    + FullyQualifiedErrorId : path,Microsoft.PowerShell.Commands.SetItemCommand
因此,为了寻找解决方法,我尝试了以下代码:

$currentSite = Get-Item IIS:\Sites\$WebSiteName
$currentSite | Set-Item
但我也犯了同样的错误


因此,我想知道Set项是否需要一些参数,但Get项在与站点一起工作时不会返回(我指定了站点,因为我使用相同的结构设置应用程序池,并且没有任何问题)

即使这没有回答问题,我也找到了解决问题的方法:

代替使用

$currentSite = Get-Item IIS:\Sites\$WebSiteName
$currentSite.id = $WebSiteID
$currentSite | Set-Item
可使用以下命令设置网站id:

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

当您得到错误时,
$currentSite | gm
返回什么?
TypeName:System.Object
您也需要该列表吗?在调用
设置项之前,如果($currentSite-ne$null){Write Host currentSite不是null!}
请尝试
如果($currentSite-ne$null){Write Host currentSite NOT null!}
。从错误中可以看出,
path
为空,或者如果不为空,则表示它不指向任何地方。因此,您应该尝试使用其他
Set Item
语法,例如:
Set Item-path IIS:\Sites\$WebSiteName-value$currentSite