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

Read text file and return read lines after certain string is found

$
0
0

I want to read a text file but only interested in reading lines after a line "Start Here" is found and end when "End Here" is found.

the text files is like this.

fdjksfjkdf

sdjfkdsjfksdjf

Start Here

These are the lines I am interested in.

These are the lines I want to return.

These are the lines I am interested in.

These are the lines I am interested in.

These are the lines I am interested in.

These are the lines I am interested in.

These are the lines I am interested in.

End here

fdsjfdksfjsdlkfj

---------------------------------------------

I've written something like this so far..

$lines = Get-Content -Path "test.txt"

$patternText = "Start Here"

foreach ($line in $lines)
{
    if ($line | Select-String -Pattern $patternText)
    {
       
    }
}


Pester - How mock user interaction New-Object System.Management.Automation.Host .ChoiceDescription ?

$
0
0

Hi

I would like extended Pester tests for the module New-OutputObject .

In the code I use

        #Dialog for decision if Force was not set or Overwrite All not selected previously
        [String]$Title = "Overwrite File"

        [String]$MessageText = "The file {0} already exist" -f $OutputFilePath

        $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `"The file already exists. Overwrite the existing file."

        #$yesall = New-Object System.Management.Automation.Host.ChoiceDescription "&All", `
        #                     "Overwrite the all existing files."

        $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `"Retain the existing file."

        #$noall = New-Object System.Management.Automation.Host.ChoiceDescription "N&o for All", `
        #                   "Retain the all existing files."

        $cancel = New-Object System.Management.Automation.Host.ChoiceDescription "&Cancel", `"Cancel."

        $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no, $cancel)

$Answer = $host.ui.PromptForChoice($Title, $MessageText, $Options, 0)
https://github.com/it-praktyk/New-OutputObject/blob/master/Public/New-OutputFile.ps1#L244-L266

If/how can be mocked user interaction taken using "New-Object System.Management.Automation.Host.ChoiceDescription" ?


Thank you in advance for any help.


Wojciech Sciesinski

If my answer help you please mark it as the answer or helpful post.

Thank you.

Accepting single quote character in powershell script arguement

$
0
0

Hi,

We have configured a powershell script that accepts arguements on a third party tool.

The issue is, if the parameter contains single quote it breaks.

for example, ./script.ps1 'test param 1' 'test 'param2' which accepts two parameters. In the second parameter the value contains (') single quote. Now the issue is we cannot escape the character from the tool where it is confiugred, as the tool does not provide any function that allows to escape or even replace the characters.

Is there anything that can be done on powershell script end.

Automate IE to get info from site's page, contained within a dynamically created iframe.

$
0
0

I've written other IE automation scripts using COM in powershell.  As of now, I can navigate to the URL of my choosing, I can input my password and .click() the submit button. The page then loads 3 frames. I verified it with the .length of:

$Frames = $IE.Document.frames

I also verified in IE's DOM explorer, when "inspecting" the elements.  I then grab the specific frame by doing:

$iFrame = $IE.Document.getElementsByTagName("iframe") | ?{$_.title -eq "WebAdvisor"}

The issue is that when doing a:

$iFrame.document.body.innerHTML

I'm getting the same info I would get if I did:

$IE.Document.body.innerHTML
From I understanding I should only be getting what's in the frame.  The issue with getting the same as the parent doc is that it does not show the text that is in the iframe.  From seeing the page itself, it gets created dynamically using info from a database.  

The parent page remains the same at all times, but when a selection is made, it updates just the frame. As an example, this is the "a" tag for one such link:

<a href="PageServlet?pg=WebAdvisorIFrameProxy&amp;a_ppl=ST&amp;f_ormMnemonic=WRGS&amp;cmp=F22.154_201&amp;cx=22.154">*Return to Registration Selections</a>
PageServlet is the parent page. 

get existiing string match from eventlog message

$
0
0

Hi guys,

I need to get eventlog which has specific string in message property. I found out this, which is exaple of select-string cmdlet but it doesn't work:

$Events = Get-EventLog -LogName application -Newest 1
$Events | Select-String -InputObject {$_.message} -Pattern "failed"
It shows me the whole message. The only working solution which works is export message to .txt file and with get-content cmdlet and select-string find If the string is has match. But I don't want that.  Can you tell me what I'm doing wrong? Thank youl.

How can I connect to another machine and, and have it run a set of commands?

$
0
0

Hi,

I'm trying to write a script that will connect to another machine in my domain, and run a function from my script.

I don't want an interactive session.

I just need to.

  • 1. Run my script.
  • 2. Have it connect to the remote machine.
  • 3. Run the function on the remote machine.
  • 4. Close the session and return back to my local machine.

I would also it to run under the context of the current user.

Would this just be a case of using the invoke-command cmdlt, or will I have to use another method.

Thanks

ComputerInfo - Not available?

$
0
0

Hi Im trying to run the Get-ComputerInfo command and I get the below...

Anyone have any thoughts?

PS C:\SOFTWARE> Get-ComputerInfo
Get-ComputerInfo : The term 'Get-ComputerInfo' 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:1 char:1
+ Get-ComputerInfo
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-ComputerInfo:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Dee


Dee

Return Object values from invoke command

$
0
0

Hi guys,

I'm trying to write a script that loops through a list of computers and runs query to get an objects back into a variable to be used in an if statement.

This is the code I have written.

$Thereturn = Invoke-command -ComputerName $Entry.ServerName -Credential $Credentials -ScriptBlock {
                write-host "connected to " $env:ComputerName
                racadm config -g cfgLanNetworking -o cfgNicIpAddress $Args[1]
                racadm config -g cfgLanNetworking -o cfgNicNetmask 255.255.252.0
                racadm get iDRAC.IPv4
                                }  -ArgumentList $entry.ServerName, $Entry.ip  #Passing Arguments to invoke $arg array

The data I want to return from the invoke command and pass into another statement is the Racadm object "racadm get iDRAC.IPv4"

This command would normally return the bellow member values.
Address x.x.x.x
Netmask 255.255.255.0
IPv4.Gateway x.x.x.x
IPv4.DHCPEnable 0
IPv4.DNSFromDHCP 0
IPv4.DNS1 y.y.y.y

Example calling the IP address would be "racadm set iDRAC.Address"

I'v tried to figure out how to do this but not 100% and not sure if i'm doing something wrong, I can pass variables into the invoke command fine but getting them out is appearing strange to me. Is what I have above correct and to return the value of say the address, should this just be $Thereturn.Address ?


Tea Tutaki



WARNING: The cmdlet extension agent with the index 5 has thrown an exception in OnComplete()

$
0
0

Setup:
DC = Server 2012
Exchange Roles Installed on DC: HT, CAS & MB
$PSVersiontabel - 4.0
Setup is for learning PowerShell


Get-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 | Add-PSSnapin

And if i run New-MailboxDatabase or New-Mailbox or Enable-Mailbox
I get this warning on powershell console & even on powershell ise but not on exchange shell

WARNING: The cmdlet extension agent with the index 5 has thrown an exception in OnComplete(). The exception is: System.TypeInitializationException: The type initializer for 'Microsoft.Exchange.Data.Storage.NativeStorePropertyDefinitionDictionary' threw an ex
ception. ---> System.NotSupportedException: Not supported field(MailEnabled) type(Microsoft.Exchange.Data.Storage.PropertyTagPropertyDefinition).
   at Microsoft.Exchange.Data.Storage.NativeStorePropertyDefinitionDictionary.PropertyDefinitionSets.BuildWellKnownSets()
   at Microsoft.Exchange.Data.Storage.NativeStorePropertyDefinitionDictionary..cctor()
   --- End of inner exception stack trace ---
   at Microsoft.Exchange.Data.Storage.PropertyTagPropertyDefinition.TryFindEquivalentDefinition(PropTagKey key, Boolean isCustom, PropType type, TypeCheckingFlag typeCheckingFlag, PropertyTagPropertyDefinition& definition, Boolean& createNewDefinition)
   at Microsoft.Exchange.Data.Storage.PropertyTagPropertyDefinition.InternalCreate(String displayName, PropTag propertyTag, PropertyFlags flags, TypeCheckingFlag typeCheckingFlag, Boolean isCustom, PropertyDefinitionConstraint[] constraints)
   at Microsoft.Exchange.Data.Storage.PropertyTagCache.InternalPropertyDefinitionsFromPropTags(TypeCheckingFlag propertyTypeCheckingFlag, MapiProp mapiProp, StoreSession storeSession, PropTag[] propTags, Int32& resolvedPropertyCount)
   at Microsoft.Exchange.Data.Storage.RecipientTable.GetRecipientPropertyDefinitionsFromMapiTable(Boolean& originalColumnsChanged)
   at Microsoft.Exchange.Data.Storage.RecipientTable.BuildRecipientCollection(Action`2 recipientCollectionBuilder)
   at Microsoft.Exchange.Data.Storage.CoreRecipientCollection..ctor(ICoreItem coreItem)
   at Microsoft.Exchange.Data.Storage.CoreItem.Microsoft.Exchange.Data.Storage.ICoreItem.GetRecipientCollection(Boolean forceOpen)
   at Microsoft.Exchange.Data.Storage.CoreItem.GetRecipientCharsetDetectionData(StringBuilder stringBuilder, Boolean isComplete)
   at Microsoft.Exchange.Data.Storage.CoreItem.GetCharsetDetectionData(StringBuilder stringBuilder, CharsetDetectionDataFlags flags)
   at Microsoft.Exchange.Data.Storage.ItemCharsetDetector.BuildCodePageDetector(MemoryStream& cachedHtmlBody)
   at Microsoft.Exchange.Data.Storage.ItemCharsetDetector.DetectCpidWithOptions(Charset userCharset, MemoryStream& cachedHtmlBody)
   at Microsoft.Exchange.Data.Storage.ItemCharsetDetector.SetCachedBodyDataAndDetectCharset(Char[] cachedBodyData, Charset userCharset, BodyCharsetFlags charsetFlags)
   at Microsoft.Exchange.Data.Storage.BodyCharsetDetectionStream.CalculateCharset()
   at Microsoft.Exchange.Data.Storage.BodyCharsetDetectionStream.OnBufferFull()
   at Microsoft.Exchange.Data.Storage.BodyCharsetDetectionStream.CloseDetectorConversionStream()
   at Microsoft.Exchange.Data.Storage.BodyCharsetDetectionStream.Flush()
   at Microsoft.Exchange.Data.TextConverters.ConverterEncodingOutput.Flush()
   at Microsoft.Exchange.Data.TextConverters.Internal.Text.TextCodePageConverter.Run()
   at Microsoft.Exchange.Data.TextConverters.Internal.Text.TextCodePageConverter.Flush()
   at Microsoft.Exchange.Data.TextConverters.ConverterWriter.Flush()
   at Microsoft.Exchange.Data.TextConverters.ConverterWriter.Dispose(Boolean disposing)
   at System.IO.TextWriter.Close()
   at Microsoft.Exchange.Data.Storage.BodyTextWriter.<CloseWriter>b__11()
   at Microsoft.Exchange.Data.Storage.ConvertUtils.CallCts(Trace tracer, String methodName, LocalizedString exceptionString, CtsCall ctsCall)
   at Microsoft.Exchange.Data.Storage.BodyTextWriter.CloseWriter()
   at Microsoft.Exchange.Data.Storage.BodyTextWriter.Dispose(Boolean disposing)
   at System.IO.TextWriter.Dispose()
   at Microsoft.Exchange.ProvisioningAgent.MailboxLoggerFactory.XsoMailer.Log(AdminLogMessageData data, LogMessageDelegate logMessage)
   at Microsoft.Exchange.ProvisioningAgent.AdminLogProvisioningHandler.OnComplete(Boolean succeeded, Exception e)
   at Microsoft.Exchange.Provisioning.ProvisioningLayer.OnComplete(Task task, Boolean succeeded, Exception exception)WARNING: The cmdlet extension agent with the index 5 has thrown an exception in OnComplete(). The exception is: System.TypeInitializationException: The type initializer for 'Microsoft.Exchange.Data.Storage.NativeStorePropertyDefinitionDictionary' threw an ex
