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

Need help with inherited powershell code

$
0
0

Hey all so I inherited this code at work. It is suppose to get information for desired computers where I work. However some of the things it tries to pull doesn't always work. The main one is the mac address.

Here's the code:

Function Get-Inventory {

PROCESS {
$ErrorActionPreference = "SilentlyContinue"

$os = Get-WmiObject Win32_OperatingSystem -EA silentlyContinue  –computer $_ 

$bios = Get-WmiObject Win32_BIOS -EA silentlyContinue –computer $_ 

$Network = Get-WmiObject win32_networkadapterconfiguration -EA silentlyContinue  -Filter 'DHCPEnabled = "true"' –computer $_

$make = get-wmiobject win32_computersystem -EA silentlyContinue  –computer $_

$processor = Get-WmiObject Win32_Processor -EA silentlyContinue  -computer $_

$mem = get-wmiobject win32_computersystem -EA silentlyContinue  -computer $_

$disk = Get-WmiObject Win32_LogicalDisk -EA silentlyContinue  -computerName $_ -Filter "DeviceID='C:'" |Select-Object Size,FreeSpace

$output = New-Object PSObject

$output | Add-Member NoteProperty ComputerName $_

$output | Add-Member NoteProperty MACAddress ($Network.MACAddress)

$output | Add-Member NoteProperty Model ($make.Model)

$output | Add-Member NoteProperty BIOSSerial ($bios.SerialNumber)

$output | Add-Member NoteProperty Processor ($processor.name)

$output | Add-Member NoteProperty Memory ([math]::round($mem.totalphysicalmemory/1GB))

$output | Add-Member NoteProperty LocalStorage ([math]::round($disk.Size)/1GB)

$output | Add-Member NoteProperty User ($make.username)

#$output | Add-Member NoteProperty SPVer ($os.ServicePackMajorVersion)

#$output | Add-Member NoteProperty BuildNo ($os.BuildNumber)

$output | Add-Member NoteProperty 32/64BitOS ($os.OSArchitecture)

Write-Output $output

}

}

So all this goes to an excel file.


Here's a snippet of what it out puts:

#TYPE System.Management.Automation.PSCustomObject								
ComputerName	MACAddress	Model	BIOSSerial	Processor	Memory	LocalStorage	User	32/64BitOS
CEIT2552210X023	System.Object[]	4524W1P	MJVBTR1	Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz	16	465.7597618		64-bit
CEIT2552210X033	System.Object[]	4524W1P	MJVBTV6	Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz	16	465.7597618		64-bit
CEIT2552210X014	System.Object[]	4524W1P	MJVBTR5	Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz	16	465.7597618		64-bit
CEIT2552210X018	System.Object[]	4524W1P	MJVBTP9	Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz	16	465.7597618		64-bit
CEIT2552210X015	System.Object[]	4524W1P	MJVBTR6	Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz	16	465.7597618		64-bit
CEIT2552210X025	System.Object[]	4524W1P	MJVBTP4	Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz	16	465.7597618		64-bit
CEIT2552210X036	System.Object[]	4524W1P	MJVBTT2	Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz	16	465.7597618		64-bit

So the problem is that where I need the mac address it says System.object. So does anyone know any functions that would work better to pull the macs.

Thanks like I said I really knew to powershell.


Robocopy Error 3 (System cannot find path specified) and Error 5 (Access Denied)?

$
0
0

So I am really new to Powershell and just yesterday learned about Robocopy.

I have been trying to find a solution to this problem:

I wrote a script in Powershell that is to simulate a "Backup". It  should copy files, using Robocopy, from user specified folders on a server to a user specified location elsewhere.

Right now, I have been testing it various ways.

1) One way I tried testing it was mapping the server's location as a network drive. I currently have it as drive V:\.
Whenever I run the script, I get this error:

Get-Item: Cannot find drive. A drive with the name 'V' does not exist.
ERROR 3 (0x00000003) Accessing Source Directory V:\
The System cannot find the path specified.

I'm using Robocopy like this: robocopy $spath $newFolder /COPY:DAT /b

2) The first time I tried test my script, I was trying to access directly to the server. $spath = \\###.###.##.###\
Whenver I tried this, this is the error I got:

Get-Item : Cannot find path '\\###.###.##.###\' because it does not exist.
ERROR 5 (0x00000005) Accessing Source Directory \\###.###.##.##\
Access is denied.


