PowerShell: Get-Service w/ Get-Content, -name and select - powershell

I am trying to get the status of a specific service on 2008 R2 servers listed in a text file.
I once was able to successfully run the following:
$servers = Get-Content "C:\scripts\Computers.txt"
Get-Service -ComputerName $servers -Name MrT |
Select Name, MachineName, Status
As shown here:
Now when I run the same script I get the following error:
Get-Service : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.
At line:3 char:27
+ Get-Service -ComputerName $servers -Name MrT |
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Service], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetServiceCommand
Technically to get past this, I could run the following but would rather run against a list of servers.
Get-Service -ComputerName 3b, 4b, 7b -Name MrT | Select Name, MachineName, Status
What am I doing wrong and how did it work once and not work again?

As the error message points it out, the $servers variable probably doesn't contain any items. Check the output by running:
Get-Content "C:\scripts\Computers.txt"

Related

Attempting to query all Windows servers to find those that have media loaded in the CD-ROM drive

I'm trying to build a command to query all Windows servers in AD and report if they have media loaded in the CD-ROM drive. I pieced together a command that I thought was correct and now I'm stuck at it reporting and RPC error. Note: The CD-ROM drive does not have the same assigned drive letter on every server.
Command:
$Computers = Get-ADComputer -filter 'operatingsystem -like "server" -and enabled -eq "true"'
foreach($Computer in $Computers){GET-WmiObject –query 'SELECT * from win32_logicaldisk where DriveType = "5"' –computername $Computer | Select Displayname,DeviceID,Size,VolumeName}
I receive the following error when executing it.
GET-WmiObject : The RPC server is unavailable.
At line:2 char:34
... $Computers){GET-WmiObject –query 'SELECT * from win32_logicaldisk whe ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
I've never used the Get-WmiObject command before and I'm in unfamiliar territory. Any assistance would be greatly appreciated.
Thank you
Get-AdComputer doesn't return computer names you can use directly with -ComputerName, try:
–computername $Computer.Name

Powershell Profile Removal - Windows 7

I am running the below script on Windows 10 without problems. So i am attempting to run it on Windows 7. However I get this weird error. The piece before the pipe to Remove-CimInstance works fine. Just something wrong when it hits the pipe
Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $pullUser } | Remove-CimInstance
However, i am getting the error below
Remove-CimInstance : The parameter is incorrect.
At line:1 char:104
+ ... LocalPath.split('\')[-1] -eq "useridhere" } | Remove-CimInstance
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (Win32_UserProfi...6-100815088...):CimInstance) [Remove-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070057,Microsoft.Management.Infrastructure.CimCmdlets.RemoveCimInstanceCommand
EDIT
So as it turns out, there was an issue with a WMI on the device i was testing on. I originally created this script for Win10 and have been moving backwards to make it work on Windows 7. The premise of the entire script is to create a TASK JOB to delete a user profile on Startup.
For whatever reason, the script in its entirety works fine when running from a Powershell ISE Window with Admin rights, the TASK JOB is set to run as system, however it is failing the most basic of commands (almost as if the cmdlets are not loaded). I will be posting a new question on this if I cannot figure out what the problem is.
Tyr this to see all details of this action.
# Get the stack information and the full error message if any
Trace-Command -Name metadata,parameterbinding,cmdlet -Expression {
Get-CimInstance -Class Win32_UserProfile |
Where-Object {
$_.LocalPath.split('\')[-1] -eq 'TestUser'} |
Remove-CimInstance -Verbose -WhatIf
} -PSHost
$Error[0] |
Select-Object -'*' |
Format-List -Force

Revoke-AzureADUserAllRefreshToken CommandNotRecognized

I'm trying to run the following script to disable AD and O365 accounts that are disabled.
import-module activedirectory
$Corporate = Get-ADUser -Server "myActiveDirectoryDomain" -Filter * -Property Enabled | Where-Object {$_.Enabled -like “false”}
$Corporate | ForEach-Object -Process { Revoke-AzureADUserAllRefreshToken -ObjectId $_.ObjectGUID }
However, when I run my script, I get this errror...
Revoke-AzureADUserAllRefreshToken : The term 'Revoke-AzureADUserAllRefreshToken' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that
the path is correct and try again.
At C:\Users\lpurhr1\Documents\_RHR\PowerShellScripts\RemoveAccessTokenForDisabledAccounts.ps1:37 char:40
+ ... | ForEach-Object -Process { Revoke-AzureADUserAllRefreshToken -Object ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Revoke-AzureADUserAllRefreshToken:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I have no idea why I'm getting this error, and nothing online is really telling me why this should be happening. I can run the Get-ADUser cmdlet just fine, but the Revoke-AzureADUserAllRefreshToken doesn't seem to be recognized. I'm sure there's something I'm not installing. Does anyone know what I'm missing?
The command Revoke-AzureADUserAllRefreshToken belongs to the AzureAD powershell module, you need to install it first.
Install-Module AzureAD
Reference - https://learn.microsoft.com/en-us/powershell/azure/active-directory/install-adv2?view=azureadps-2.0

Get-DnsServerResourceRecord not working on 2016 server

I have a powershell that utilizes the function Get-DnsServerResourceRecord. I have it working on a couple of different servers for testing, but on the server that I want it to run from I get this error:
Get-DnsServerResourceRecord : The term 'Get-DnsServerResourceRecord'
is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again. At line:2
char:3
+ Get-DnsServerResourceRecord -ComputerName $DNSServer -ZoneNam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-DnsServerResourceRecord:String) [], CommandNotF oundException
+ FullyQualifiedErrorId : CommandNotFoundException
All of my googling has told me that since I am running this on a Windows Server 2016 (DataCenter) that this should just work. What am I missing in order for this to run?
How I am actually running it:
$DNSServer = "dnsservername"
$dnsrecord = Get-DnsServerResourceRecord -ComputerName $DNSServer -ZoneName 'db.local' -RRType CName | Where-Object {$_.RecordData.HostNameAlias -like "*" -and $_.HostName -like "*.*"}
$Datatable = New-Object System.Data.DataTable
[void]$Datatable.Columns.Add("CName")
[void]$Datatable.Columns.Add("HostNameAlias")
Foreach ($record in $dnsrecord)
{
[void]$Datatable.Rows.Add($record.HostName, $record.RecordData.HostNameAlias)
}
You need to install DNS server Tools module.
run below powershell command
Install-WindowsFeature rsat-dns-server
(As of 2022)
List Installed Windows Features on Win10 (Powershell)
Get-WindowsOptionalFeature -Online | Where Name -Match "RSAT.*" | Format-Table -Autosize
Install RSAT.DNS.TOOLS
Add-WindowsCapability -Online -Name Rsat.Dns.Tools

Where-Object : Cannot bind parameter 'FilterScript'

I have one problem with two questions. I have following powercli cmd:
$snapLst = Get-VM vmindev |Get-Snapshot |Select VM, Name, Description, `
#{Name='Created'; Expression={{$_.Created.ToString("yyMMdd")}}, `
#{Name='SizeMB'; Expression={[int] $_.SizeMB}}
$resultLst=$snapLst| where SizeMB -gt 1000 |Sort-Object SizeMB |`
Select #{Name='Type'; Expression={'BIG'}},*
When run in my DEV env (powercli session on my desktop connecting to the vSphere sever), everything is fine. When run in PRODUCTION (ie. powercli session on the vSphere server), I get the following error:
Where-Object : Cannot bind parameter 'FilterScript'. Cannot convert the "SizeMB" value of type "System.String" to type System.Management.Automation.ScriptBlock".
At C:\Users\kness\Scripts\sn2.ps1:32 char:27
+ $resultLst=$snapLst| where <<<< SizeMB -gt 1000 |Sort-Object SizeMB |Select
#{Name='Type'; Expression={'BIG'}},
+ CategoryInfo : InvalidArgument: (:) [Where-Object], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.WhereObjectCommand
Q1: What - in the environment setup - would make the script behaves differently? I checked the versions of the powercli ... they're exactly the same.
Q2: Because the above error, I look into the property of the list by running this cmd:
$snapLst = Get-VM vmindev |Get-Snapshot |Get-Member |Findstr Size
SizeGB Property System.Nullable`1[[System.Decimal, mscorlib, Ve...
SizeMB Property System.Decimal SizeMB {get;}
SizeMB is a "decimal" type; why the error complains that it is a "string"?
Thx in advance!
I got it resolved with helps fr TessellatingHeckler.
A1. Although my PowerCLI package is the same, it operates on two different Powershell installation. On my desktop, PSVersion is 4.0 and on the production server, it is 2.0
A2. This is related to A1. In PS 4.0, the cmdlet where is translated properly to Where-Object {...}. Whereas in PS 2.0, it is a syntax error. The complain about SizeMB being System.String is just a red herring following the "where" syntax error.
By changing where SizeMB -gt 1000 to Where-Object {$_.SizeMB -gt 1000} the script is now working. I guess, the alternative would be to upgrade the PS on the vSphere server ... but I dont want to go there. Thanks for your helps everyone.