How to remove the error from the powershell report - powershell

i have created a powershell script to run image validation remotely and when any of the service found in stopped state this will fail the script.I am getting below error while failing the script.Is there anyway so that I can hide these error from the report?
+ Invoke-Command -ScriptBlock {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], RuntimeException
+ FullyQualifiedErrorId : ScriptHalted
This is the script i used to fail when the service is in stopped state.
$EMService = get-wmiobject win32_service | where-object {($_.Name -eq 'HP12cAgent') -or ($_.Name -eq 'HPagent12c2Agent') -or ($_.Name -eq 'HPagent10gAgent') -or ($_.Name -eq 'FarmEM10gAgent') -or ($_.Name -eq 'FarmEM11gAgent')} | format-list name | Out-String
$Servicename = $EMService.Split(":")[1].Trim()
$EMStatus1 = get-wmiobject win32_service | where-object {$_.Name -eq $Servicename} | format-list state | Out-String
$ServiceStatus = $EMStatus1.Split(":")[1].Trim()
if ($Servicename -eq $null)
{
$Servicename = "Unavailable"
}
else
{
$Servicename = "$Servicename"
}
if ($ServiceStatus -eq "Stopped")
{
throw
}
Else
{
exit 0
}

You can always try wrapping stuff in a try/catch block.
try { some powershell stuff }
catch { Write-Host $_ ; or do nothing }

Related

If not run after get-service in powershell

I'm trying to access the service status of the remote server. i wrote this
$ServerList = get-content -Path "c:\users\cont015\Desktop\ServerList.txt"
ForEach ($ServerName in $ServerList)
{
$Status= Get-Service -ComputerName $ServerName | ?{$_.DisplayName -like "SQL Server (*"} | select Status | format-wide
if($st -eq "Running")
{
$SeverName
$Status
}
else
{
}
}
it is showing
$Status= Get-Service -ComputerName $ServerName | ?{$_.DisplayName -li ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand
in error. i don't know what i am missing. but when i run without if condition if shows proper output.
$ServerList = Get-Content -Path "c:\users\cont015\Desktop\ServerList.txt"
ForEach ($ServerName in $ServerList)
{
$Status= #(
Get-Service -ComputerName $ServerName -DisplayName "SQL Server (*" |
Select-Object -ExpandProperty Status)
if ("Running" -in $Status)
{
[PSCustomObject]#{
Server = $ServerName
Status = $Status
}
}
else
{
}
}
Explanation:
Get-Service docs: -DisplayName
Specifies, as a string array, the display names of services to be retrieved. Wildcards are permitted (used instead of Where-Object as such filtering is always faster).
Array subexpression operator #( ). -
Returns the result of one or more statements as an array. The result is always an array of 0 or more objects (i.e. force Powershell to always return an array when a call returns only one object or even $null)
Used [PSCustomObject]#{} in output instead of a sequence of strings (learn advantages at Everything you wanted to know about PSCustomObject).

Powershell: Retrieving LogonDate in Active Directory