I am running Powershell as an administrator, on the administrator account on this computer (It's just for testing, but it's a Windows 7 desktop).
Any ideas?


Edit: The destination path is a hard drive that we have connected USB 2.0

Mapping network drive using PS V3.0 New-PSDrive -name "K" -PSProvider FileSystem -Root but have snag on passing credentials through

$
0
0

Hello,

I am creating a simple PowerShell v3.0 local logon script for all who logon that is running on W2K8 R2 SP1 server to map a persistent "K:" drive to a remote AD domain W2K8 R2 SP1 file server (no AD domain trust between the server mapping from and file server mapping to).  The PS v3.0 script will map but you have to manually enter a password.  I want to get it where the PS script can store the username and password so no user intervention is necessary to persistently map this network drive. Here is the simple PS v3.0 script which works but requires manually entering a password:

New-PSDrive -name "K" -PSProvider FileSystem -Root \\FileServer1\FileShare1\DeptFolder1 -Persist -Credential DOMAIN\%serviceaccountname% -Password %Password%

I don't know if there is a "-Password" parameter so if any PS expert can lead a novice like me to a script that can store credentials, I will be most grateful.  



Matt

More classes needed using get-wmiobject

$
0
0

Hi

I have been able to get some good information out using get-wmiobject, but I've run out of ideas.  Can anyone add to the list I have below to help me describe the machine.  Please note I want to describe what it is and not how it is being used at that point in time.  So for example total memory would be useful, but not memory being used or free memory.  I'm trying to think of more communication links or storage devices.  Anyway, the list i already have is:

  1.   Processor
  2.   PhysicalMemoryperformance
  3.   Diskdrive
  4.   USBhub
  5.   Networkadapter
  6.   Operatingsystem
  7.   Diskpartition
  8.   Videocontroller
  9.   BIOS

Many thanks

get-command/show-command error: Object reference not set to an instance of an object

$
0
0

I have started receiving the following error when running either the get-command or show-command commandlets in powershell v3.0

PS U:\> get-command
get-command : Object reference not set to an instance of an object.
At line:1 char:1
+ get-command
+ ~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-Command], NullReferenceException
    + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.GetCommandCommand
 

PS U:\> show-command
get-command : Object reference not set to an instance of an object.
At line:1 char:3
+ @(get-command -CommandType Cmdlet,Function,Script,ExternalScript,Workflow),@(get ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-Command], NullReferenceException
    + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.GetCommandCommand

Also, the "Commands" add-on is empty in Powershell ISE, and if I click the "Refresh" button, I receive the error:  Object reference not set to an instance of an object.

Thanks


Matt

Get-WMIOBJECT GUID

$
0
0

Hi

I'm trying to get the GUID information from my machine, but I don't know the script to get it.  Can anyone help?

Thanks

Nicktay

Form and Progressbar

$
0
0

Question 1:

I created a form. After click button on it to run script, the form cannot be dragged or moved until the script finished. Is there a way to move the form around while script running?

$Form = New-Object System.Windows.Forms.Form   
$Form.Size = New-Object System.Drawing.Size(370,340) 
$Form.StartPosition = "CenterScreen"

Question 2:

I added a progressbar on the form. It shows by default as green. I would like to be other color, blue & textbox like, but it is still green (on windows 7):

$ProgressBar1 = New-Object System.Windows.Forms.ProgressBar
$ProgressBar1.Location = new-object System.Drawing.Point(36, 245)
$ProgressBar1.Size = New-Object System.Drawing.Size(285, 20)
$ProgressBar1.ForeColor = 'Blue'
$Form.Controls.Add($ProgressBar1)

Update-TypeData: how to make NoteProperty read/write?

$
0
0
$obj=New-Object -TypeName datetime
$obj|Update-TypeData -MemberType NoteProperty -MemberName Probability -Value 100

$obj.Probability=0 # Error! How to make it read/write?


Powershell Memory Usage - Leakage?

$
0
0

Hi,

I am having an issue with a long running powershell script with a the memory increasing over time, like a leak. I am creating collection variables but after doing a connection to sql. Later on I am writing the output to a CSV file. However in my functions I am setting the collection variables to $null. But the memory keeps going up and up.

Is there something special I am missing on how powershell frees it memory. So for example if I call function a and I have a variable called $test should the memory be free for what was allocated to that function.

