Where is the best place to Add-PSSnapin SqlServerCmdletSnapin* and SqlServerProviderSnapin*? - powershell

I created some psm1 files and I put the following lines at the top of every psm1 file,
Set-StrictMode -Version 2
Add-PSSnapin SqlServerCmdletSnapin*
Add-PSSnapin SqlServerProviderSnapin*
However, it got warning of
WARNING: The names of some imported commands from the module 'mymodule' include unapproved verbs that might make them
less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose
parameter. For a list of approved verbs, type Get-Verb.
And it got the following error if import the modules multiple times.
Add-PSSnapin : An item with the same key has already been added.
At line:1 char:1
+ Add-PSSnapin SqlServerCmdletSnapin*
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-PSSnapin], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.AddPSSnapinCommand
Add-PSSnapin : An item with the same key has already been added.
At line:2 char:1
+ Add-PSSnapin SqlServerProviderSnapin*
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-PSSnapin], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.AddPSSnapinCommand
Or is there a way make these snapins loaded for every users when the system is booted?

The warning simply says that authors of SqlServerCmdletSnapin and SqlServerProviderSnapin used some 'unapproved' names for their functions. But these functions will work just fine, though MS thinks they can be 'less discoverable' (when user search commands like writing "Get-" and pressing Tab-Tab-Tab... from PS console).
So you are right to put them on the top, just add -ErrorAction SilentlyContinue to get rid of the warning:
Add-PSSnapin SqlServerCmdletSnapin* -ErrorAction SilentlyContinue
Add-PSSnapin SqlServerProviderSnapin* -ErrorAction SilentlyContinue
As for loading these snapins for every user, there are several options to do that using profiles. Read Understanding the Six PowerShell Profiles article.

Related

PowerShell PackageManagement - How to uninstall a package provider?

Troubleshooting i tried uninstalling nuget. NuGetProvider-2.8.5.208.dll to be specific.
I have never worked with Power Shell before and am totally lost.
I found this question that helped me find nuget and create a command to delete it.
But I'm unable to follow through.
I did start powershell as administrator.
Here the input:
(Get-PackageProvider|where-object{$_.name -eq "nuget"}).ProviderPath|Remove-Item -force Restart-Computer
The error message:
Remove-Item : The input object cannot be bound to any parameters of the command because the command does not accept pipeline input or the input and its properties do not match any of the parameters that accept pipeline input.
and its properties do not match any of the parameters that accept pipeline input.
line:1 character:70
+ ... _.name -eq "nuget"}).ProviderPath|Remove-Item -force Restart-Computer
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (C:\Users\XXX ...GetProvider.dll:String) [Remove-Item], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.RemoveItemCommand
How can i solve this and successfully uninstall it?
Thanks for your answer!
Still no luck. Here the error:
Remove-Item : The element C:\Users\XXX\AppData\Local\PackageManagement\ProviderAssemblies\nuget\2.8.5.208
\Microsoft.PackageManagement.NuGetProvider.dll cannot be removed: Access to the path "C:\Users\XXX\AppData\Local\PackageManagement\ProviderAssemblies\nuget\2.8.5.208\Microsoft.PackageManagement.NuGetProvide
r.dll" denied.
Line:1 Character:44
+ (Get-PackageProvider NuGet).ProviderPath | Remove-Item -Force
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\Users\XXX ...GetProvider.dll:FileInfo) [Remove-Item], Unauthoriz
edAccessException
+ FullyQualifiedErrorId : RemoveFileSystemItemUnAuthorizedAccess,Microsoft.PowerShell.Commands.RemoveItemCommand

Powershell not always running ScriptsToProcess on import

After using Install-Module to install powershell-yaml I had about a week of use before I came in one morning to it not loading YamlDotNet properly.
Now if I try to use ConvertFrom-Yaml before manually running Import-Module powershell-yaml I get the the following error:
PS C:\Users\user> "---" | ConvertFrom-Yaml
New-Object : Cannot find type [YamlDotNet.RepresentationModel.YamlStream]: verify that the assembly containing this type is loaded.
At C:\Program Files\WindowsPowerShell\Modules\powershell-yaml\0.3.1\powershell-yaml.psm1:24 char:23
+ ... $yamlStream = New-Object "YamlDotNet.RepresentationModel.YamlStream"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At C:\Program Files\WindowsPowerShell\Modules\powershell-yaml\0.3.1\powershell-yaml.psm1:25 char:9
+ $yamlStream.Load([System.IO.TextReader] $stringReader)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Previously (and on most systems) this worked fine. If I run a manual Import-Module before calling the function it works fine:
PS C:\Users\user> Import-Module powershell-yaml
PS C:\Users\user> "---" | ConvertFrom-Yaml
PS C:\Users\user>
Both my and a coworker's machines started this behavior at about the same time. This morning my system started working properly again, but his is still exhibiting the behavior. We haven't been able to duplicate it on other machines.
I've narrowed it down to a script referenced in Powershell-Yaml manifest's ScriptsToProcess not being called during autoload, but runs fine during a manual Import-Module. On working machines the script in ScriptsToProcess is run in both cases. As a workaround we can force a module load by putting an Import-Module in our profile, ideally we'd like to find a root cause.
Import-Module -Verbose doesn't help, because calling Import-Module first always works.

