powershell failing to import module - powershell

I am working with powershell on a server and want to use it to stop and start a task in the task scheduler. I run this command "Import-Module TaskScheduler" but get an error:
Import-Module : The specified module 'TaskScheduler' was not loaded because no valid module file was found in any module directory.
Any idea of the problem?

The most likely case is that you've got your module installed to a personal location, and not a system location. If you're running it inside of a scheduled task, or have it installed for a particular user (and are running as someone else), then you'll need to make sure that the module is in the "right" location.
$env:PSModulePath
Will show the current module paths. There should be at least 2. One will be in your user directory, and the other will be in $pshome\Modules.
If you want to be lazy, you can put a module there. If you want to be thorough, you can create a new directory, change PSModulePath (outside of PowerShell, so it sticks from one PowerShell instance to the next) to include this directory. This is the "official" way.
On a personal note, since you're probably using the very old TaskScheduler module I wrote in the PowerShellPack, I'm sorry that my installer drops them into user directories, and not global directories. While user directories are the common case, global directories should have been an option.

I had the same issue and my module was in the correct location, and everything was named according to the expected convention. After a bit of frustration I figured out the issue: the window that I was trying to import the module in was launched before I created the module. When I launched a new instance of Powershell, it loaded. So hopefully this might help someone else who is having this same issue and can't figure out why.
You can also add the location of the Powershell modules to the module path:
$env:PSModulePath=$env:PSModulePath + ";" + "F:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules"
Or you can add logic to an existing script:
$module_path = $env:PSModulePath
if (-not($module_path -match "F:\\Program Files (x86)\\Microsoft SQL Server\\110\\Tools\\PowerShell\\Modules")) {
if (Test-Path("F:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules")) {
$env:PSModulePath=$env:PSModulePath + ";" + "F:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules"
}
else {
write-host "sqlps not in default location - this can cause errors" -foregroundcolor yellow
}
}
import-module "sqlps" -DisableNameChecking

Related

PowerShell module installed manually. cmdlets found with help but not recognized when executed

I have a machine i would like to install a module on, specifically SwisPowerShell for working with SolarWinds. Internet is disabled on it so i cant use install-module, so i manually downloaded the .nupkg from another machine and went through the steps of unpacking the files into the correct folders. https://learn.microsoft.com/en-us/powershell/scripting/gallery/how-to/working-with-packages/manual-download?view=powershell-7.2. all the .dll files and the windows powershell datafile i have tried in both directories "C:\Program Files\WindowsPowerShell\Modules\SwisPowerShell\3.1.0.343" and "C:\Users\username\Documents\WindowsPowerShell\Modules\SwisPowerShell\3.1.0.343". Importing the module with "import-module -name SwisPowerShell -Global -force -Verbose" shows that everything loads correctly, but then running "get-module SwisPowerShell -Verbose" returns nothing. even loading each dll individually with "add-type -path "C:...\somefile.dll" shows nothing. running "get-module -ListAvailable" shows the module in both (or either) directories as they should be. using "get-help cmdletname" and "get-command cmdletname" shows the correct cmdlet definitions. trying to run any of the cmdlets returns "The term 'connect-swis' is not recognized as the name of a cmdlet, function... yada yadda" for all of the cmdlets. its like powershell sees the files but refuses to use them. Am i missing a step that tells powershell that this is a valid module to use? could it be blocked somehow? what extra steps does install-module do that a manual install does not that i could try?
Try running process monitor while installing on another machine. You might find out it's doing some registry changes too.

PowerShell Install Module command not failing but not installing module

