Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

VID, PID, Serial Number of USB HDD

$
0
0

Hi All,

I would like write a script to display and export (csv) VID, PID, Serial Number of USB HDDs. I have two scripts which does the job however I would like to merge them so there is only one script hence one cvs file so I don't have to merge them manually.


Script 1 Manufacturer,Description,DeviceID (VID & PID)

gwmi Win32_USBControllerDevice |%{[wmi]($_.Dependent)} | Sort Manufacturer,Description,DeviceID | Ft -GroupBy Manufacturer Description,Service,DeviceID | out-file c:\VidPid.csv


Script 2 Tag, Name, Manufacturer, Partitions, DeviceID, Model, Size, serialnumber

Get-WmiObject win32_diskdrive| Format-List Tag, Name, Manufacturer, Partitions, DeviceID, Model, Size, serialnumber | out-file c:\VidPid.csv

Thank you 

Kind regards



PowerShell get IP address based on first octet

$
0
0

Hi All,
I have the following code which will pull the IP address from my servers. What i am looking for is a way to grab just the IP addresses that start with 171.

Example:
$NICs = Get-CimInstance -Class Win32_NetworkAdapterConfiguration –CimSession $computer | where {$_.IPEnabled -eq $true }
$IP = $NICs.IPAddress

This will output the following
10.1.1.102
fe80::9424:cfd7:b92a:51da
171.100.2.4
fe70::8c1d:af2b:3bda:f289
169.254.1.95
fe70::c51:ebf2:a8e2:560

Looking to just output the address that starts with 171 to a varaible.

thanks in advanced for the help.
Gaz

Is it possible to list all servers with specific role installed using Powershell on Servers WS2012 and WS2008 ?

$
0
0

Hi,

I am wondering if I can list all servers which have print-server role installed. I have written script which is based on Get--Windowseature bat as far as I know It doesn't work on Windows 2008 as long as those servers don't have Server Manager role installed. I have a lot of servers so I cannot just install this role on all of them.

Maybe Invoke command? Or other command which works for both versions (2008 and 2012)

I will copy my script if you wish.

Any ideas?

Thanks in advance.

PowerShell Script Errors: "Cannot find path 'C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLProvider.Types.ps1xml' because it does not exist."

$
0
0

This error *appers* to occur on machines:

Do SQL 2008 Tools put something in the user's profile that would cause this?


Darwin ____________________ CSI:\> windows Put Apps On Win7 and Virtualization http://csi-windows.com/courses

Exchange - Setting a Retention Policy through Powershell on a folder that a user created themself

$
0
0

Does anyone know if it's possible to set retention policy tags upon folders that a user creates that falls inside their root mailbox?

Presently, we're using Exchange Online through Office365.

So, we have asked all users to create two folders that will sit in the root mailbox they own along the default folders (Inbox, Sent Items, etc.); the folders are called Keep 5 Years and Keep Indefinitely; all users have been instructed to create these folders exactly as named. I know there are default tags that are created in the default MRM policy that will fill these roles, but I am trying to find a way to set these particular tags upon the folders through PS scripting instead of relying upon the end users to set the tags upon the folders themselves; while far from difficult for the end user, I don't trust that all users will adhere to this request in a timely fashion and performing it behind-the-scenes through scripting would be preferred.

How to Get-WMIObject Win32_PnPEntity | where {$_.Name -like “USB Serial Port*”} by Model (label) of Unspecified Device

$
0
0

With PowerShell I ask the following:

Get-WMIObjectWin32_PnPEntity| where {$_.Name-like "USB Serial Port*"}|Format-TableName,Description,Manufacturer

The output brings me:

Name         : USB Serial Port (COM15)
Description  : USB Serial Port
Manufacturer : FTDI

Name         : USB Serial Port (COM10)
Description  : USB Serial Port
Manufacturer : FTDI

So I get two results with the difference in brackets. What I am looking for is to get COMxx but by the Model(label) displayed in Control Panel - Devices and Printers - Unspecified - an item Properties.

Is anyone of you who knows a way to solution? I will be appreciated for your help.


"Get-WmiObject not supported" when using WmiMonitorID class

$
0
0

