There is an inconsistency concerning the location of powershell's profile on my windows 7 machine - powershell

I created a profile.ps1 in the same directory that contains the powershell executable, which on my machine is C:\Windows\System32\WindowsPowerShell\v1.0
The profile file is definitely executed when I run powershell.exe
However when I enter $profile at the powershell prompt, the following non-existent filename is returned
C:\Users\richard\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.psi
Does anyone know how this inconsistency may have happened and what steps should I take to resolve it?

$Profile is a string, but it has 4 note properties with possible locations to put profile scripts. Each is selected depending on which user and which host is being executed.
To see all 4, use something like this
$profile| select-object *Host* | format-list
The list you get will show profile script locations that would be run for you and this host.

Related

Can no longer start PowerShell script from batch file

We have a batch file that certain users can launch from their local machines that will run a PowerShell script on a DC in order to unlock user accounts or reset a password. However, all of a sudden it's not working, not even for network admins running it as an administrator. If we log on to the DC and run it locally, it works exactly as it should.
There haven't been any changes to the permissions of the file and no changes to the AD groups that have permission to run the file.
The batch file is this:
#echo off
cls
echo Loading, Please Wait...
;C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe -ExecutionPolicy Bypass -File %logonserver%\<PATH TO FILE>\FILENAME.ps1
Same batch file that it's always been, but now when we run it remotely, we get multiple errors:
The term 'Get-ADGroupMember' 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.
Locally, it runs just fine. And yes, the first thing the PowerShell script does is
Import-Module ActiveDirectory -ErrorAction SilentlyContinue
As I said, it used to work but now it doesn't and we're completely lost as to why. We've searched and searched, but can't seem to find any information as to what might be causing it to error out.
If anyone has any ideas or suggestions, we would appreciate it.
Discovered that RSAT wasn't on any of the machines anymore. It required downloading the installer and running it on the machines. Once we did that, everything works like it should.

PowerShell ISE not recognizing $profile variables