So is there any general advice somebody can offer how powershell allocates and frees it's memory, or any other advice that you can offer?

I am even calling the GC::Collect() and it is still not helping

thanks,

Ward

Here is  simplified version of the code I am using:

function Test1($machine_list)

$data_list = @()

foreach ($pc in $machine_list)
{
	$obj = New-Object System.Object
	$obj | Add-Member -MemberType NoteProperty Data1 $pc
	$obj | Add-Member -MemberType NoteProperty Data2 $pc
	$obj | Add-Member -MemberType NoteProperty Data3 $pc
	$data_list += $obj
}

$data_list | Export-Csv c:\scripts\test.txt -notype

$data_list = $null
}

$machine_list = @()

#select Name from Table where ProductID = 'XX'

# Then put each Name into a machine_list variable.

Test1 $machine_list



Handling plan_handle with varbinary data type in PowerShell

$
0
0

Hi,

I have a problem handling a varbinary column in PowerShell.

I am reading up some plan handles into a dataset. The plan_handle is varbinary(64) in SQL Server. Then I am trying to call a function in SQL Server for each plan handle.

  $SqlTargetConnection.Open()
   $SqlCmdPlanHandlesGet = New-Object System.Data.SqlClient.SqlCommand("SELECT plan_handle FROM dbo.QueryPlans",$SqlTargetConnection)
   $SqlCmdPlanHandlesGet.CommandTimeout = 30
   $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($SqlCmdPlanHandlesGet)
   $DataSet = New-Object System.Data.DataSet
   $SqlAdapter.Fill($DataSet)
   $SqlTargetConnection.Close()

  $DataTable = new-object "System.Data.DataTable"
  $DataTable = $DataSet.Tables[0]

  #Add new columns
   $ColumnQueryPlan = New-Object System.Data.DataColumn query_plan,([string])
   $DataSet.Tables[0].Columns.Add($ColumnQueryPlan)
   
   foreach ($Plan in $DataSet.Tables[0])
   {
     $plan_handle = $Plan["plan_handle"]
     $SqlSourceConnection.Open()
     $SqlCmdQueryPlanGet = New-Object System.Data.SqlClient.SqlCommand("SELECT query_plan FROM sys.dm_exec_query_plan($plan_handle)",$SqlSourceConnection)
     $SqlCmdQueryPlanGet.CommandTimeout = 30
     $QueryPlan = $SqlCmdQueryPlanGet.ExecuteScalar()
     $SqlSourceConnection.Close()
   }

I get this error:

Exception calling "ExecuteScalar" with "0" argument(s): "Incorrect syntax near '0'."
At char:51 + $QueryPlan = $SqlCmdQueryPlanGet.ExecuteScalar( <<<< )

I think that the problem is related to the data type of the plan_handle. All feedback is greatly appreciated.

Ola Hallengren
http://ola.hallengren.com


Search Computers object in AD based on its description using PS

$
0
0

Hi everyone,

How can I enter a search string and it will search all AD computers with that string in computer's description attribute using PS.  I am trying to search a computer with a specific text in its description field.  Thanks in advance.

Processor information using get-wmiobject

$
0
0

Hi

Suppose there is more than one processor in my machine, can anyone give me a script which show me a breakdown of the processors and their varying speeds/a distribution of resources between the processors?

Thanks

Active Directory Module for Windows Powershell Output Results as Excel document.

$
0
0

My current issue is that i am trying to find all expired accounts under my OU in Active Directory. The current script i have runs great but i dont know how to be more specific or to get the results to Output to a file such as an excel document.

Current Script:

Search-ADAccount -AccountExpired

That runs and finds all users. I have other options the script i tried running is:

Search-ADAccount -AccountExpired -SearchBase"OU=(My OU),DC=(My Domain),DC=(local)" -SearchScope SubTree

That Script will not run the same as the first one. It results in a >> Prompt i was unsure what the "local" part was and left it as is. So my question is can anyone provide me with the script i'm looking for?

When Value contains multiple values convertto-html will return system.object[] and not value

$
0
0

What I'm trying to do is build a function to pull networking values from some ESXi hosts. The function works correctly, but when I try to convertto-html values that contain more then one entry returns the result system.object[]