I ran into an issue on remote systems when running a script that grabs system info. It works fine on my laptop, but for some reason, it fails to work on some remote systems. They are about 3-5 years old, so I assume they are missing something, but I could use some help trying to figure out how to fix it. Here is the simple code I use to get the Monitor info:

$monitors = gwmi -Class WmiMonitorID -Namespace 'root\wmi' -computername $computerName | Select @{ n = "Model"; e = { [System.Text.Encoding]::ASCII.GetString($_.UserFriendlyName -ne 00) } }

GPO Report with Security Filtering

$
0
0

Hi,

I'm trying to get a list of group policies and their respective security filtering.  I run the following command:

get-gppermissions -name "group policy name" -all | where {$_.permission -eq "GpoApply"}

and that gives me the security filtering for that particular group policy like this:

Trustee: security group name

TrusteeType: Group

Permission: gpoapply

Inherited: False

What I want is just the gp displayname, trustee and permission.  Using "select trustee, permission" gives me:

Microsoft.GroupPolicy.GPTrustee                      GpoApply

How can I get it such that it shows gp displayname, trustee displayname and permission?  And how do I do the same for an array containing a bunch of group policies, like $array = get-gpo | where ($_.displayname -like "*name*"}, then feed that to the get-gppermissions command.

Thanks.


PowerShell DSC xPendingReboot resource: Error

$
0
0

Hi there,

I am exploring the xPendingReboot DSC resource. I have the code at the bottom which installs the latest WMF build and tests for a reboot. However, I am getting the output instead:

VERBOSE: [WIN-P4A2GG3KMT4]: LCM:  [ Start  Resource ]  [[xPendingReboot]RebootCheck1]
VERBOSE: [WIN-P4A2GG3KMT4]: LCM:  [ Start  Test     ]  [[xPendingReboot]RebootCheck1]
WARNING: [WIN-P4A2GG3KMT4]:                            [[xPendingReboot]RebootCheck1] Unable to query CCM_ClientUtilities: Invalid namespace

In investigating the missing namespace via wmimgmt.msc I see that it does not natively exist in either Server 2012 R2 or server 2016. Further, it appears to be a function of System Center Config Manager client installation? We don't use System Center and so this error makes me wonder if I have missed a configuration step or if there is a depending on something else I have not fulfilled yet?

-John

Configuration NewServerConfig
{
    Import-DscResource –ModuleName 'xPSDesiredStateConfiguration'
    Import-DscResource -ModuleName 'xPendingReboot'

    Node localhost
    {

            Script InstallPowerShell5.x
            {

                GetScript = {
                    Return @{
                        Result = [string]$($PSVersionTable.PSVersion.Major)
                    }
                }


                SetScript = {
                    # Use shortcode to find latest TechNet download site
                    $confirmationPage = 'http://www.microsoft.com/en-us/download/' +  $((invoke-webrequest 'http://aka.ms/wmf5latest' -UseBasicParsing).links | ? Class -eq 'mscom-link download-button dl' | % href)
                    # Parse confirmation page and look for URL to file
                    $directURL = (invoke-webrequest $confirmationPage -UseBasicParsing).Links | ? Class -eq 'mscom-link' | ? href -match 'Win8.1AndW2K12R2-KB3134758-x64.msu' | % href | select -first 1
                    # Download file to local
                    $download = invoke-webrequest $directURL -OutFile $env:Temp\wmf5latest.msu

                    if (test-path $env:Temp\wmf5latest.msu)
                        {
                            start -wait $env:Temp\wmf5latest.msu -argumentlist '/quiet /norestart'
                        }
                    else
                        {
                            throw 'the update file is not available at the specified location'
                        }

                    Remove-Item $env:Temp\wmf5latest.msu

                    $global:DSCMachineStatus = 1

                }


                TestScript = {
                    if ($PSVersionTable.PSVersion.Major -eq 5)
                        {
                            Return $True
                        }
                }

            }

            # Reboot if pending
            xPendingReboot RebootCheck1
            {
                Name = "RebootCheck1"
            }



            LocalConfigurationManager

            {

                RebootNodeIfNeeded = $True

            }


    }

}

If ((test-path c:\temp) -eq $false)
{
    mkdir c:\temp
}

Set-Location c:\temp

NewServerConfig

Start-DscConfiguration -Verbose -wait -Path .\NewServerConfig -Force

