Powershell Profile Removal - Windows 7 - powershell

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

Related

PowerShell command to locate software on all PC's on AD group

We have swapped over to a new virus protection and I'm trying to track down all the machines with our old McAfee software on it. We are in a domain group, and all the PC's are listed in active directory.
$list = Get-ADComputer -Filter *
foreach($PC in $list){
$data = Get-WmiObject -ComputerName $PC -Class Win32_Product | sort-object Name |
Select-Object Name | Where-Object { $_.Name -like "*McAfee*"}
if($data){
Write-Output "$PC has $($data.name) installed" |
out-file C:\Users\username\Desktop -Append
}
}
I'm a bit amateur when it comes to powershell.
Im getting this error over and over again
Get-WmiObject : The RPC server is unavailable.
At line:4 char:13
+ $data = Get-WmiObject -ComputerName $PC -Class Win32_Product | so ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
I've read it's likely a firewall setting in the group policy. Before I try and get that changed is this the most effective way to do this? I'm avoiding using a list of computer names for simplicity, but I can do if necessary.
You are right, there is a firewall setting blocking the Powershell remote access. It seems like a very common security setting in a lot of places since it's easier to turn it all off than to try to tune it to just allow specific people to use.
If you don't have access to SCCM or any other inventory/configuration management software like AdminOfThings commented, then this is a reasonable way to get the information you're looking for. I used a similar method to track RAM and CPU usages on some of our computers, but I had to modify each computer with the code at the link codaamok posted. It was an opt-in program so that method worked for me.
It's probably going to depend on how your Group Policy Admins want to handle it, if they want to allow this sort of remote access or not.

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

Write synchronously to the command line inside a foreach with a pipelined command

I have the following code:
Get-ResourcePool -Server 1.1.1.1 | Where-Object {$_.Name -like 'XX*'} | foreach {
Write-Host $_.Name -ForegroundColor Red
Get-ResourcePool -Name $_.Name | Get-VM
}
Which is executed asynchronously, due to pipeline - so all of the Write-Host outputs appear on the console and only after that I get the result from Get-ResourcePool.
Question: how do I make it synchronous - how do I wait for the pipeline to finish before executing the next foreach cycle.
P.S. I was able to determine that the problem is with the pipeline because when I remove the pipe inside the for each I get what I expect.
P.P.S i tried Start-Job -ScriptBlock { Get-ResourcePool -Name $Input | Get-VM } -InputObject "$_.Name" and then wait for the job to finish - but that does not work due to fact that I need to be connected to the vCenter while this command runs, so I get:
7/1/2019 6:37:49 PM Get-ResourcePool You are not currently connected to any servers. Please connect first using a Connect cmdlet.
+ CategoryInfo : ResourceUnavailable: (:) [Get-ResourcePool], ViServerConnectionException
+ FullyQualifiedErrorId : Core_BaseCmdlet_NotConnectedError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetResourcePool
+ PSComputerName : localhost
ADDENDUM:
Adding screenshots with some of the suggestions - unfortunately none of them work:
Suggestion from reddit also does not work: https://www.reddit.com/r/PowerShell/comments/8hvjyn/output_delay/
Adding a pause at the end:
Adding pause and Out-Host at the end:
how do I wait for the pipeline to finish before executing the next foreach cycle.
You can force synchronous output to the host application with Out-Default:
Get-ResourcePool -Server 1.1.1.1 | Where-Object {$_.Name -like 'XX*'} | ForEach-Object {
Write-Host $_.Name -ForegroundColor Red
Get-ResourcePool -Name $_.Name | Get-VM | Out-Default
}
Solved the issue: it was my personal mistake. I was testing with resource pools where the only resource pool having any VMs was the last one. After I changed it to resource pool containing multiple VMs and tested it, I was able to see it working fine.

When removing software "you cannot call a method on a null-valued expressions" error

I know there are other threads with this question but they all involve code that I don't understand. I know very little of scripting and I'm looking for someone to help me with an easy to understand answer.
I am trying to remove a program with PowerShell (the program doesn't have an uninstaller file).
I can remove it with Control Panel → Programs and Features, but I would like to do this remotely with a PSSession. So after some searching on Google I found the following script.
I first run
Get-WmiObject -Class Win32_Product | Select-Object -Property Name
Which gets me the name of the program I want to delete: "OpenOTP-CP (64 bit)"
I then run the script:
$app = Get-WmiObject -Class Win32_Product | Where-Object {
$_.Name -match "OpenOTP-CP (64 bit)"
}
$app.Uninstall()
I then get the following error
You cannot call a method on a null-valued expression.
At C:\Users\Administrator\Desktop\Remote2.ps1:4 char:1
+ $app.Uninstall()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Could someone maybe help me by telling me what is wrong or providing me with the correct code?
OS: Windows Server 2012 R2
Source for the script: http://lifeofageekadmin.com/how-to-uninstall-programs-using-powershell/
It sounds like $app may be an empty variable. I would add a temporary write-host "app is: $app" before you call $app.uninstall() to check if that is the case.
Alternatively, you could add some logic like this:
If ($app){
$app.Uninstall()
}else{
write-host "app was not found"
}
The reason $app might be empty is because the -match operator uses regular expressions, so it's likely treating the brackets as special characters. Try using -like instead of -match and surrounding it with asterisks:
$app = Get-WmiObject -Class Win32_Product | Where-Object {
$_.Name -like "*OpenOTP-CP (64 bit)*"
}
You could do it this way and it would be faster. I'm assume it's an msi provider.
get-package "*OpenOTP-CP (64 bit)*" | uninstall-package

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

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"