Function get-vmnetworking
{

param
(
  [Parameter(ValueFromPipelineByPropertyName=$true)]$Name
)

$i = 0
$Output = @()
$itemCount=$input.Count

    $Input | ForEach {

        Write-Progress -activity "Getting Networking Information" -status $_ -PercentComplete (($i++ / $itemCount)  * 100)

$temp = (get-vmhost $_ | Get-VMHostNetworkAdapter )

$object = New-Object PSObject

$object | Add-Member NoteProperty "Host"         $_
$object | add-member NoteProperty "MGMT IP"      ($temp | ? {$_.ManagementTrafficEnabled -eq $True} | Select-object -ExpandProperty IP)
$object | add-member NoteProperty "MGMT MTU"     ($temp | ? {$_.ManagementTrafficEnabled -eq $True} | Select-object -ExpandProperty MTU)
$object | add-member NoteProperty "VMotion IP"   ($temp | ? {$_.VMotionEnabled -eq $True} | Select-Object -ExpandProperty IP)
$object | add-member NoteProperty "VMotion MTU"  ($temp | ? {$_.VMotionEnabled -eq $True} | Select-Object -ExpandProperty MTU)
$object | add-member NoteProperty "StorageIP"   ($temp | ? {$_.ManagementTrafficEnabled -eq $False -and $_.VMotionEnabled -eq $false -and $_.FaultToleranceLoggingEnabled -eq $false} | Select-Object -ExpandProperty IP)
$object | add-member NoteProperty "StorageMTU"  ($temp | ? {$_.ManagementTrafficEnabled -eq $False -and $_.VMotionEnabled -eq $false -and $_.FaultToleranceLoggingEnabled -eq $false} | Select-Object -ExpandProperty MTU)

$Output += $object

    } # End For Each Loop

$Output

} # End of set-vmnetworking

Running the command

get-vmhost | sort-object Name | get-vmnetworking

Will return the result

MGMT IP     : 192.168.100.24
MGMT MTU    : 1500
VMotion IP  : 192.168.102.24
VMotion MTU : 1500
StorageIP   : {192.168.101.24, 192.168.101.27}
StorageMTU  : {1500, 1500}

As you can see the results Storage IP and Storage MTU are contained within brackets because they have multiple values.

If I were to convertto-html

$frag0 = get-vmhost | get-vmnetworking | convertto-html -as Table -Fragment -PreContent '<H2>Networking Information</H2>' | out-string

Convertto-html $style -PostContent $frag0 | out-file $output\file.html

The outputted html file will replace the multiple values as System.Object[]

Any help would be appreciated.


Walter

Read in specific line numbers from a text file (very large 1.5GB) using PowerShell

$
0
0

Hi all,

I have a large file (a text file) which is over 1.5GB in size. 

I need to read in specific line numbers from the file, I have a list of exact line numbers I wish to read.

If I use "get-content" to read in all the contents, PowerShell consumes 1.3GB in memory then crashes out.  I don't have enough memory to cope with using get-content to read in all the contents.

Is there any way of doing the following:

       $entry = get %linenumber% from %filename%

Any help is greatly appreciated!

Kathy


Kathleen Hayhurst Senior IT Support Analyst


Powershell against wim images

$
0
0
Hello there

is there a possibility to use powershell to recover additional infos about wim/mounted images?

I know that there are DISM Cmdlets and the DISM utility by itself (i use them normally) but DISM Cmdlets lacks the possibility to recover info about installed apps in Win7 images and if i use DISM by itself i lose the powershell capability to work with objects,sorting,filtering, ecc. ecc.

Is there another way using powershell?I don't know,is it possible to interrogate wmi classes of a mounted wim image (i think that i already know the answer...)?

Using both on the same mounted wim seems impossibile because if i mount an image with DISM cmdlet then DISM by itself don't recognize the mounted image so i cannot mix the results between this 2 tools...

Well,i know that i can mount and re-mount the single wim image but it is a really time-consuming task so,if there are any other options...

I'm using Powershell V4,ADK 8.0

Thanks

Error while adding local user to a local group through powershell

$
0
0

I used the following command to set the password and add a group to the user :

$user=[ADSI]'WinNT://localhost/account5';
$user.SetPassword('Passw0rd#');
$OBjOU =[ADSI]'WinNT://localhost/Administrators,group';
$objOU.add($user.path);

The password is getting reset, but I am getting the following error while adding the account to the user :