Simple PS script for retrieving share printers

$
0
0

Hi all,

I would like to obtain a list of shared print queues across all of the print servers in my domain. Which are around 100.

My PS skill are basic, and because I wanted some very simple to execute, I used this:

Get-Printer -ComputerName xxxx | where shared -eq $true | Export-Csv -Path "c:\sharedprinters.csv"

This worked just fine. So now I wanted to simple duplicate this line for the 100 print servers. Which also worked fine. EXCEPT, that it only exports the last server results, even if powershell actually displays all results on the screen.

I know I should apply the export command as a separate line that would overarching all the Get-Printer results from the previous queries. But I dont know how to do this.

::::::

I know I could simplify my life and and do all of that with one line, by getting the server names from a txt. But from some reason, when I include more than one server name into the .txt file it fails (I am writing them in a row format with no symbols such as , or ; to separate the servernames).

The command tried is

$computernames = Get-Content -Path "c:\servers.txt"

Get-Printer -ComputerName $computernames | where shared -eq $true | Export-Csv -Path "c:\sharedprinters.csv"

This fails with message:

Get-Printer : Cannot process argument transformation on parameter 'ComputerName'. Cannot convert 
value to type System.String.
At line:2 char:27
+ Get-Printer -ComputerName $computernames | where shared -eq $true | Export-Csv - ...
+                           ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-Printer], ParameterBindingArgumentTransformatio 
   nException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-Printer

powershell Send-MailMessage : Mailbox unavailable. The server response was: 5.7.1 Unable to relay

$
0
0

Hi,

I have two domain..say abc.local and xyz.local

Send-MailMessage -From "a@abc.local" -To "x@xyz.local" -Subject $subject -Body $body $PSEmailServer -Credential $cred

while sending an E-mail from abc.local to xyz.local via powershell script, fails with error as: Send-MailMessage : Mailbox unavailable. The server response was: 5.7.1 Unable to relay

I searched and followed steps mentioned on http://blog.powerbiz.net.au/exchange/how-to-set-up-an-internal-smtp-service-for-windows-server-2012-essentials/

but no luck...FYI..IIS 6.0 Manager, SMTP virtual server instance is in stopped state and clicking on start button, getting message as "The service has retuned service specific error code. check event viewer for more details.."

Please help me


copy-item behaviour

$
0
0
PS C:\Windows\system32> Set-Content C:\test2\test "prova test2"
PS C:\Windows\system32> Get-Content C:\test1\test
prova test1
PS C:\Windows\system32> Get-Content C:\test2\test
prova test2
PS C:\Windows\system32> Copy-Item c:\test1 c:\test2 -recurse
PS C:\Windows\system32> Get-Content C:\test2\test
prova test2
PS C:\Windows\system32> Copy-Item c:\test1\* c:\test2 -recurse
PS C:\Windows\system32> Get-Content C:\test2\test
prova test1

As shown above, using "c:\test1" or "c:\test1\*" as source path does change the commandlet behaviour. Using the former path does not cause copy-item to overwrite destination files, using the latter the destination file is overwritten. 

I miss the logic behind that. Any hints?

Grazie, ciao.

How to get user details using UPN

$
0
0

Hello,

 

I want to get the user details using their UPN names without providing suffixes in the input file, so trying this cmd but not output, looks like variable is not taking, any idea please.

 
$USERS = Get-Content c:\temp\userlist.txt
Get-ADUser -filter {userprincipalname -like "$_.@*"} -properties * | Export-Csv output.txt

no results while running powershell using windows task scheduler

$
0
0

Hello,

I am trying to schedule a powershell code which accepts 4 parameters 1. folderpath 2. list of server seperated by semi colon 3. threshold an integer value 4. boolean variable (true/false)

Thing is, when I run this using cmd shell I am getting results as expected but when i run it using task scheduler no results are coming

Actions tab of the task is as below:

Program/Script:

c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe

Add arguments (optional): -command "& 'D:\script.ps1' 'd:\logs' 'srv1;srv2;srv3' 100 'true'"

any help is highly appreciated pl


Faizan

screen resolution

$
0
0

 We have a software app in our environment that "had" to have a set resolution.  The vendor has upgraded their software to a new version, which we now have and this new version does Not require a set screen resolution.   so we now have many computers that have jacked up resolutions when running this new software app.   I need to push out a script that fixes it.  