I am trying to install the PnP online commands for SharePoint onto my PowerShell however the following command doesn't seem to work;
Install-Module -name SharePointPnPPowerShellOnline -scope CurrentUser
The command seems to run through fine with no errors appearing but when I try to run Commands which should have been installed I get an error saying the commands can not be found.
connect-pnponline : The term 'connect-pnponline' 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:1 char:1
+ connect-pnponline
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (connect-pnponline:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I have had a look at all the module folders and the module is not in any of them. I have compared my environment paths with a coworker who has this working and they are the same.
Does anyone know what might be causing this?
This was caused by by modules being stored on OneDrive. By default my module path was set to "%USERPROFILE%\Documents\WindowsPowerShell\Modules" but since i had OneDrive installed my path changed to "%USERPROFILE%\OneDrive\Documents\WindowsPowerShell\Modules".
To resolve this issue I went to Documents>Windows Powershell>Modules and copied the link. Then, via the Start' menu, I went to 'Edit the system environment variables'>advanced>Environment Variables, highlighted PSModulePath and clicked Edit.
Once in this window I clicked New and pasted the link I found above.
This resolved the problem I was experiencing.
The module probably isn't imported. You should be able to executeImport-Module SharePointPnPPowerShellOnline which should either import your module, or give you an error if it can't be imported for some reason.
To tackle the non-autoloading issue, check the following:
Check that you're setting $PSModuleAutoLoadingPreference and that it's not set to None or 0
Cmdlets which make use of a PowerShell provider do not get automatically imported
SharePointPnPPowerShellOnline implements a SharePoint provider so I'd wager this is the case.
I had the same symptom The term '' is not recognized..., but a different fix.
When I checked $ENV:PSModulePath in Windows Powershell (this problem was not present in pwsh powershell core), I saw the expected folder C:\Users\cwalsh\OneDrive\Documents\WindowsPowerShell\Modules was missing:
Instead $ENV:PSModulePath was ;;C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\
The root cause was I had PSModulePath env var defined at both User-level as ; (this is not how my other PC is set up), and at System-level as %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\. I guess unlike PATH this variable doesn't automatically concatenate both.
I deleted the user-level PSModulePath environment variable and now in a new process the module works as expected.
Onedrive syncing screwed up the files for MgGraph authentication.
one of the subfolders sync was broken he file was removed because "cloud" didnt know about it. Had to reinstall... Need to change the default location out of documents if you have onedrive so silly

Write to Profile File After Installing PowerShell Module with PowerShellGet

I have a custom PowerShell module with two cmdlets. I have it successfully, but manually, deployed on my machine. However, I deployed it by placing the binary file and module manifest in a location, and then registering the module. I also had to manually write an Import-Module command into my 'all users' profile.
Now I am sure I can deploy this module with Publish-Module, but how do I get the Install-Module to write the Import-Module statement to the profile file?
As of PowerShell 3.0, a module is automatically imported when a command from the module is invoked. This was a brilliant on Microsoft's part; however, it did require that modules are located in a location where PowerShell looks for modules by default. Makes sense. You can see those locations by running the following command:
$env:PSModulePath -split ';'
Is there a reason you'd rather not use one of the paths stored in the above environmental variable? That said, I'd keep your code out of the "C:\Windows\System32..." path. The other options are better: "C:\Program Files\PowerShell\Modules" (AllUsers) and "C:\Users\tommymaynard\Documents\PowerShell\Modules" (CurrentUser). Depending on your PowerShell version/OS, those path could be different. You won't need to write an Import-Module command into a $PROFILE script if you get the module into a preferred location. Maybe you already know this, but maybe not.
You're not going to get Install-Module to write to any of the $PROFILE scripts.
$PROFILE | Select-Object -Property *
Well, not by default anyway. You could write your own Install-Module function, that runs PowerShellGet's Install-Module function, and includes writing to various $PROFILE scripts. The problem is that you'll need to include logic so you don't blow away the contents of someone's $PROFILE script if it's not empty, and only append to it.
Seriously though, this is turning into a lot of work, when you could drop the module into a location where PowerShell can find it on its own.
Edit: It just occurred to me, you can add a value/path to the $env:PSModulePath environmental variable. It's a single string with semi-colon delimiters:
$env:PSModulePath.GetType().Name
Therefore, it'd look like this:
$env:PSModulePath += ';C:\Another\Path'
That's great and all, but again how might you stage this, right? It takes you back to the write-to-all-the-$PROFILE-scripts problem,... although you may be able to update the variable via Group Policy Preferences. Again, probably better to just relocate your module.

How can I set up a default powershell profile for all my co workers at work as simple as possible?

What do I want to achieve?
I have one ps1 file that has all of my functions inside. In the first step I want to convert it into a ps module. Then I want to have the following:
Colleague gets a script or bat he has to run ONCE. This will set his Modules Environment path $Env:PSModulePath to a path on a network drive everyone has access to
Copy and paste a custom profile.ps1 into the users %userprofile%\Documents\WindowsPowershell that imports the module
Every user should now have the powershell scripts I made available in their shell
How I tried to solve it
The way me and a colleague have set it up in the past is with this:
(we have a profile.ps1 file that does the following):
#set path for profile_loader.ps1
$path = "\\server\share\folderwithscripts";
#call profile_loader.ps1
. "$path"
Then this profile_loader.ps1 baiscally just loads tons of scripts (ps1 files) like this:
. "\\server\share\pathtoanotherscript.ps1
Line after line.
I don't like it and it is too complicated for my 25 other colleagues I want to set up in the future.
Question
What is the best way to achieve this? A good old .bat file that copy and past the ps1 file into their userprofile? Or is there a better way?
As someone who had their $profile wiped and set to a "company default", for the love of god, don't.
If you have to, then I suggest just creating a profile you want everyone to have with all your modules in a shared location, like your securely locked down Sysadmin folder.
Do psedit $proile.AllUsersAllHosts on your machine, modify that, then make a text file with all the hostnames you want to destroy with your own forced profile. Throw this in there to make it import your modules by default.
# Checks your server share for any PSM1 files, could change to include PS1 as well I suppose. Long name because its in a $Profile so ¯\_(ツ)_/¯
$ModulePathWithLongNameBecauseSomeoneMayUseThisInAnActualScript = Get-ChildItem -file -Recurse "\\server\share\" -Include "*.psm1"
# Sets module path for other adhoc module calls if they dont want to restart their Powershell
$env:PSModulePath = $env:PSModulePath + ";\\server\share\"
# Imports all PSM1 files from the ModulePath*
Foreach($psm in $ModulePathWithLongNameBecauseSomeoneMayUseThisInAnActualScript){
Import-Module "$($ModulePath.FullName)"
}
Run this on your machine to deliver your soul crushing $profile to your colleagues who may have had their own setup.
# Get a list of machines that your staff will use and throw them into a txt or csv etc.
$PCsForForcedProfile = Get-Content "\\server\share\PleaseNo.txt"
Foreach($Colleague in $PCsForForcedProfile){
Copy-Item "C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1" "\\$Colleague\C$\Windows\System32\WindowsPowerShell\v1.0\" -force
}

Powershell import-module doesn't find modules

I'm learning PowerShell and I'm trying to build my own module library.
I've written a simple module XMLHelpers.psm1 and put in my folder $home/WindowsPowerShell/Modules.
When I do:
import-module full_path_to_XMLHelpers.psm1
It works. But when I do:
import-module XMLHelpers
It doesn't work and I get the error:
Import-Module : The specified module 'xmlhelpers' was not loaded because no valid module file was found in any module directory.
I've checked that the environment variable PSModulePath contains this folder. As it is a network folder, I've also tried to move it to a local folder and to modify PSModulePath but without success
$env:PSModulePath=$env:PSModulePath+";"+'C:\local'
Any idea on what could cause this issue?
The module needs to be placed in a folder with the same name as the module. In your case:
$home/WindowsPowerShell/Modules/XMLHelpers/
The full path would be:
$home/WindowsPowerShell/Modules/XMLHelpers/XMLHelpers.psm1
You would then be able to do:
import-module XMLHelpers
1.This will search XMLHelpers/XMLHelpers.psm1 in current folder
Import-Module (Resolve-Path('XMLHelpers'))
2.This will search XMLHelpers.psm1 in current folder
Import-Module (Resolve-Path('XMLHelpers.psm1'))
I think that the Import-Module is trying to find the module in the default directory C:\Windows\System32\WindowsPowerShell\v1.0\Modules.
Try to put the full path, or copy it to C:\Windows\System32\WindowsPowerShell\v1.0\Modules
I experienced the same error and tried numerous things before I succeeded. The solution was to prepend the path of the script to the relative path of the module like this:
// Note that .Path will only be available during script-execution
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path
Import-Module $ScriptPath\Modules\Builder.psm1
Btw you should take a look at http://msdn.microsoft.com/en-us/library/dd878284(v=vs.85).aspx which states:
Beginning in Windows PowerShell 3.0, modules are imported automatically when any cmdlet or function in the module is used in a command. This feature works on any module in a directory that this included in the value of the PSModulePath environment variable ($env:PSModulePath)
I had this problem, but only in Visual Studio Code, not in ISE. Turns out I was using an x86 session in VSCode. I displayed the PowerShell Session Menu and switched to the x64 session, and all the modules began working without full paths. I am using Version 1.17.2, architecture x64 of VSCode. My modules were stored in the C:\Windows\System32\WindowsPowerShell\v1.0\Modules directory.
Some plugins require one to run as an Administrator and will not load unless one has those credentials active in the shell.
My finding with PS 5.0 on Windows 7: $ENV:PsModulePath has to end with a . This normally means it will load all modules in that path.
I'm not able to add a single module to $env:PsModulePath and get it to load with Import-Module ExampleModule. I have to use the full path to the module. e.g. C:\MyModules\ExampleModule. I am sure it used to work.
For example:
Say I have the modules:
C:\MyModules\ExampleModule
C:\MyModules\FishingModule
I need to add C:\MyModules\ to $env:PsModulePath, which will allow me to do
Import-Module ExampleModule
Import-Module FishingModule
If for some reason, I didn't want FishingModule, I thought I could add C:\MyModules\ExampleModule only (no trailing \), but this doesn't seem to work now. To load it, I have to Import-Module C:\MyModules\ExampleModule
Interestingly, in both cases, doing Get-Module -ListAvailable, shows the modules, but it won't import. Although, the module's cmdlets seem to work anyway.
AFAIK, to get the automatic import to work, one has to add the name of the function to FunctionsToExport in the manifest (.psd1) file. Adding FunctionsToExport = '*', breaks the auto load. You can still have Export-ModuleMember -Function * in the module file (.psm1).
These are my findings. Whether there's been a change or my computer is broken, remains to be seen. HTH
try with below on powershell:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
import-module [\path\]XMLHelpers.psm1
Instead of [] put the full path
Full explanation of this and that
First of all check Your account type,some imports are not allowed to normal partner accounts.