In my $profile directory, I have a few custom variables, as well as the default variables, such as $root (which equals "C:\"), etc. One custom variable I have holds the filepath to my desktop, so I can easily reference the path, and also not have to create the variable every time I start up PS. If I attempt to resolve any variable value from the $profile path within ISE(both the script pane and console) it does not work. However, if I use the regular PS terminal, it works no problem. Any suggestions or explanations?
PowerShell ISE uses a different host profile than a standard PowerShell session. The $profile variable actually displays the profile for the CurrentUserCurrentHost profile by default, but there are four profile locations stored in this variable. Each of these locations are dot-sourced by default when you load PowerShell. You can see this by typing $profile | Get-Member -MemberType NoteProperty to see the total profiles configured:
AllUsersAllHosts
AllUsersCurrentHost
CurrentUserAllHosts
CurrentUserCurrentHost
Before we continue, let's talk about what a PowerShell Host really is. From Microsoft:
The host application can define the runspace where commands are run, open sessions on a local or remote computer, and invoke the commands either synchronously or asynchronously based on the needs of the application.
So what this means is that a PowerShell Host implements a PowerShell session. This can be powershell.exe for a basic, standard host, but there could be any number of alternative applications or development tools that may implement their own PowerShell Host as well, for a number of reasons.
The AllHosts profile locations should remain standard regardless of your PowerShell host, but different PowerShell hosts will typically set their own CurrentHost profile locations for their host. For example, powershell.exe is its own PowerShell host, and will have its own host-specific profiles, named Microsoft.PowerShell_profile.ps1. PowerShell ISE implements its own PowerShell host, and has different host-specific profiles named Microsoft.PowerShellISE_profile.ps1.
If you want code in your profile to be host-agnostic, you should make sure to place your profile code in one of the AllHosts profiles. Host-specific code, such as things you only want to be available in the context of the ISE PowerShell host, or a VSCode PowerShell host, should go into that host-specific profile.
$profile is different in the ISE:
$profile
C:\Users\js\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
console:
$profile
C:\Users\js\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

How to run powershell script on computer start-up

I am trying to run a PowerShell script Daily.ps1 on start-up, however, due to administrator settings (I cannot run as admin, that is not an option), I cannot run it through the Task Scheduler. For example, this is the contents of Daily.ps1:
if (1 -eq 1) {
"Hello there!"
}
So I tried to have a batch script Daily.cmd run on start up (through the start-up folder), which runs, but I cannot get it run the Daily.ps1, and I get a message saying running scripts is disabled. (Both files are in the same directory)
powershell C:\Users\Simon\Desktop\Daily.ps1
File C:\Users\Simon\Desktop\Daily.ps1 cannot be loaded because running scripts is disabled on this system
I then tried using this line of code from a trick I learned to bypass running scripts directly:
powershell cat Daily.ps1 | powershell invoke-expression
This works but only for one liners. So I added the -raw flag for
cat, which works when in powershell, but not in CMD. For some reason, Daily.ps1's text is still stored as an array of strings. (apologies for formatting)
cmdlet Invoke-Expression at command pipeline position 1
Supply values for the following parameters:
Command: if (1 -eq 1) {
invoke-expression : At line:1 char:14
if (1 -eq 1) {
Missing closing '}' in statement block or type definition.
At line:1 char:1
invoke-expression ~~~~~~~~~~~~~~~~~
So I tried to add this to Daily.cmd:
powershell
cat -raw Daily.ps1 | powershell-invoke-expression
However, the rest of the script doesn't get executed at all once I enter PowerShell.
I don't know to get Daily.ps1 to run through a batch command. Is there a way I missed, or is one of the ways I tried faulty (without admin rights)?
Edit: To clarify, ExecutionPolicy is set to Restricted, and that cannot be changed. Additionally, I can run PowerShell scripts fine through right clicking the file and running with PS.
Create a scheduled task to run at computer startup. Put powershell.exe in the field "program/script" and -File "C:\path\to\your.ps1" in the field "arguments" (you may want to avoid placing the script in a user profile). Set the task to run whether the user is logged on or not.
I found an answer!
After trying many different methods, I came across this line of code that allows you to run PS scripts if ExecutionProperty is set to restricted:
start powershell "cat -raw C:\Users\Simon\Desktop\Daily.ps1 | invoke-expression"
This runs powershell and uses the trick of piping the results of cat -raw [file.ps1] to invoke-expression. This is useful workaround if ExecutionProperty is set to restricted.
Then you can save this line to a .cmd or .bat file and use either Task Scheduler (more customizability) or put it in the startup folder.
P.S. for everyone who kept saying change the ExecutionProperty to something other than restricted. I clearly stated multiple times that I cannot do that(not admin), nor will the Sys Admin do that, nor will it ever happen(must stay restricted) :)

Deleting all locally stored user profiles on log off

I want to delete all locally stored user profiles on logoff using a Powershell script. I've the following script:
Set-ExecutionPolicyRemoteSigned[gc]::collect()
cmd /c start reg unload "HKCU"Remove-PSDrive HKCU import-module C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ManageUserProfiles\ManageUserProfiles.PSM1
get-userprofile |where{ $_.SID -ne ("S-1-5-21-3071724114-2656578308-4228372245-500")} | remove-userprofile
I'm a complete newbie to powershell. So could someone tell me whether this script meets my needs and how does it run? And could you also explain what $_.SID -ne ("S-1-5-21-3071724114-2656578308-4228372245-500") means too. Thanks in advance.
I am not familiar with the module that you are running, and it looks like that should be 6 lines not 3 (insert break before [gc], before Remove-PSDrive, and before Import-Module).
Next, add a space between Set-ExecutionPolicy and RemoteSigned.
Now, the script appears to collect user profiles, pipes them through a Where statement that excludes the Administrator account from the list of profiles, and then removes all remaining profiles. Let's step through it...
Set-ExecutionPolicy RemoteSigned
This sets your execution policy. I'm going to assume this is to avoid issues with an unsigned module that you load in a couple steps.
[gc]::collect()
This forces the garbage collection to clean up memory and remove unused resources. This line can probably be skipped.
cmd /c start reg unload "HKCU"
This uses the reg.exe command line application to unload the HKEY_CURRENT_USER hive from within the current registry set. This would need to be done before deleting a profile since you can't delete files that are in use.
Remove-PSDrive HKCU
This does pretty much the same thing, but for PowerShell's registry provider. I'm guessing this is so that you don't get errors, or so that it doesn't try to reload the HKCU hive.
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ManageUserProfiles\ManageUserProfiles.PSM1
This loads the 'Manage User Profiles' module. I am not familiar with the module, but you would need to make sure that you have that module installed on the computer that this is running on, so if you are running this on all of your computers you need to install that module on all of your computers.
get-userprofile |where{ $_.SID -ne ("S-1-5-21-3071724114-2656578308-4228372245-500")} | remove-userprofile
This is a command from the module you just loaded. It will, I assume, get user profiles as some sort of custom object, and then it pipes to a Where statement that excludes the Administrator account by stating that it only allows profile objects that do not (-ne is the 'not equal' operator) have a SID property equal to "S-1-5-21-3071724114-2656578308-4228372245-500". So all user profiles except the admin account's profile are then piped to the Remove-UserProfile command, which we can probably assume deletes each profile that is piped to it.
Hopefully that explains what your script is doing.

PowerShell: "Get-Help Cannot find Help for topic" error with script Comment_Based_Help

Trying to retrieve help from a script gives the following error:
Get-Help : Cannot find Help for topic ".\Process-Test.ps1".
At line:1 char:9
+ get-help <<<< .\Process-Test.ps1
+ CategoryInfo : ResourceUnavailable: (:) [Get-Help], HelpNotFoundException
+ FullyQualifiedErrorId : HelpNotFound,Microsoft.PowerShell.Commands.GetHelpCommand
I've encountered the same error when attempting to retrieve help information from any custom PowerShell script. This does not happen when viewing help information from built-in cmdlets.
A test script is below:
<#
.SYNOPSIS
Adds a file name extension to a supplied name.
.DESCRIPTION
Adds a file name extension to a supplied name.
Takes any strings for the file name or extension.
.EXAMPLE
C:\PS> extension -name "File"
File.txt
#>
Write-Host "Test script"
Troubleshooting steps I've taken:
I've copied this script (or similar scripts) to other machines with PowerShell installed and used it to view help successfully.
I've also been able to view the help using a different account (User2) on my computer successfully, but only when logged in as the other user (versus running the PowerShell console as User2 when logged in as User1).
I've tried viewing the help with and without my PowerShell profile loaded, with the same result (I only have one profile loaded, my personal profile versus machine profiles).
I took this to be a sign that there was a problem with my Windows user profile, so I deleted my profile and re-created it with the same result. I've also tried running System Restore, with no change.
This happens in the PowerShell console along with the ISE.
Occurs when using both Get-Help as well as help.
I noticed, however, that my PowerShell console settings stayed consistent throughout deleting and re-creating my Windows user profile (height, width, colors, etc), which I wouldn't have expected since I deleted my user profile.
Since I'm using Windows 7, I'm not able to uninstall PowerShell and re-install as it's baked into the OS.
Google wasn't helpful for me in this case, but my google skills could be lacking. Any ideas as to further troubleshooting steps, or anyone who's seen this error before?
Edit: this only happens with the 64-bit version of the console and ISE, not with the 32-bit version, and persists through profile deletion
Have you tried to set execution policy?
Set-ExecutionPolicy -ExecutionPolicy remotesigned -Scope process
Then do Get-Help .\script.ps1.
I had the same problem. That was because my script was located on a networkshare in a DFS folder. So I am pointing to network file. When I copied the file locally, directly on the root of my C drive, and called the help option for my script with the normal get-help myscript.ps1 parameter, it worked!