like most companies we have 19 inch up to 27 inch monitors in our environment.   I have found a few scripts that allow me to set a new screen resolution.  But how do I know or find out  via a PowerShell script what the recommended screen resolution is?  when you right click your desktop and change the resolution there is always one that says "recommended"  how can you find that information within a PS Script?


mqh7


How to allow distribution group to receive emails from external emails ?

$
0
0

Hello,

After few hours of searching such "checkbox" I found nothing.

The checkbox in "delivery management" Senders inside and outside of my organization is checked.

How to manage it in proper way ?

Thanks,

BR, Dimitriy

<input aria-labelledby="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1_label ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_label ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_fvaspan" id="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1" name="ctl00$ctl00$ResultPanePlaceHolder$EditMailGroup$deliveryManagementSection$contentContainer$rblRequireSenderAuthentication" style="font-family:'Segoe UI WPC Regular', 'Segoe UI', Tahoma, 'Microsoft Sans Serif', Verdana, sans-serif;font-size:12px;vertical-align:middle;float:left;clear:both;" type="radio" umc-skipdefaultlabelledby="true" value="false" /><label for="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1" id="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1_label" style="vertical-align:middle;padding-top:1px;float:left;cursor:pointer;width:263.156px;color:#666666;font-family:'Segoe UI WPC Regular', 'Segoe UI', Tahoma, 'Microsoft Sans Serif', Verdana, sans-serif;">Senders inside and outside of my organization</label>
<input aria-labelledby="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1_label ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_label ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_fvaspan" id="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1" name="ctl00$ctl00$ResultPanePlaceHolder$EditMailGroup$deliveryManagementSection$contentContainer$rblRequireSenderAuthentication" style="font-family:'Segoe UI WPC Regular', 'Segoe UI', Tahoma, 'Microsoft Sans Serif', Verdana, sans-serif;font-size:12px;vertical-align:middle;float:left;clear:both;" type="radio" umc-skipdefaultlabelledby="true" value="false" /><label for="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1" id="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1_label" style="vertical-align:middle;padding-top:1px;float:left;cursor:pointer;width:263.156px;color:#666666;font-family:'Segoe UI WPC Regular', 'Segoe UI', Tahoma, 'Microsoft Sans Serif', Verdana, sans-serif;">Senders inside and outside of my organization</label>
<input aria-labelledby="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1_label ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_label ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_fvaspan" id="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1" name="ctl00$ctl00$ResultPanePlaceHolder$EditMailGroup$deliveryManagementSection$contentContainer$rblRequireSenderAuthentication" style="font-family:'Segoe UI WPC Regular', 'Segoe UI', Tahoma, 'Microsoft Sans Serif', Verdana, sans-serif;font-size:12px;vertical-align:middle;float:left;clear:both;" type="radio" umc-skipdefaultlabelledby="true" value="false" /><label for="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1" id="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1_label" style="vertical-align:middle;padding-top:1px;float:left;cursor:pointer;width:263.156px;color:#666666;font-family:'Segoe UI WPC Regular', 'Segoe UI', Tahoma, 'Microsoft Sans Serif', Verdana, sans-serif;">Senders inside and outside of my organization</label>
<input aria-labelledby="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1_label ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_label ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_fvaspan" id="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1" name="ctl00$ctl00$ResultPanePlaceHolder$EditMailGroup$deliveryManagementSection$contentContainer$rblRequireSenderAuthentication" style="font-family:'Segoe UI WPC Regular', 'Segoe UI', Tahoma, 'Microsoft Sans Serif', Verdana, sans-serif;font-size:12px;vertical-align:middle;float:left;clear:both;" type="radio" umc-skipdefaultlabelledby="true" value="false" /><label for="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1" id="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1_label" style="vertical-align:middle;padding-top:1px;float:left;cursor:pointer;width:263.156px;color:#666666;font-family:'Segoe UI WPC Regular', 'Segoe UI', Tahoma, 'Microsoft Sans Serif', Verdana, sans-serif;">Senders inside and outside of my organization</label>
<input aria-labelledby="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1_label ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_label ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_fvaspan" id="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1" name="ctl00$ctl00$ResultPanePlaceHolder$EditMailGroup$deliveryManagementSection$contentContainer$rblRequireSenderAuthentication" style="font-family:'Segoe UI WPC Regular', 'Segoe UI', Tahoma, 'Microsoft Sans Serif', Verdana, sans-serif;font-size:12px;vertical-align:middle;float:left;clear:both;" type="radio" umc-skipdefaultlabelledby="true" value="false" /><label for="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1" id="ResultPanePlaceHolder_EditMailGroup_deliveryManagementSection_contentContainer_rblRequireSenderAuthentication_1_label" style="vertical-align:middle;padding-top:1px;float:left;cursor:pointer;width:263.156px;color:#666666;font-family:'Segoe UI WPC Regular', 'Segoe UI', Tahoma, 'Microsoft Sans Serif', Verdana, sans-serif;">Senders inside and outside of my organization</label>

