Update 1:
Originally, I posted this with the title: "Scripts ignoring error handling in PowerShell module" as that is the current issue, however it seems more of a module issue, so I have renamed the title.
Update 2:
After a comment that made me question Azure cmdlets, I've tested with the most basic of scripts (added to the module) and the findings are the same, in that the error is not passed to the calling script, however, adding -errorVariable to Get-Service does return something (other than WriteErrorException) that I could probably harness in the handling of the error:
function Test-MyError($Variable)
{
Try
{
Get-Service -Name $variable -ErrorAction Stop -ErrorVariable bar
#Get-AzureRmSubscription -SubscriptionName $variable -ErrorAction Stop
}
Catch
{
Write-Error $error[0]
$bar
}
}
returns:
Test-MyError "Foo"
Test-MyError : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:3 char:1
+ Test-MyError "Foo"
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-MyError
The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Cannot find any service with service name 'foo'.
However, if I run "Test-MyError" in ISE, then call the function, I get:
Test-MyError "Foo"
Test-MyError : Cannot find any service with service name 'Foo'.
At line:3 char:1
+ Test-MyError "Foo"
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-MyError
The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Cannot find any service with service name 'Foo'.
So I am not sure what is happening when running "Test-MyError" in ISE and calling it, against it being dot-sourced in the PSM1 file and then calling it?
Do I now have to use -ErrorVariable and handle on that?
Original Question:
I have two functions in a module: Get-Subscription and Get-AllSubscriptions. Each function sits in its own PS1 file and the PSM1 file dot-sources them. The module seems fine as the module scripts are accessible using intelisense and the module loads without issue. I've used this structure in many modules and I haven't come across this problem before. (Although I wonder if MS have changed the way modules work in PS 5.1 as I have noticed using FunctionsToExport='x','y','Z' and Export-ModuleMember don't seem to behave the same way as they used to.)
Get-AllSubscriptions calls Get-Subscription.
If I am not logged into Azure, Get-Subscription should throw an error which is handled, prompting me to log in. This works as expected, if I call Get-Subscription from the Get-Subscription.ps1.
However, when I call Get-Subscription from the a new PS1 file, Get-AllSubscriptions or from the powershell console, it doesn't work. It iterates all the way through the do..until loop, without "handling" the errors as I would expect. On each iteration, it seems to throw a generic error:
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
However, I do see the last error, Get-Subscription : Unable to find requested subscription after 3 login attempts.
If I execute Get-Subscription in ISE, then call Get-Subscription in a new PS1 file or from Get-AllSubscriptions, it works as expected, however, once I re-import the module (Import-Module AzureVnetTools -Force -Verbose), it goes back to the incorrect behaviour.
If I dot-source Get-Subscription, inside the caller script, it works, but why? This is what should happen with the module's PSM1.
Can anyone help me work out what I am doing wrong here?
(PS 5.1, Windows 7)
Get-Subscription:
function Get-Subscription
{
[cmdletbinding()]
Param
(
[string]$SubscriptionName,
[string]$UserName,
[string]$code
)
$c=1
Write-Verbose "Checking access to '$SubscriptionName' with user '$UserName'..."
Do
{
Write-Verbose "Attempt $c"
Try
{
$oSubscription = Get-AzureRmSubscription -SubscriptionName $SubscriptionName -ErrorAction Stop -WarningAction SilentlyContinue
Write-Verbose "Subscription found: $($oSubscription.SubscriptionName)."
}
Catch
{
if($error[0].Exception.Message -like "*Please verify that the subscription exists in this tenant*")
{
Write-Verbose "Cannot find subscription '$SubscriptionName' with provided credentials."
$account = Login-AzureRmAccount -Credential (Get-Credential -UserName $Username -Message "Subscription '$SubscriptionName' user' password:")
}
elseif($error[0].Exception.Message -like "*Run Login-AzureRmAccount to login*")
{
Write-Verbose "No logged in session found. Please log in."
$account = Login-AzureRmAccount -Credential (Get-Credential -UserName $Username -Message "Subscription '$SubscriptionName' user' password:")
}
else
{
Write-Error $error[0]
}
}
$c++
}
until(($oSubscription) -or ($c -eq 4))
if($c -eq 4)
{
Write-Error "Unable to find requested subscription after $($c-1) login attempts."
break
}
$oSubscription | Add-Member -MemberType NoteProperty -Name Code -Value $code
$oSubscription
}
Get-AllSubscriptions:
function Get-AllSubscriptions
{
[cmdletbinding()]
param
(
[string]$MasterSubscription,
[string]$MasterSubscriptionCode,
[string]$MasterSubscriptionUsername,
[string]$ChildSubscription,
[string]$ChildSubscriptionCode,
[string]$ChildSubscriptionUsername
)
Write-Verbose "Getting all subscriptions..."
$oAllSubscriptions = #()
$oMasterSubscription = Get-Subscription -SubscriptionName $MasterSubscription -UserName $MasterSubscriptionUsername -code $MasterSubscriptionCode -Verbose
$oChildSubscription = Get-Subscription -SubscriptionName $ChildSubscription -UserName $ChildSubscriptionUsername -code $ChildSubscriptionCode -Verbose
$oAllSubscriptions = ($oMasterSubscription,$oChildSubscription)
$oAllSubscriptions
}
Test:
$splat2 = #{
SubscriptionName = "SomeSubscription"
Code = "S02"
Username = "some.user#somewhere.com"
}
#Write-Output "Dot-source:"
#. "D:\Temp\PS.Modules\AzureVnetTools\functions\public\Get-Subscription.ps1"
Get-Subscription #splat2 -verbose
Output:
Get-Subscription #splat2 -verbose
VERBOSE: Checking access to 'SomeSubscription' with user 'some.user#somewhere.com'...
VERBOSE: Attempt 1
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:7 char:1
+ Get-Subscription #splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription
VERBOSE: Attempt 2
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:7 char:1
+ Get-Subscription #splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription
VERBOSE: Attempt 3
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:7 char:1
+ Get-Subscription #splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription
Get-Subscription : Unable to find requested subscription after 3 login attempts.
At line:7 char:1
+ Get-Subscription #splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription
AzureVnetTools.psm1
#Get public and private function definition files.
$Public = #( Get-ChildItem -Path $PSScriptRoot\Functions\Public\*.ps1 -ErrorAction SilentlyContinue )
$Private = #( Get-ChildItem -Path $PSScriptRoot\Functions\Private\*.ps1 -ErrorAction SilentlyContinue )
#Dot source the files
Foreach($import in #($Public + $Private))
{
#write-error $import.fullname
Try
{
#Write-Host "Dot-sourcing file: $($import.fullname)."
. $import.fullname
}
Catch
{
Write-Error -Message "Failed to import function $($import.fullname): $_"
}
}
Export-ModuleMember -Function $Public.Basename
AzureVnetTools.psd1 (Relevant section):
FunctionsToExport = '*'
-ErrorAction Stop -WarningAction SilentlyContinue
Is it a warning that's being thrown instead of an error?
So my specific problem was that I was relying on handling the error and doing something based on that. The problem was caused by the way PowerShell's Write-Error works (or not) as I learned from the reply here, given by #Alek.
It simply wasn't passing the actual error back to the calling script. As #Alex suggested, I replaced Write-Error with $PSCmdlet.WriteError(). Although this didn't totally work.
In the Catch{} block, I then changed $error[0] to $_ and the full error was returned to the calling script / function.
I went one further and wrote a reusable function, added to my module:
function Write-PsError
{
[cmdletbinding()]
Param
(
[Exception]$Message,
[Management.Automation.ErrorCategory]$ErrorCategory = "NotSpecified"
)
$arguments = #(
$Message
$null #errorid
[Management.Automation.ErrorCategory]::$ErrorCategory
$null
)
$ErrorRecord = New-Object -TypeName "Management.Automation.ErrorRecord" -ArgumentList $arguments
$PSCmdlet.WriteError($ErrorRecord)
}
Which seems to be working well at the moment. I especially like the way intellisense picks up all the ErrorCategories. Not sure what or how ISE (PS 5.1 / Win 7) does that. I thought I was going to have to add my own dynamic parameter.
HTH.
Related
I am working on PowerShell scripts. I have two scripts in those scripts I am connecting with two Azure Analysis Servers one by one. And these scripts are calling by the main script. I am getting errors
"Exception calling "Connect" with "1" argument(s): "Object reference not set to an instance of an object."
My Scripts code is below
Child1.ps1
param(
[String]
$envName1,
[String]
$toBeDisconnect1
)
$loadInfo1 = [Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")
$server1 = New-Object Microsoft.AnalysisServices.Server
if($toBeDisconnect1 -eq "No")
{
$server1.Connect($envName1)
return $server1
}
elseif($toBeDisconnect1 -eq "Yes")
{
$server1.Disconnect()
Write-Host $server1 " has been disconnected."
}
Child2.ps1
param(
[String]
$envName1,
[String]
$toBeDisconnect1
)
$loadInfo1 = [Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")
$server1 = New-Object Microsoft.AnalysisServices.Server
if($toBeDisconnect1 -eq "No")
{
$server1.Connect($envName1)
return $server1
}
elseif($toBeDisconnect1 -eq "Yes")
{
$server1.Disconnect()
Write-Host $server1 " has been disconnected."
}
MainParent.ps1
param(
$filePath = "C:\Users\user1\Desktop\DBList.txt"
)
$command = "C:\Users\User1\Desktop\test1.ps1 –envName1
asazure://aspaaseastus2.asazure.windows.net/mydevaas -toBeDisconnect1 No"
$Obj1 = Invoke-Expression $command
Start-Sleep -Seconds 15
$command1 = "C:\Users\User1\Desktop\test2.ps1 –envName2
asazure://aspaaseastus2.asazure.windows.net/myuataas -toBeDisconnect2 No"
$Obj2 = Invoke-Expression $command1
Error is below in MainParent.ps1
Exception calling "Connect" with "1" argument(s): "Object reference not set to an instance of an
object."
At C:\Users\User1\Desktop\test1.ps1:13 char:5
+ $server1.Connect($envName1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NullReferenceException
Exception calling "Connect" with "1" argument(s): "Object reference not set to an instance of an
object."
At C:\Users\User1\Desktop\test2.ps1:13 char:5
+ $server2.Connect($envName2)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NullReferenceException
My AzureAnalysis Services dll version is 13.0.4495.10. I am sharing this info, may be it can be a issue.
It seems Invoke-Expression is not passing the param envName1. I would rather call the child script normally like below:
$Obj1 = &"C:\Users\User1\Desktop\test1.ps1" -envName1 "asazure://aspaaseastus2.asazure.windows.net/mydevaas" -toBeDisconnect1 No | select -Last 1
$Obj2 = &"C:\Users\User1\Desktop\test2.ps1" -envName2 "asazure://aspaaseastus2.asazure.windows.net/myuataas" -toBeDisconnect2 No | select -Last 1
$command = "C:\Users\User1\Desktop\test1.ps1 –envName1 asazure://aspaaseastus2.asazure.windows.net/mydevaas -toBeDisconnect1 No"
Look closely at the hyphen before envName1. It's actually – (en-dash) instead of - (hyphen). That's the reason envName1 is not being passed. The second param toBeDisconnect1 has it correct.
How to know the difference? - (hyphen) is shorter than – (en-dash) :)
I have a funktion to list all email-addresses on a specified user in Office365 and I use this function to check if an email-address is available.
Why is the Try-Catch not working in VS Code but in PS ISE?
Function ListAllEmailAdresses
{
param ($ID)
Try
{
$Mailbox = Get-Mailbox -Identity $ID -ErrorAction Stop
$VarUser = Get-User -Identity $ID -ErrorAction Stop
Write-Output "Email is occupied by: $Mailbox, $($VarUser.Title)"
Write-Output $Mailbox.EmailAddresses
}
Catch
{
Write-Output "E-mail $ID is available"
}
}
when calling this function in VS Code the Try-Catch is not working.
PS C:\script> ListAllEmailAdresses -ID 'lidingo#elon.se'
The operation couldn't be performed because object 'lidingo#elon.se' couldn't be found on 'VI1PR03DC0025.eurprd03.prod.outlook.com'.
+ CategoryInfo : NotSpecified: (:) [Get-Mailbox], ManagementObjectNotFoundException
+ FullyQualifiedErrorId : [Server=VI1PR03MB3165,RequestId=62016320-c687-41ed-9949-4b0fe854d821,TimeStamp=2017-08-09 13:54:40] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] 2CD51ECE,Microsoft.Exchange.Management.RecipientTasks.GetMailbox
+ PSComputerName : ps.outlook.com
The operation couldn't be performed because object 'lidingo#elon.se' couldn't be found on 'VI1PR03DC0025.eurprd03.prod.outlook.com'.
+ CategoryInfo : NotSpecified: (:) [Get-User], ManagementObjectNotFoundException
+ FullyQualifiedErrorId : [Server=VI1PR03MB3165,RequestId=db435869-8b64-4edf-bb90-a2eb836b07fa,TimeStamp=2017-08-09 13:54:41] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] DAFB12B9,Microsoft.Exchange.Management.RecipientTasks.GetUser
+ PSComputerName : ps.outlook.com
Email is occupied by: ,
The PS Error say that the called E-mailadrdress could not be found and therefore it should got to the Catch-code. But it doesnt :(
If I call the same function in Powershell ISE I get this result:
PS C:\Script> ListAllEmailAdresses -ID 'lidingo#elon.se'
E-mail lidingo#elon.se is available
The PS Error is catched and I get the wanted output.
/Anders
I am trying to add an open varible to this command so when the data pulls from line 24 it adds it to the variable and makes it executable.
$data = Get-Content "C:\Users\bgriffiths\Documents\test.dat"
$data[24]
I have tried adding different formats to do this and nothing seems to work.
one command i tried was
invoke-command sql -query = $data
I get an error telling me
Invoke-Command : A parameter cannot be found that matches parameter name 'query'.
At line:4 char:26
+ invoke-command sql -query <<<< = $data
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
another command I have been trying to run is
$Command.CommandType.text = $data
the only error I get from this is
Property 'text' cannot be found on this object; make sure it exists and is settable.
At line:10 char:30
+ $Command.CommandType. <<<< text = $data
+ CategoryInfo : InvalidOperation: (text:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
I am at a lost on how to import file data into the script and have it run it.
I figured out how to run commands for sql through my powershell I had to actaully import the assembly list for the sql ps and then I was able to run the Invoke-SqlCmd
the script to add the information for sqlps to your windows ps is -
$ErrorActionPreference = "Stop"
$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"
if (Get-ChildItem $sqlpsreg -ErrorAction "SilentlyContinue")
{
throw "SQL Server Powershell is not installed."
}
else
{
$item = Get-ItemProperty $sqlpsreg
$sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)
}
#
# Preload the assemblies. Note that most assemblies will be loaded when the provider
# is used. if you work only within the provider this may not be needed. It will reduce
# the shell's footprint if you leave these out.
#
$assemblylist =
"Microsoft.SqlServer.Smo",
"Microsoft.SqlServer.Dmf ",
"Microsoft.SqlServer.SqlWmiManagement ",
"Microsoft.SqlServer.ConnectionInfo ",
"Microsoft.SqlServer.SmoExtended ",
"Microsoft.SqlServer.Management.RegisteredServers ",
"Microsoft.SqlServer.Management.Sdk.Sfc ",
"Microsoft.SqlServer.SqlEnum ",
"Microsoft.SqlServer.RegSvrEnum ",
"Microsoft.SqlServer.WmiEnum ",
"Microsoft.SqlServer.ServiceBrokerEnum ",
"Microsoft.SqlServer.ConnectionInfoExtended ",
"Microsoft.SqlServer.Management.Collector ",
"Microsoft.SqlServer.Management.CollectorEnum"
foreach ($asm in $assemblylist)
{
$asm = [Reflection.Assembly]::LoadWithPartialName($asm)
}
#
# Set variables that the provider expects (mandatory for the SQL provider)
#
Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000
#
# Load the snapins, type data, format data
#
Push-Location
cd $sqlpsPath
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
Update-TypeData -PrependPath SQLProvider.Types.ps1xml
update-FormatData -prependpath SQLProvider.Format.ps1xml
Pop-Location
Write-Host -ForegroundColor Yellow 'SQL Server Powershell extensions are loaded.'
Write-Host
Write-Host -ForegroundColor Yellow 'Type "cd SQLSERVER:\" to step into the provider.'
Write-Host
Write-Host -ForegroundColor Yellow 'For more information, type "help SQLServer".'
the link where I found this is http://blogs.msdn.com/b/mwories/archive/2008/06/14/sql2008_5f00_powershell.aspx
I want to execute below code in the either local or remote machine whith current user.
$BackUpSqlAgentAndRemoveOldbackup = {
param([string]$AppServer,[string]$SqlInstance,[string]$BackupShare,[string]$alias)
[Environment]::UserName #I got same user name in all cases.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo') | Out-Null
$server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $SqlInstance
$backupName = 'SqlAgentJob_' + $SqlInstance + '_' + (Get-Date –format ‘yyyyMMdd_HHmm’) + '_' + $alias + '.sql'
$backupPath = join-path $BackupShare $backupName
$oldBackups = Get-ChildItem $backupShare | where { ( $_.name -like 'SqlAgentJob_*.sql' ) }
$server.JobServer.Jobs.Script() | Out-File -filepath $backupPath
foreach ( $item in $oldBackups ) { remove-item $item.fullName }
}
the #argList is
#('hafcapp-1', 'hafcsql-1', '\\Host5FileSrv\Backup\test','auto')
I notice that
this one, it works well (no -comupterName and -session)
Invoke-Command -ScriptBlock $BackUpSqlAgentAndRemoveOldbackup -argumentList $argList
this one, it throw execption (I also tried "-session", get same result)
Invoke-Command -computerName localhost -ScriptBlock $BackUpSqlAgentAndRemoveOldbackup -argumentList $argList
the exception is as below, it seems the it can not access the folder.
Cannot find path '\\Host5FileSrv\Backup\test' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\Host5FileSrv\Backup\test:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (Script:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Cannot bind argument to parameter 'Path' because it is null.
+ CategoryInfo : InvalidData: (:) [Remove-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RemoveItemCommand
does anyone know how can I do if I want to add computerName or session?
(notes:[Environment]::UserName return identical user)
You have run into the double hop problem. Your credentials can be transferred to the next machine (first hop), but no further (second hop). This means that you can't use the credentials of the machine where you are executing Invoke-Command on, the remote machine (localhost) to connect to a file share (\Host5FileSrv\Backup). Even if you use localhost as computername, it is still remoting. A solution could be CredSSP. See here and here for more information.
This looks like a "second hop" remoting problem, and you'll need to configure WinRM on the computers involved to use CredSSP
http://msdn.microsoft.com/en-us/library/windows/desktop/ee309365(v=vs.85).aspx
Not sure what the eff' is wrong! I am using Powershell 2.0 on Windows 7. Had this same script working on Windows XP , am i just missing something?
$server = "server1-vm1.prod.ds.russell.com"
$name = "Superduper_Reports"
$iis = [ADSI]"IIS://$server/W3SVC/AppPools/$name"
$iis.psbase.invoke("recycle")
Error (that invoke looks okay to me?):
Exception calling "Invoke" with "2" argument(s): "Unknown error (0x80005000)"
At line:3 char:19
+ $iis.psbase.invoke <<<< ("recycle")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
When just running $iis variable i get this error:
The following exception occurred while retrieving member "PSComputerName": "Unknown error (0x80005000)"
+ CategoryInfo : NotSpecified: (:) [format-default], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMember,Microsoft.PowerShell.Commands.FormatDefaultCommand
Roooarr! I'd rather use ADSI over WMI! Any help? :)
I think that you can use WebAdministration module for that
Import-Module WebAdministration
Get-Command -Module WebAdministration
Get-ChildItem IIS:
You will find a lots of Cmdlets to admin IIS and a new drive IIS:
You will find on this Microsoft Web site some explanations.
This question has a WMI script which has been stated to work.
Alternatively ADSI equivalent would look something like this ...
http://geekswithblogs.net/Lance/archive/2010/12/16/powershell-ndash-recycle-all-iis-app-pools.aspx
function Recycle-AppPools {
param(
[string] $server = "3bhs001",
[int] $mode = 1, # ManagedPipelineModes: 0 = integrated, 1 = classic
)
$iis = [adsi]"IIS://$server/W3SVC/AppPools"
$iis.psbase.children | %{
$pool = [adsi]($_.psbase.path);
if ($pool.AppPoolState -eq 2 -and $pool.ManagedPipelineMode -eq $mode) {
# AppPoolStates: 1 = starting, 2 = started, 3 = stopping, 4 = stopped
$pool.psbase.invoke("recycle")
}
}
}
You can't recycle a stopped AppPool however so you need to check for that.