I am trying to get network mapped drives using below commands.
Get-WmiObject -Class Win32_MappedLogicalDisk | %{$_.Name}
Get-WmiObject -Class Win32_MappedLogicalDisk | %{$_.ProviderName}
This works in some system however does not in other systems(may be powershell version issue) So I thought of using net use command. However, I am unable to fetch the values or not sure how to get the values displays when i type 'net use'
when I type net use I get status, Local, Remote and Network column. I tried to use the below command to get the field values.
net use | select local.
but I get blank or nothing
Used below command.
net use | select local.
Need to get Local and Remote values from net use command.
See this for parsing legacy console output ---
How to Convert Text Output of a Legacy Console Application to PowerShell Objects
Yet, along with what LotPings gave you already. Your query could be a duplicate of this ...
Equivalent of net use (to list computer's connections) in powershell?
... and it's accepted answer
# For the mapped logical drive you can use WMI class Win32_MappedLogicalDisk :
Get-WmiObject Win32_MappedLogicalDisk
# Here is another way with Win32_LogicalDisk :
PS C:\> Get-WmiObject -Query "Select * From Win32_LogicalDisk Where DriveType = 4"
DeviceID : V:
DriveType : 4
ProviderName : \\jpbdellf1\c$
FreeSpace :
Size :
VolumeName :
# Edited
# You are right, you can get what you need with Win32_NetworkConnection :
Get-WmiObject Win32_NetworkConnection
LocalName RemoteName ConnectionState Status
--------- ---------- --------------- ------
\\jpbasusf1\temp Connected OK
# On Seven or W2K8 be careful to call this with the same user that run the NET USE because it's a session information.
How about using get-psdrive (the root header actually matches the displayroot property)?
get-psdrive | where displayroot -like '\\*'
Name Used (GB) Free (GB) Provider Root
---- --------- --------- -------- ----
Y 91.84 7.82 FileSystem \\server....
Depending on the PowerShell versions available you might encounter similar problems with
Get-SmbMapping which wraps the CimClass: ROOT/Microsoft/Windows/SMB:MSFT_SmbMapping.
But has otherwise an output resembling net use.
To process the real net use output and convert to an object with properties,
you may use:
$SmbMapping = (net use) -like '* \\*' | ForEach-Object {
$Status,$Local,$Remote,$Null = $_ -split ' +',4
[PSCustomObject]#{
Status = $Status
Local = $Local
Remote = $Remote
}
}
This works at least in my German locale Win10.
(Not sure about different status messages in other locales.)
Related
I have the following Powershell code to restore an Encryption key on a Power BI Report Server instance:
$encKeyPath = "C:\Test\enc.snk"
$encKeyPass = Read-Host 'Enter password for key:' -AsSecureString
Restore-RsEncryptionKey -ComputerName "localhost" -Password $encKeyPass -KeyPath $encKeyPath -ReportServerInstance PBIRS -ReportServerVersion SQLServer2016
When I run this I get the error:
Get-WmiObject : Invalid namespace "root\Microsoft\SqlServer\ReportServer\RS_PBIRS\v13\Admin"
At C:\Users\MyUser\Documents\WindowsPowerShell\Modules\ReportingServicesTools\ReportingServicesTools\Functions\Utilities\New-Rs
ConfigurationSettingObject.ps1:100 char:19
+ $wmiObjects = Get-WmiObject #getWmiObjectParameters
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
I have tried also tried with the -ReportServerInstance and -ReportServerVersion parameters but get the same error message. I have also tried my local computer name for the -ComputerName parameter rather than localhost but still had no luck.
The error seems to refer to an error in the actual module itself rather than my code. Can anyone suggest where I am going wrong?
Environment
Power BI Report Server version: 1.8.7450.37410 (May 2020)
Instance name: PBIRS
Report Manager URL: http://localhost/reports
Service URL: http://localhost/reportserver
ReportServer database is on a SQL Server 2016 instance (the database name is PowerBIReportServer)
EDIT:
Using the two answers so far, I have found the following:
Restore-RsEncryptionKey -ComputerName "localhost" -Password $encKeyPass -KeyPath $encKeyPath -ReportServerInstance PBIRS -ReportServerVersion SQLServer2016
Throws
Invalid namespace "root\Microsoft\SqlServer\ReportServer\RS_PBIRS\v13\Admin"
and changing the -ReportServerVersion:
Restore-RsEncryptionKey -ComputerName "localhost" -Password $encKeyPass -KeyPath $encKeyPath -ReportServerInstance PBIRS -ReportServerVersion SQLServer2017
Throws
Invalid namespace "root\Microsoft\SqlServer\ReportServer\RS_PBIRS\v14\Admin"
(note the difference in versions)
running
Get-WmiObject -Namespace "Root/Microsoft/SqlServer/ReportServer/RS_PBIRS" -Class __Namespace | Select-Object -Property Name | Sort Name
outputs:
Name
----
V15
which makes sense as to why the two different -ReportServerVersion arguments throw an error.
this page suggests
+--------------------+---------+
| SQL Server Release | Version |
+--------------------+---------+
| SQL Server 2012 | 11 |
| SQL Server 2014 | 12 |
| SQL Server 2016 | 13 |
| SQL Server 2017 | 14 |
| SQL Server 2019 | 15 |
+--------------------+---------+
but changing -ReportServerVersion to SQLServer2019 returns:
Restore-RSEncryptionKey : Cannot process argument transformation on parameter 'ReportServerVersion'. Cannot convert value
"SQLServer2019" to type "Microsoft.ReportingServicesTools.SqlServerVersion". Error: "Unable to match the identifier name
SQLServer2019 to a valid enumerator name. Specify one of the following enumerator names and try again:
SQLServer2012, SQLServer2014, SQLServer2016, SQLServer2017, SQLServervNext"
At line:3 char:143
From here then I suppose the question is:
How do I get the module to run v15 OR how do I get version 13 of the module / namespace?
The error is being thrown from the module, but it appears to be as a result of the data we're putting into the module. Let's dive into the code to see what's happening.
I found the source code of the module here. These lines towards the bottom (85 through 102) stuck out to me:
$getWmiObjectParameters = #{
ErrorAction = "Stop"
Namespace = "root\Microsoft\SqlServer\ReportServer\RS_$ReportServerInstance\v$($ReportServerVersion.Value__)\Admin"
Class = "MSReportServer_ConfigurationSetting"
}
# code snipped
$wmiObjects = Get-WmiObject #getWmiObjectParameters
Looking back at your error, the first line is noting "invalid namespace". If anything looks immediately off in "root\Microsoft\SqlServer\ReportServer\RS_PBIRS\v13\Admin" or your values for $ReportServerInstance or $($ReportServerVersion.Value__) then I'd change those.
If those look okay to you, I'd suggest you manually search through the available WMI namespaces on the target machine. First, we want to return all the child namespaces of root.
PS C:\windows\system32> Get-WmiObject -Namespace "Root" -Class __Namespace | Select-Object -Property Name | Sort Name
Name
----
Appv
cimv2
Hardware
HyperVCluster
Microsoft
WMI
Now that we have those, we can continue searching down the path that the module is expecting. We know from the module code, it's expecting to hit "Microsoft" in the namespace/path next so add that to the namespace we're searching child namespaces for:
PS C:\windows\system32> Get-WmiObject -Namespace "Root\Microsoft" -Class __Namespace | Select-Object -Property Name | Sort Name
Name
----
HomeNet
PolicyPlatform
protectionManagement
SecurityClient
Uev
Windows
I think if you continue down that line of logic, you'll run into the spot where the module is expecting a child WMI namespace, but the target machine lacks it.
Hope this was helpful and good luck!
****Update:
To answer the new question 'How do I get the module to run v15 OR how do I get version 13 of the module / namespace?'
The example use of the cmdlet shows use of the 2-digit report server version so I'd have you try this:
Restore-RsEncryptionKey -ComputerName "localhost" -Password $encKeyPass -KeyPath $encKeyPath -ReportServerInstance PBIRS -ReportServerVersion '15'
If that returns the same error, try Connect-RsReportServer. Module documentation notes it will set/update the parameter ReportServerVersion
.PARAMETER ReportServerVersion
Specify the version of the SQL Server Reporting Services Instance.
Use the "Connect-RsReportServer" function to set/update a default value.
To troubleshoot problems with the -ReportServerVersion parameter in the ReportingServicesTools module, resulting in namespace errors, you can use the following three quick steps:
Determine the SQL server versions your server supports (replace PBIRS by your actual ReportServerInstance, if different):
Get-WmiObject -Namespace "root\Microsoft\SqlServer\ReportServer\RS_PBIRS" -Class __Namespace | Select-Object -ExpandProperty Name
Example output:
V15
Display the current version to name mappings in ReportingServicesTools:
[enum]::GetValues([Microsoft.ReportingServicesTools.SqlServerVersion]) | % {[PSCustomObject]#{Name = $_;Version = $_.value__}}
Example output:
Name Version
---- -------
SQLServer2012 11
SQLServer2014 12
SQLServer2016 13
SQLServer2017 14
SQLServervNext 15
Map your supported server version to the corresponding name in the ReportingServicesTools module and use this name to pass it to the -ReportServerVersion parameter or pass the integer directly (after stripping the v).
I have a PID for which I want to check its username. I knew that we can use GetOwner(), but it is the valid method for Get-WmiObject Win32_Process. I am using Get-WmiObject -Class Win32_PerfRawData_PerfProc_Process in which there is no way to get username (as per I search online). So, I think to check PID separately is the only way to resolve this.
Can you please tell me how can I get the username of PID or get username inside Win32_PerfRawData_PerfProc_Process?
As it is described in this technet article :Technet you can use the code below.
In the last line you can put the process you want after the get-process command.
e.g. Get-Process outlook | select processname,Id,#{l="Owner";e={$owners[$_.id.tostring()]}}
$owners = #{}
gwmi win32_process |% {$owners[$_.handle] = $_.getowner().user}
Get-Process | select processname,Id,#{l="Owner";e={$owners[$_.id.tostring()]}}
The time it takes depends on how many services are currently running.
Your output will be like:
ProcessName Id Owner
----------- -- -----
OUTLOOK 13128 UserName
Hope that helps.
Kind regards.
I'm trying to write a script that depends on knowing the names of the computers on a network segment, but all the scripts I've found depend on a DNS inquiry which only replys with the names of a few of the machines. For example:
[System.Net.Dns]::GetHostbyAddress($IPAddress)
I've also tried using
Ping -a $ipaddress
but this often fails to return the machine name as well. Is there a way to ask the host what it's name is directly and what level of permissions might be required in AD to get a response?
Thanks in advance.
[System.Net.DNS]::GetHostByAddress() (now [System.Net.DNS]::GetHostEntry()) doesn't only rely on DNS, despite it's name. It will also check the local C:\Windows\System32\Drivers\etc\hosts file for locally configured entries.
straight dns via nslookup can't find the name:
PS C:\Users\Tim> nslookup 192.168.1.50
Server: dns03
Address: 192.168.2.103
*** rpi03 can't find 192.168.1.50: Non-existent domain
yet, gethostentry() still finds the name:
PS C:\Users\Tim> [system.net.dns]::gethostentry('192.168.1.50')
HostName Aliases AddressList
-------- ------- -----------
localentry {} {192.168.1.50}
COMMAND:
wmic.exe /node:10.20.30.40 OS get CSName /format:list
BATCH FILE FOR WHOLE SUBNET:
for /L %%z in (1,1,254) do wmic.exe /node:10.20.30.%%z OS get CSName /format:list 2>NUL
You can try by using something like:
Invoke-Command -computername $computer {Get-Item HKLM:\SYSTEM\ControlSet001\Control\ComputerName\ActiveComputerName}
The active computername is equal to your DNS name (without suffix ofcourse)
I may misunderstand the problem but you can query the Win32_ComputerSystem instance using a CIM session to the remote computer and use one of those properties (Name, DNSName, etc.) Running locally it would be like
Get-CimInstance -namespace root/cimv2 -classname Win32_ComputerSystem | fl *
I'm aware that WMI might take fairly hefty permissions (e.g., domain admin) but (a) that might not be out of the question for your use case and (b) you might be able to do some limited querying with fewer permissions.
Another idea might be to query your SCCM server if you have one:
(Get-WmiObject -Query "SELECT * from SMS_R_SYSTEM WHERE IPAddresses LIKE '%$ipaddress%'" -Namespace "root\sms\site_$SiteCode" -computerName $SCCMServer).Name
Another idea using powershell:
Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer -Property Name | ForEach-Object {$_.Name}
Where $Computer is an IP address
We have an environment with different domains and forests with and without trusts.
I need to manage the license for these with out KMS.
I want to find out the servers which are running without activated or with Grace period.
I have been trying with differnt scripts from WMIC and Powershell. But, not able to generate with clear and clean.
Below are the scripts tried. I need assistance on this.
From WMIC:
WMIC /Output:#D:\output.txt /node:#D:\serverslist.txt PATH SoftwareLicensingProduct WHERE "ProductKeyID like '%-%' AND Description like '%Windows%'" get LicenseStatus
From Powershell:
PS C:\Windows\system32> Get-CimInstance -ClassName SoftwareLicensingProduct |where PartialProductKey |select PScomputername,LicenseStatus
I need help to generate a table with computer name/IP and license status.
Thanks in advance.
Here you go, I just made a few tweaks.
For one, your code returns the LicenseStatus as a number...which is OK, but to get some real wow-factor, I consulted this chart from MSDN on what the numbers mean, and used that with a Switch Statement, within a Calulated Property to replace the number with the human-meaningful license status, giving us logic like this:
select Pscomputername,Name,#{Name='LicenseStatus';Exp={
switch ($_.LicenseStatus)
{
0 {'Unlicensed'}
1 {'licensed'}
2 {'OOBGrace'}
3 {'OOTGrace'}
4 {'NonGenuineGrace'}
5 {'Notification'}
6 {'ExtendedGrace'}
Default {'Undetected'}
}
#EndofCalulatedProperty
}}
This gives us full code, like this, and also extracts the name of the product as well. You can run this against multiple systems by just adding their names to the -ComputerName property:
Get-CimInstance -ClassName SoftwareLicensingProduct -computerName localhost,dc01,windows10 |
where PartialProductKey | select Pscomputername,Name,#{Name='LicenseStatus';Exp={
switch ($_.LicenseStatus)
{
0 {'Unlicensed'}
1 {'licensed'}
2 {'OOBGrace'}
3 {'OOTGrace'}
4 {'NonGenuineGrace'}
5 {'Notification'}
6 {'ExtendedGrace'}
Default {'Undetected'}
}
#EndOfCaltulatedProperty
}}
This gives you results like this:
PSComputerName Name LicenseStatus
-------------- ---- -------------
localhost Office 15, OfficeProPlusVL_MAK edition licensed
localhost Windows(R), ServerDatacenter edition licensed
dc01 Windows(R), ServerStandard edition licensed
Windows10 Windows(R), ServerStandard edition licensed
you may also try
$activation = (Get-CimInstance -ClassName SoftwareLicensingProduct | where ApplicationId -EQ 55c92734-d682-4d71-983e-d6ec3f16059f | where PartialProductKey).LicenseStatus
Get-CimInstance -ClassName SoftwareLicensingProduct |
where PartialProductKey |
select Name, ApplicationId, LicenseStatus
When I run the qwinsta /server:somesrv command in cmd I can get a listing of all the current RDP sessions that are logged into a particular Windows server.
SESSIONNAME USERNAME ID STATE TYPE DEVICE
console 0 Conn wdcon
rdp-tcp 65536 Listen rdpwd
rdp-tcp#594 tom1 1 Active rdpwd
rdp-tcp#595 bob1 2 Active rdpwd
Is it possible to get a list like this on a remote server from Powershell so that the data can be used elsewhere?
There are multiple alternatives:
Use the Terminal Services PowerShell Module. Easy solution.
Writing a powershell wrapper that parses the output of qwinsta to objects. Easy solution. See example below
Use the Cassia.DLL .Net wrapper to access the native APIs that qwinsta runs behind the scene. This is the class that the TS Module uses. More difficult, but will have the benefit of being customized to your needs.
Go crazy and use the Native Methods that Cassia.DLL accesses using P/Invoke (wtsapi32.dll, kernel32.dll, winsta.dll). Hard and overcomplicated.
PowerShell-wrapper for qwinsta
function Get-TSSessions {
param(
$ComputerName = "localhost"
)
qwinsta /server:$ComputerName |
#Parse output
ForEach-Object {
$_.Trim() -replace "\s+",","
} |
#Convert to objects
ConvertFrom-Csv
}
Get-TSSessions -ComputerName "localhost" | ft -AutoSize
SESSIONNAME USERNAME ID STATE TYPE DEVICE
----------- -------- -- ----- ---- ------
services 0 Disc
console Frode 1 Active
rdp-tcp 65537 Listen
#This is objects, so we can manipulate the results to get the info we want. Active sessions only:
Get-TSSessions -ComputerName "localhost" | ? { $_.State -eq 'Active' } | ft -AutoSize SessionName, UserName, ID
SESSIONNAME USERNAME ID
----------- -------- --
console Frode 1
I used to use Terminal Services PowerShell Module (now in codeplex archive), but it was two years ago. I can't put my hand on it, but it also exists a function on gitshub or another site that embeded QWinsta/RmWinsta.