I've a list of computers, I'm checking if they are connected, if they aren't check with AD and "spit out" the one that aren't connecting for more than 3 months.
If it's connected then check if a services is installed.
Here's my code:
Import-Module ActiveDirectory
$datecutoff = (Get-Date).AddDays(-90)
Get-Content "C:\powershell\pc.txt" |
foreach {
if (-not (Test-Connection -comp $_ -quiet)){
Write-host "$_ is down" -ForegroundColor Red
$LastLog = Get-ADComputer -Identity $_ | Select LastLogonDate
if($LastLog -lt $datecutoff){
Write-host "$_ is offline for more than 3 months" -ForegroundColor Yellow
}
} Else {
$service = get-service -name masvc -ComputerName $_ -ErrorAction SilentlyContinue
if ($service ){
write-host "$_ Installed"
} else {
Write-host "$_ Not Installed"
}
}
}
When it finds a disconnected computer it gives me the following error:
Cannot compare "#{LastLogonDate=}" to "2020.04.16 18:49:19" because the objects are not the same type or the object "#{LastLogonDate=}" does not implement "IComparable".
At line:10 char:20
+ if($LastLog -lt $datecutoff){
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : PSObjectCompareTo
I know the error happens because my variable is saving wrong info, but I cannot find a way to only select the date in the AD.
Is there anyway to do this?
Thanks in advance.
You have a couple of issues. You'll need to request that LastLogonDate is returned with Get-ADComputer as its not by default. You'll need to use the dotted notation method of selecting property LastLogonDate from the $LastLog object so your compare works.
Import-Module ActiveDirectory
$datecutoff = (Get-Date).AddDays(-90)
Get-Content "C:\powershell\pc.txt" |
foreach {
if (-not (Test-Connection -comp $_ -Quiet)) {
Write-Host "$_ is down" -ForegroundColor Red
$LastLog = Get-ADComputer -Identity $_ -Properties LastLogonDate
if ($LastLog.LastLogonDate -lt $datecutoff) {
Write-Host "$_ is offline for more than 3 months" -ForegroundColor Yellow
}
} Else {
$service = Get-Service -Name masvc -ComputerName $_ -ErrorAction SilentlyContinue
if ($service ) {
Write-Host "$_ Installed"
} else {
Write-Host "$_ Not Installed"
}
}
}
Welcome to stackoverflow, please read https://stackoverflow.com/help/someone-answers
Side note. You can filter for aged computers like this Get-ADComputer -Filter 'LastLogonDate -lt $datecutoff'

remove-variable and pipeline - null-valued expression?

I'm trying to remove some variables in my PowerShell script like so:
#create example com object
$Excel = New-Object -ComObject Excel.Application
#do something with COM object, close COM object etc
#clear variable
get-variable | where-object { $_.Value -ne $null -And $_.Value.ToString() -eq $Excel.GetType() } | remove-variable
But it returns:
You cannot call a method on a null-valued expression.
on the get-variable.... line? However, when I test that line like so:
get-variable | where-object { $_.Value -ne $null -And $_.Value.ToString() -eq $Excel.GetType() } | Select -Property Name
It returns the correct data? I get the same behaviour with:
get-variable | where-object { $_.Value -ne $null -And $_.Value.ToString() -eq $Excel.GetType() } | ForEach-Object { remove-variable -Name $_.Name }
I can't figure out why remove-variable doesn't work? The remove-variable cmdlet accepts 'Name' in the pipeline by 'PropertyName' so i think that looks ok to me?
UPDATED
Interestingly, the full error is multiple occurrences of this (interesting because the line should only return 3 results but there are 48 of these error messages):
You cannot call a method on a null-valued expression.
At line:3 char:31
+ ... re-object { $_.Value -ne $null -And $_.Value.ToString() -eq $Excel.Ge ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
ALSO
This works:
$vars = get-variable | where-object { $_.Value -ne $null -And $_.Value.ToString() -eq $Excel.GetType() } | Select-object -ExpandProperty Name
foreach ($var in $vars) {
remove-variable -Name $var
}
But this doesn't?:
get-variable | where-object { $_.Value -ne $null -And $_.Value.ToString() -eq $Excel.GetType() } | foreach { remove-variable -Name $_.Name }
I fixed it in the end by adding more null checks in the where-object part of the pipeline (thanks #ScottHeath):
get-variable | where-object { $null -ne $_ -And $null -ne $_.Value -And $null -ne $Excel -And $_.Value.ToString() -eq $Excel.GetType().ToString() } | foreach { Remove-Variable -Name $_.Name }
Com objects need to be released from memory with:
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
After that, remove the variable itself with
$Excel = $null
Remove-Variable -Name Excel
Remove-Variable also has an -Include parameter where you can specify an array of variable names. Wildcards are also permitted there.

Delete User Profile in Windows using PowerShell

I am creating a script which should delete profiles which haven't been used in the last 180 days in Windows systems.
Following is my code.
$profiles = Get-WMIObject -Class Win32_UserProfile | Where {
(!$_.Special) -and
($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-1))
}
$count = $profiles | Measure-Object | select -ExpandProperty Count
if ($count -eq 0) {
Write-Output "No Profiles found for Deletion"
exit
}
Write-Output "Number of profiles : $count"
$profiledeleted = #()
$profileerror = #()
foreach ($profile in $profiles) {
$profile | Remove-WmiObject
if ($?) {
$profiledeleted += $profile.Localpath
continue
} else {
$profileerror += $profile.Localpath
}
}
if ($profiledeleted.Length -gt 0) {
Write-Output "Localpath of removed profiles"
$profiledeleted
}
if ($profileerror.Length -gt 0) {
Write-Output "Error While removing below profiles"
$profileerror
}
The code should run with the system account but I am getting the following error.
Remove-WmiObject :
At C:\Users\Admin\GRT-2687_deleteunuseduserprofiles.ps1:22 char:32
+ $profile | Remove-WmiObject <<<<
+ CategoryInfo : InvalidOperation: (:) [Remove-WmiObject], COMException
+ FullyQualifiedErrorId : RemoveWMICOMException,Microsoft.PowerShell.Commands.RemoveWmiObject
Edit : It is deleting all the data except the folder C:\Users\Username.

Unexpected Token with service script

I wrote a script that manages services on the server and starts/stops etc...depending on the Task in the csv file, as well as changes the startuptype, again depending on the start up type in the csv file.
CSV file:
Server,Service,Startup Type,Task
server1,SQL Server Analysis Services (MSSQLSERVER),automatic,start
server2,"SQL Server Analysis Services (MSSQLSERVER), SQL Server Analysis Services (MSSQLSERVER) CEIP",Manual,stop
Script
$csvFile = Import-CSV .\SSAS_services.csv
$ServiceState = Get-Service -Name
$ServiceStartupType = Get-Service | select -property name,starttype
ForEach ($row in $csvFile)
{
#checking if service in csv file exists on server
if (Get-Service $row.Service | Select-Object Name, StartType, Status -ComputerName $row.Server -ErrorAction SilentlyContinue)
{
"$row.Service not found on $row.Server!" | out-file .\SSAS_services.txt -Append
}
else
{
Get-Service $row.Service | Select-Object Name, StartType, Status -ComputerName $row.Server | select machinename,name | format-table -AutoSize
}
# Change the service on the server
if ($row.Task -eq "stop" -and $row.Server $ServiceState $row.Service -ne "stop")
{
Invoke-Command -ScriptBlock { Stop-Service $using:row.Service } -ComputerName $row.Server -ArgumentList $row
Start-Sleep 60
}
elseif ($row.Task -eq "start" -and $row.Server $ServiceState $row.Service -ne "start")
{
Invoke-Command -ScriptBlock { Start-Service $using:row.Service } -ComputerName $row.Server -ArgumentList $row
Start-Sleep 60
}
elseif ($row.Task -eq "pause" -and $row.Server $ServiceState $row.Service -ne "pause")
{
Invoke-Command -ScriptBlock { Suspend-Service $using:row.Service } -ComputerName $row.Server -ArgumentList $row
Start-Sleep 60
}
elseif ($row.Task -eq "Restart")
{
Invoke-Command -ScriptBlock { Restart-Service $using:row.Service } -ComputerName $row.Server -ArgumentList $row
Start-Sleep 60
}
#changing startup type if different
if ($row."Startup Type" -eq $ServiceStartupType -ComputerName $row.Server)
{
"Changing Startup Type from '$ServiceStartupType' to $row.'Startup Type'"
Invoke-Command -ScriptBlock { Set-Service $using:row.Service -StartupType $using:row."Startup Type" } -ComputerName $row.Server -ArgumentList $row
}
} | Tee-object .\SSAS_services.txt -Append
I am getting the following errors:
Unexpected token '$ServiceState' in expression or statement.
+ if ($row.Task -eq "stop" -and $row.Server $ServiceState $row.Serv ...
Missing closing ')' after expression in 'if' statement.
+ ... if ($row.Task -eq "stop" -and $row.Server $ServiceState $row.Service ...
Missing closing '}' in statement block or type definition.
+ ... sk -eq "stop" -and $row.Server $ServiceState $row.Service -ne "stop")
+
Unexpected token ')' in expression or statement.
+ ... elseif ($row.Task -eq "start" -and $row.Server $ServiceState $row.Se ...
~
Unexpected token '$ServiceState' in expression or statement.
+ elseif ($row.Task -eq "start" -and $row.Server $ServiceState $row ...
+
Unexpected token '$row' in expression or statement.
+ ... -eq "start" -and $row.Server $ServiceState $row.Service -ne "start")
+ Unexpected token ')' in expression or statement.
+ ... elseif ($row.Task -eq "pause" -and $row.Server $ServiceState $row.Se ...
+
~~~~~~~~~~~~~ Unexpected token '$ServiceState' in expression or statement. Not all parse errors were reported. Correct
the reported errors and try again.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken ~
The if statement with -and $row.Server $ServiceState $row.Service -ne "stop" isn't valid powershell syntax (the expression should evaluate to boolean). You have write a function or use invoke-expression to evaluate the service state.
E.g.
$serviceName = "WSearch"
$command = "get-service $serviceName"
if ((invoke-expression $command).Status -eq "Running") {
# do something...
}