A member could not be added to or removed from the local group because the member does not exist.

But the local member is already present and it is resting the password of the local user.

While trying to add a user to a group manually, the location in which the user is searched is by default a domain.The local user in the machine is not a part of this domain and so it cannot be added. When I select the location as local machine and then add the user, the user is getting added. This might be the reason for getting the above error. How can we change the location(in which to search for users) to the local machine through powershell commands?

Error installing both PowerShell 3.0 and 4.0! Anyone?

$
0
0

Relevant System Information:
Windows 7 SP1 - 64-bit
.NET 4.0 and 4.5 both installed
System currently at PowerShell 2.0

I have tried running it with the System Update Readiness Tool but it didn't change the outcome. Always the same error.

PowerShell 3.0 Installation notes (Windows6.1-KB2506143-x64.msu):
Windows setup log shows - Package KB2506143 failed to be changed to the Installed state. Status: 0x80070005

ERROR lines from "C:\Windows\Logs\CBS\CBS.log":

2013-11-27 10:34:54, Error                 CBS    Shtd: Failed while processing non-critical primitive operations queue. Non-critical primitives will be retried from SMSS. [HRESULT = 0x80070005 - E_ACCESSDENIED]
2013-11-27 10:37:22, Error                 CSI    00000006 (F) Error: ResolvePendingTransactions called after poqexec failure (call 1)
  Status = STATUS_ACCESS_DENIED, Operation = DeleteFile, DiagString = [l:144{72}]"\??\C:\WINDOWS\SysWOW64\WindowsPowerShell\v1.0\en-US\about_trap.help.txt"
[gle=0x80004005]
2013-11-27 10:37:25, Error                 CBS    Startup: Primitive operations failed, startupPhase: 0.  The transaction will be cancelled. [HRESULT = 0x80004005 - E_FAIL]

PowerShell 4.0 Installation notes (Windows6.1-KB2819745-x64-MultiPkg.msu):
Windows setup log shows - Package KB2819745 failed to be changed to the Installed state. Status: 0x80070057

ERROR lines from "C:\Windows\Logs\CBS\CBS.log":

2013-11-27 10:44:33, Error                 CBS    Shtd: Failed while processing non-critical primitive operations queue. Non-critical primitives will be retried from SMSS. [HRESULT = 0x80070005 - E_ACCESSDENIED]
2013-11-27 10:46:56, Error                 CSI    00000006 (F) Error: ResolvePendingTransactions called after poqexec failure (call 1)
  Status = STATUS_ACCESS_DENIED, Operation = DeleteFile, DiagString = [l:144{72}]"\??\C:\WINDOWS\SysWOW64\WindowsPowerShell\v1.0\en-US\about_trap.help.txt"
[gle=0x80004005]
2013-11-27 10:46:59, Error                 CBS    Startup: Primitive operations failed, startupPhase: 0.  The transaction will be cancelled. [HRESULT = 0x80004005 - E_FAIL]

Strangely I just noticed that they both reference the same file. Will do some more digging, but does anyone have any other ideas?

Select-Object: why -Unique is not always unique?

$
0
0

An example where -Unique is unique:

'a','a','a' | Select-Object -Unique

An example where -Unique is not unique:

Select-Object -InputObject 'a','a','a' -Unique

Parse Windows login event for specific details

$
0
0

Hi,

I have a windows event that I want to search for in the event log using Powershell.  I've got the basics but can't find how to drill further into the details.  This is what I have so far:

get-eventlog security | where{$_.eventid -eq 4624 -and $_.message -match "Logon Type:\s+3"}

The problem is in the event details I have the following:

An account was successfully logged on.

Subject:
    Security ID:        NULL SID
    Account Name:        -
    Account Domain:        -
    Logon ID:        0x0

Logon Type:            3

New Logon:
    Security ID:        test\administrator
    Account Name:        administrator
    Account Domain:        test
    Logon ID:        0x318df67
    Logon GUID:        {0b843e34-532c-e4c2-9577-2ee19684f472}

Process Information:
    Process ID:        0x0
    Process Name:        -

Network Information:
    Workstation Name:    
    Source Network Address:    192.168.10.11
    Source Port:        51446

How can I query for this information, as for example there are 2 instances of Security ID....

Thanks

James


Alter De Ruine


Viewing all 21975 articles
Browse latest View live