Get-WmiObject Win32_Process and Csv File

$
0
0

Hi

I want to put only certain fields into a csv file, but the file seems to get some messed up data , so not sure on how to get this right.

Do I need to create a custom object and then pull the data from there, or is it something I'm doing?

****Working Code****

#This gets all the process data, which is fine, but now I want only certain fields 
function Myprocess
{
  Get-WmiObject Win32_Process | Export-Csv .\MyProcesses.csv -NoTypeInformation
  Get-Content .\MyProcesses.csv

}

If I Run the below Code, it the csv file gets messed up

****Failed Code****

function Myprocess
{
Get-WmiObject Win32_Process | Format-Table ProcessName, Handle, Handles, ThreadCount, ExecutablePath -AutoSize | Export-Csv .\MyProcesses.csv -NoTypeInformation
Get-Content .\MyProcesses.csv

}

This line works - but I want the data in a csv file

Get-WmiObject Win32_Process | Format-Table ProcessName, Handle, Handles, ThreadCount, ExecutablePath -AutoSize

Rgds

Dee


Dee

Powershell Script to Set the Location Attribute of a computer based on IP Address using a .CSV File

$
0
0

Hello

I am an IT Professional at my Company and we just got done doing a Domain Migration and Now are also deploying and deployed a bunch of new PCs (+500 or more) at 20 plus locations and I want to be able to set the location variable on each PC based on IP address. If Pcs have IP address of 172.23.12.XX then they are at *This Location* and so on. I would like to be able too do it in batches using a .csv file with all my IP addresses and Location Information in it

Please Help

ITTek5C

Get-WmiObject Win32_Process - Memory - WorkingSetSize

$
0
0

Hi

I Want to find out the memory used by the process's or service , Does anyone know if the property called

WorkingSetSize from the Get-WmiObject Win32_Process is the right one or do I need another object to look at?

Rgds

Dee


Dee

sql backup from list and exclude any OFFLINE databases

$
0
0

 

 I'm do a cleanup of old databases and marking them offline. I want my backup script to exclude offline
databases. How would I add a log that shows dbs that processed versus offline and not backed up. The script
currently in just using 2 databases one online and the other offline for testing.

 Thanks.

$assemblyInfo = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")
if ($assemblyInfo.GetName().Version.Major -ge 10)
{
# sql server version is 2008 or later, also load these other assemblies
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended') | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SQLWMIManagement') | Out-Null
}

$s = new-object ("Microsoft.SqlServer.Management.Smo.Server") "(local)" #this can also be "SERVERNAME\INSTANCENAME"

$bkdir = "c:\backup\" #We define the folder path as a variable
$dbstobackup = @(“StagingDatabase","Testing")

 try

  {

$dbs = $s.Databases
foreach ($db in $dbs)
{
if($dbstobackup -contains $db.Name)
 {
$dbname = $db.Name
$dt = get-date -format yyyyMMddHHmm
$dbBackup = new-object ("Microsoft.SqlServer.Management.Smo.Backup")
$dbBackup.Action = "Database"
$dbBackup.Database = $dbname
$dbBackup.Devices.AddDevice($bkdir + "\" + $dbname + "_db_" + $dt + ".bak", "File")

write-host $dbBackup.Status
$dbBackup.SqlBackup($s)

 }

}

  }

  catch [Exception]
    {
      echo $_.Exception|format-list -force

    }

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>