Why are PowerShell Import-Module wildcards not working? - powershell

I have a few scripts where I import all VMware-Modules for simplicity. This has worked all the time - but now on one server it won't.
PS C:\Temp> Import-Module VMware.*
Import-Module : The specified module 'VMware.*' was not loaded because no valid module file was found in any module
directory.
At line:1 char:1
+ Import-Module VMware.*
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (VMware.*:String) [Import-Module], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
I just copied the modules to C:\Windows\System32\WindowsPowerShell\v1.0\Modules.
When I use the full name (Import-Module VMware.VimAutomation.Core) it works as usual.
How can I fix this? They appear correctly when I do a Get-Module -ListAvailable.

Import-Module doesn't support wildcards. What you could do, however, is get all the module names using Get-Module and then pipe them into a ForEach-Object command.
I believe this will achieve what you are after:
Get-Module -Name "VMWave.*" | ForEach-Object { Import-Module $_; Write-Host "Imported Module $_"}

Related

Can't publish script to PowerShell gallery, getting error

Publish-Script -Path "path-to-script.ps1" -NuGetApiKey 123456789
after doing that, I get this error in PowerShell 7.3:
Write-Error: Failed to generate the compressed file for script 'C:\Program Files\dotnet\dotnet.exe failed to pack: error '.
and I get this error in PowerShell 5.1:
Publish-PSArtifactUtility : Failed to generate the compressed file for script 'C:\Program Files\dotnet\dotnet.exe
failed to pack: error
'.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.2.5\PSModule.psm1:11338 char:17
+ ... Publish-PSArtifactUtility #PublishPSArtifactUtility_Param ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : FailedToCreateCompressedScript,Publish-PSArtifactUtility
my script has no dependency.
this problem has been going on for the past 2 weeks.
I even gave my script with API key to a friend from another country and they receive the same error too.
how can I fix this? I've published previous versions of this script before at least 6 times.
I've tried resetting my API key and running PowerShell as admin, didn't fix it.
Update:
I installed .NET 7 runtimes x64 and used this command from this answer on PowerShell 5.1:
# find the file having wrong .NET version
$path = Get-ChildItem (Get-Module PowerShellGet -ListAvailable).ModuleBase -Recurse -File |
Select-String -Pattern netcoreapp2.0 | ForEach-Object Path
# unload the module
Remove-Module PowerShellGet -Verbose -Force -EA 0
# update the file
$path | ForEach-Object {
(Get-Content -LiteralPath $_ -Raw).Replace('netcoreapp2.0', 'net7') |
Set-Content $_
}
Import-Module PowerShellGet -Force -Verbose
# now try to publish
but still getting error:
Publish-PSArtifactUtility : Failed to generate the compressed file for script 'C:\Program Files\dotnet\dotnet.exe
failed to pack: error
'.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.2.5\PSModule.psm1:11338 char:17
+ ... Publish-PSArtifactUtility #PublishPSArtifactUtility_Param ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : FailedToCreateCompressedScript,Publish-PSArtifactUtility
enter image description here
I fixed the problem by installing .NET Core 2.0 SDK
https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-2.1.202-windows-x64-installer

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

Powershell copy from linux samba to local windows server folder

I need to copy a file from a Linux samba server to various Windows Server 2008.
The shared folder has a specific login and is read-only.
I can access and copy the shared file using Windows Explorer without a problem.
But, when using PowerShell to copy the file, it always give an error as shown below.
I have tried using Copy-item, robocopy and bitstransfer but they all give an error.
$arq = "file.zip"
$downloadSource = "\\domain.or.ip\sharedfolder\$arq"
echo $downloadSource
Copy-Item -Path "$downloadSource" -Destination ".\$arqAgenteZabbix"
this method gives me the following error
Copy-Item : Access denied
CategoryInfo : PermissionDenied: (\domain.or.ip\sharedfolder\file.zip:String) [Copy-Item], UnauthorizedAc
cessException
FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand
...
Copy-Item: path not found...
So, I tried adding a credential parameter
$credencial = New-PSSession -ComputerName "serverhostname" -Credential "serverhostname\sharedfolder"
Copy-Item -Path "$downloadSource" -Destination ".\$arqAgenteZabbix" -ToSession $credencial
But received this error after typing my password:
"New-PSSession : [pxl0mon00013] Fail to connect to remote server >serverhostname ...
WinRM cannot process the request... error 0x80090311 ...
CategoryInfo : OpenError (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
gTransportException
FullyQualifiedErrorId : AuthenticationFailed,PSSessionOpenFailed
Then, I decided to give BitsTransfer a shot.
Import-Module bitstransfer
$arq = "file.zip"
$downloadSource = "\\domain.or.ip\sharedfolder\$arq"
Start-BitsTransfer -DisplayName DownloadName `
-TransferType Download `
-Source $downloadSource `
-Destination .\$arq
And it also gave me an error:
Start-BitsTransfer : path not found
'\domain.or.ip\sharedfolder\file.zip' does not exist.
CategoryInfo : ObjectNotFound: (\domain.or.ip\sharedfolder\file.zip:String) [Start-BitsTransfer], ParentC
ontainsErrorRecordException
FullyQualifiedErrorId : PathNotFound,Microsoft.BackgroundIntelligentTransfer.Management.NewBitsTransferCommand
How can I make this file copy, please?
EDIT - 20190403
I tried the following:
get-childitem \\domain.or.ip\sharedfolder\
which resulted in:
Get-ChildItem : Cannot find path '\\domain.or.ip\sharedfolder\' because it does not exist.
At line:1 char:3
+ ls <<<< \\domain.or.ip\sharedfolder\
+ CategoryInfo : ObjectNotFound: (\domain.or.ip\sharedfolder\:String) [Get-ChildItem], ItemNotFo
undException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
So, I opened Explorer and pasted \domain.or.ip\sharedfolder\ at the address bar. It asked me for username and password, then, the file was available.
After that, I returned to PowerShell and tried once again the same Get-ChildItem cmdlet. Then, I was able to list the shared folder contents as expected.
Directory: \\domain.or.ip\sharedfolder
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 01/04/2019 10:06 3896455 file.zip
Finally, I tried:
Copy-Item -Path \\domain.or.ip\sharedfolder\file.zip -Destination ".\file.zip"
And it was copied successfully.
Well, only after I entered my login information in Explorer that PowerShell was able to find the shared folder.
But I need it to copy without having to open explorer.
You can provide alternate credentials with Invoke-Command:
Invoke-Command -ScriptBlock {
$arq = "file.zip"
$downloadSource = "\\domain.or.ip\sharedfolder\$arq"
echo $downloadSource
Copy-Item -Path "$downloadSource" -Destination ".\$arqAgenteZabbix"
} -Credential $Cred
I finally managed to successfully copy the shared file in a relative simple way. I used "NET USE" command to open a session and copy the file, like shown below.
$arq = "file.zip"
$downloadSource = "\\domain.or.ip\sharedfolder"
net use $downloadSource /persistent:no /user:[user] [pass]
Copy-Item -Path "$downloadSource\$arq" -Destination ".\$arq"
net use $downloadSource /delete
Now, a new challenge... encrypt the clear-text password.

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"