ception. ---> System.NotSupportedException: Not supported field(MailEnabled) type(Microsoft.Exchange.Data.Storage.PropertyTagPropertyDefinition).
   at Microsoft.Exchange.Data.Storage.NativeStorePropertyDefinitionDictionary.PropertyDefinitionSets.BuildWellKnownSets()
   at Microsoft.Exchange.Data.Storage.NativeStorePropertyDefinitionDictionary..cctor()
   --- End of inner exception stack trace ---
   at Microsoft.Exchange.Data.Storage.PropertyTagPropertyDefinition.TryFindEquivalentDefinition(PropTagKey key, Boolean isCustom, PropType type, TypeCheckingFlag typeCheckingFlag, PropertyTagPropertyDefinition& definition, Boolean& createNewDefinition)
   at Microsoft.Exchange.Data.Storage.PropertyTagPropertyDefinition.InternalCreate(String displayName, PropTag propertyTag, PropertyFlags flags, TypeCheckingFlag typeCheckingFlag, Boolean isCustom, PropertyDefinitionConstraint[] constraints)
   at Microsoft.Exchange.Data.Storage.PropertyTagCache.InternalPropertyDefinitionsFromPropTags(TypeCheckingFlag propertyTypeCheckingFlag, MapiProp mapiProp, StoreSession storeSession, PropTag[] propTags, Int32& resolvedPropertyCount)
   at Microsoft.Exchange.Data.Storage.RecipientTable.GetRecipientPropertyDefinitionsFromMapiTable(Boolean& originalColumnsChanged)
   at Microsoft.Exchange.Data.Storage.RecipientTable.BuildRecipientCollection(Action`2 recipientCollectionBuilder)
   at Microsoft.Exchange.Data.Storage.CoreRecipientCollection..ctor(ICoreItem coreItem)
   at Microsoft.Exchange.Data.Storage.CoreItem.Microsoft.Exchange.Data.Storage.ICoreItem.GetRecipientCollection(Boolean forceOpen)
   at Microsoft.Exchange.Data.Storage.CoreItem.GetRecipientCharsetDetectionData(StringBuilder stringBuilder, Boolean isComplete)
   at Microsoft.Exchange.Data.Storage.CoreItem.GetCharsetDetectionData(StringBuilder stringBuilder, CharsetDetectionDataFlags flags)
   at Microsoft.Exchange.Data.Storage.ItemCharsetDetector.BuildCodePageDetector(MemoryStream& cachedHtmlBody)
   at Microsoft.Exchange.Data.Storage.ItemCharsetDetector.DetectCpidWithOptions(Charset userCharset, MemoryStream& cachedHtmlBody)
   at Microsoft.Exchange.Data.Storage.ItemCharsetDetector.SetCachedBodyDataAndDetectCharset(Char[] cachedBodyData, Charset userCharset, BodyCharsetFlags charsetFlags)
   at Microsoft.Exchange.Data.Storage.BodyCharsetDetectionStream.CalculateCharset()
   at Microsoft.Exchange.Data.Storage.BodyCharsetDetectionStream.OnBufferFull()
   at Microsoft.Exchange.Data.Storage.BodyCharsetDetectionStream.CloseDetectorConversionStream()
   at Microsoft.Exchange.Data.Storage.BodyCharsetDetectionStream.Flush()
   at Microsoft.Exchange.Data.TextConverters.ConverterEncodingOutput.Flush()
   at Microsoft.Exchange.Data.TextConverters.Internal.Text.TextCodePageConverter.Run()
   at Microsoft.Exchange.Data.TextConverters.Internal.Text.TextCodePageConverter.Flush()
   at Microsoft.Exchange.Data.TextConverters.ConverterWriter.Flush()
   at Microsoft.Exchange.Data.TextConverters.ConverterWriter.Dispose(Boolean disposing)
   at System.IO.TextWriter.Close()
   at Microsoft.Exchange.Data.Storage.BodyTextWriter.<CloseWriter>b__11()
   at Microsoft.Exchange.Data.Storage.ConvertUtils.CallCts(Trace tracer, String methodName, LocalizedString exceptionString, CtsCall ctsCall)
   at Microsoft.Exchange.Data.Storage.BodyTextWriter.CloseWriter()
   at Microsoft.Exchange.Data.Storage.BodyTextWriter.Dispose(Boolean disposing)
   at System.IO.TextWriter.Dispose()
   at Microsoft.Exchange.ProvisioningAgent.MailboxLoggerFactory.XsoMailer.Log(AdminLogMessageData data, LogMessageDelegate logMessage)
   at Microsoft.Exchange.ProvisioningAgent.AdminLogProvisioningHandler.OnComplete(Boolean succeeded, Exception e)
   at Microsoft.Exchange.Provisioning.ProvisioningLayer.OnComplete(Task task, Boolean succeeded, Exception exception)

Disk Pre-Check for software install..

$
0
0

Hi Everyone,

Im looking to write a script which enables me to automatically check free disk space prior to installing a piece of software providing the ability for my script to spit out responses to input. For example - I have written -

Get-WMIObject win32_logicaldisk  -filter "DeviceID='c:'" | select freespace | foreach-object {$_.Freespace / 1gb -as [int]}

This provides me with the free disk space for the C drive in GIGABYTES to the nearest whole number. What I need now it to write a piece of code where I can enter a value based on the size of a piece of software and the system will automatically check the drive to make sure there is enough space before installing and spit out a response based on what it recovered.. e.g. 'you are free to go ahead with installation' and 'sorry you cannot instal this piece of software.

Any help will be greatly appreciated!

If you are unable to reply to this thread, drop me an email at hawdon@hotmail.co.uk

Thanks 

Looking for a way to list all installed KB on a windows machine

$
0
0

Hi Guys,

I'm trying to find a way to list all installed KB's on a server.

Specifically, I fail to list KB3033929 no matter what approach I've tried.

I've used Get-HotFix, wmi (win32_quickfixengineering), wmic qfe get Hotfixid & even the CreateUpdateSearcher() method.

When trying to install the KB on the server I get the following message:

---------------------------
Windows Update Standalone Installer
---------------------------
Security Update for Windows (KB3033929) is already installed on this computer.

Any ideas?

Thanks!

Error with Get-Item : Cannot find path. File does not exist

$
0
0

Hi,

I'm working on an script which will update ACL.
So first I'm trying to list every files in order to change the owner (There are some issues with some owners).

My script is starting well the listing, but for some files (not all), I've got an error on an Get-Item with the known message "Cannot find path. File does not exist".

Can you help me please?

Here is my code :

import-module c:\temp\Get-FolderItem.psm1


$FolderToScan = "D:\Donnees\00 - Maintenance Thermique\1. Organisation"
$OldOwner = "Administrateurs"
$NewOwner = New-Object System.Security.Principal.NTAccount($OldOwner)

    TRY
    {

        Get-folderItem -Path $FolderToScan | Foreach-object {
        $path = $_.FullName
        $test = Resolve-Path $_.FullName

        $f = Get-Item -LiteralPath $_.FullName -Force

        }
    }
    CATCH [System.IO.IOException]
    {
        $Log = "" | Select-Object FileName,Path
        $Log.FileName = $_.Name
        $Log.Path = $_.FullName

        $Log | Export-Csv "c:\temp\errlog.csv" -Notype -Append
    }


function Resolve-PathSafe
{
    param
    (
        [string] $Path
    )

    $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
}

My try catch is not working, but it's an other pb.
The function Get-FolderItem is an function from technet which use robocopy to get full path when there are longer than 255.

For example, I've got my error for this file : D:\Donnees\00 - Maintenance Thermique\1. Organisation\Procédures\Réunion d'agence 2015-4T.PPTX

Where is the error in the path ? This file is really existing (I checked).

regards


TopConsoleUser using powershell different than using Hardware 05A in SCCM

$
0
0

I am trying to find the Top Console User for a given system and while I found out how to do it, the query doesn't match when I use Hardware 05A in Asset Intelligence. Any idea why? Obviously I use the same computer name for both methods. The Hardware 05A method differs from the PS method by only one user, meaning that PS shows the TCU but that same user is shows in H05A as the 2nd one in the list of users for the same system.

Brian Embree

Legacy Health System

Portland, OR

Error Cannot bind argument to parameter 'Identity' because it is null.

$
0
0

Hi Experts,

Below is the powershell scripts. I really have no idea why it went wrong. It seems the input of $URL is not recognized in the command.

#Predefine necessary information
$URL= Read-Host "Please enter your site URL"
If ($URL -like "https://xxx/*") {$Username = "xxx";$Password = "xxx";$ComputerName = "xxx"}

$Script= {Set-SPSite -Identity $URL -LockState "unlock"}

#Create credential object
$SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $SecurePassWord

#Create session object with this
$Session = New-PSSession -ComputerName $ComputerName -credential $Cred

#Invoke-Command
Invoke-Command -Session $Session -ScriptBlock {Add-PSSnapin Microsoft.SharePoint.PowerShell}
$Job = Invoke-Command -Session $Session -Scriptblock $Script
echo $Job

#Close Session
Remove-PSSession -Session $Session

#Prevent Powershell Windows from closing
Read-Host "Press ENTER to continue"


Leo Qin
MCSE 2003&CCNP

Sysprep script

$
0
0

Hello

is anyone can help me to create a sysprep script?

i need script to create

Local Admin User, Local User, Add Custom Background or Wallpaper, Create an optional hostname, Installer Adobe PDF Reader and 2 more other softwares.

all in one script 

regards MeMo.


How to login automatically during OneDrive Configuration Wizard using PowerShell script?

$
0
0

Hello

I created a PS script where I am checking following

1. OneDrive is installed or not, if it is not installed, installing in silent mode

2. Checking OneDrive is Configured or not, if it is not configured then initiating configuration wizard

During the configuration, is there any way to user email address automatically filled and wizard runs in silent mode and OneDrive cache folder creates automatically?

Avi

How To Create a Powershell Instance from running instance

$
0
0

Hello,

I'm using the Foreach-Object-Parallel function from this article in order to process objects from pipeline in parallel. Everything is working fine but I'm having trouble using this function in conjunction with the Exchange SnapIns.

When I run an Exchange cmdlet in the scriptblock I get no results since the new powershell instance does not have the exchange snapins or implicit remoting module installed.

Should I add the snapins using the ImportPSSnapIn method of the InitialSessionState? Is there a way to create a powershell instance similar to the one that's already running with all the modules and snapins?

Moreover, can I run a script after the powershell instance is created in order to configure it with all the modules, snapins, etc?

Regards,

Christos

Log all PS activity

$
0
0

Hello

for a learning-curve i want to log all my PS-activity on my workstation.

What can i do to log all my PS-sessions to a specific drive on my network?

Thx

EUM Export from exchange 2013

$
0
0

Get-mailbox -ResultSize unlimited | select -ExpandProperty emailaddresses | where {$_.prefixstring -eq "EUM"}

how would I get the user's name with the above command?

need to export all eum from exchange to find conflicts.

thank you

Add-PrinterDriver on Windows Server 2012

$
0
0

This question is in addition to the following thread which already was marked as answered:

http://social.technet.microsoft.com/Forums/windowsserver/en-US/7a2db68a-659d-4ba2-b732-52b55b9688cd/addprinterdriver-infpath?forum=winserverpowershell

Here's what I'm currently trying to achieve:

We're currently using 10 printserver appliances for publishing about 1k printer queues to the AD and making them available to the users. Sometime this year those printserver appliances will have to be replaced by a Windows printserver, because of ongoing problems we regularly encounter with the current solution.

I tried to create a PowerShell script to migrate all the printers from the appliances to the Windows server, which checks for published queues in the AD, installs the needed drivers on the Windows server and installs the printers as a last step.

I was rather happy to see that new Cmdlets were introduced with Server 2012 which seemed to be pointed exactly at what I wanted to achieve.

Here's my current problem:

Using Add-PrinterDriver didn't work as it should for a majority of our printers as their drivers are not available in the Windows driver store by default.

Using Add-WindowsDriver didn't work as it only allows drivers to be installed into offline images, not into the currently running system.

Using pnputil to add the driver to the driver store worked great, although it feels like a break in technology usage when calling this from PowerShell.

But, to get down to the core problem, Add-PrinterDriver doesn't seem to recognize a x86 driver in the driver store even if it was successfully added by pnputil. Here's an example with a HP PostScript universal printer driver (commands were taken from the script I mentioned earlier):
PS C:\Windows\system32> pnputil -a $AvailableX64Drivers[$Printer.driverName].Driver
Microsoft PnP Utility

Processing inf :            hpcu155v.inf
Driver package added successfully.
Published name :            oem11.inf


Total attempted:              1
Number successfully imported: 1


PS C:\Windows\system32> pnputil -a $AvailableX86Drivers[$Printer.driverName].Driver
Microsoft PnP Utility

Processing inf :            hpcu155d.inf
Driver package added successfully.
Published name :            oem16.inf


Total attempted:              1
Number successfully imported: 1


PS C:\Windows\system32> Add-PrinterDriver $Printer.driverName -PrinterEnvironment "Windows x64" -ErrorAction Stop

PS C:\Windows\system32> Add-PrinterDriver $Printer.driverName -PrinterEnvironment "Windows NT x86" -ErrorAction Stop
Add-PrinterDriver : The specified driver does not exist in the driver store.
At line:1 char:1+ Add-PrinterDriver $Printer.driverName -PrinterEnvironment "Windows NT x86" -Erro ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (MSFT_PrinterDriver:ROOT/StandardCimv2/MSFT_PrinterDriver) [Add-PrinterDriver], CimException+ FullyQualifiedErrorId : HRESULT 0x80070705,Add-PrinterDriver


PS C:\Windows\system32> 

The file hpcu155v.inf is confirmed to be the correct x64 driver and the file hpcu155d.inf is confirmed to be the correct x86 driver. Both work correctly when installing them using the printer driver wizard.

Viewing all 21975 articles
Browse latest View live


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