Set the font type and size using the command prompt (or batch file)

I tried the solution given from: Specify the size of command prompt when executing a batch file
I ran:
powershell -command "&{set-executionpolicy remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize}"
But I get these errors, any ideas?
Set-ExecutionPolicy : Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. At line:1 char:22 + &{set-executionpolicy <<<< remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize} + CategoryInfo : NotSpecified: (:) [Set-ExecutionPolicy], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand
Import-Module : The specified module 'SetConsoleFont' was not loaded because no valid module file was found in any module directory . At line:1 char:50 + &{set-executionpolicy remotesigned; Import-Module <<<< SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize} + CategoryInfo : ResourceUnavailable: (SetConsoleFont:String) [Import-Module], FileNotFoundException + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
The term 'Get-ConsoleFontInfo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spe lling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:86 + &{set-executionpolicy remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo <<<< | Format-Table -AutoSize} + CategoryInfo : ObjectNotFound: (Get-ConsoleFontInfo:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
I have put the file SetConsoleFont.psm1 in
C:\Users\Adrian\Documents\WindowsPowerShell\Modules\SetConsoleFont
You say "You're not allowed to set the execution policy" well maybe I'm not, but it's my machine so why shouldn't I? I don't want to execute these commands as Administrator, just as a user, me (Adrian)
Another comment was to try set-executionpolicy bypass process
so I tried:
powershell -command "&{set-executionpolicy bypass process; set-executionpolicy remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize}"
But got even more red errors.
I have no idea what powershell is or how to use it, I just want to change the font from a batch file without hassle!
Try set-executionpolicy bypass process instead.
Also make sure you have put the module in a module path folder such as:
[yourprofile]\Documents\WindowsPowershell\Modules
I managed to get it working but only in a PowerShell console, and I had to run it as Administrator. However this is not practical for me for the following reasons:
I wish to change the font of new window seamlessly from a batch file, which will be run by users of the software. They may not have Administrator access and so cannot execute "set-executionpolicy remotesigned" which I needed to do to get it working.
Also this has to be done in a DOS batch file, so opening up a powershell window is not an option. It only works in a PowerShell window and not with the DOS "powershell -command" option.
So a partial answer.
If you want to change Execution Policy, it should be done in an elevated prompt.
And loading the module can be done by giving absolute path. Example is below.
Import-Module c:\users\testuser\desktop\SetConsoleFont.psm1 -Verbose
and we can bypass execution policy like below.
powershell.exe -executionpolicy bypass -command "${<your code>}"
Edit: The imported module will be available only in the scope of the script block.
here it is with in {}. So whatever cmdlets and functions in side the module should be executed in sided the scriptblock.
Regards,
Kvprasoon

Import-Module stops working sporadically

I have a problem where Import-Module -Name "./MyAssembly.dll" stops working sporadically. If I restart the computer, everything seems to work as normal for a while, but it's getting really frustrating.
The reason for importing the same module (in different Powershell sessions) is because I'm currently writing a cmdlet using C#, and I start a powershell instance as part of debugging the cmdlet.
The Import-Module command gives me no feedback whatsoever of whether or not the loading succeeded.
PS C:\Source\MyProject> Import-Module -Name "./MyAssembly.dll"
PS C:\Source\MyProject> Get-Stuffz
Get-Stuffz : The term 'Get-Stuffz' is not recognized as the name of a cmdlet, function, script file, or ope
rable 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
+ Get-Stuffz
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-Stuffz:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Any help or suggestions are welcome.

Can't run my own powershell Cmdlet because access to "Templates" folder is denied?

I'm starting out with Powershell, and I'm having a strange error that I can't find much details about with our friend Mr. Google.
And before you ask, yes, I am definitely running Powershell as an Administrator.
I created a simple Cmdlet that counts files of a specified extension in the current directory.
I can build and run installutil fine.
I can see the snap-in when I Call Get-PSSnapin -Registered, and I can add it using Add-PSSnapin
But when I run my cmdlet, I get the following error:
PS C:\work\Enterprise> Get-PSSnapin -Registered
Name : FileCountCmdlet
PSVersion : 2.0
Description : Returns a file count
PS C:\work\> Add-PSSnapin FileCountCmdlet
PS C:\work\> Get-FileCount
Get-FileCount : Access to the path 'C:\Users\{My-User-Name}\Templates' is denied.
At line:1 char:14
+ Get-FileCount <<<<
+ CategoryInfo : NotSpecified: (:) [Get-FileCount], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,FileCount.FileCountCmdlet
Any thoughts or help would be greatly appreciated!
It sounds like you might be running into what this link describes:
Junction Points
http://www.svrops.com/svrops/articles/jpoints.htm
If so, you'll need to update your cmdlet to skip over these junction points.