Create Printer Powershell - powershell

Am having major difficulties getting a script I am working on to to successfully create a Printer. I have so far managed to get the Printer Ports created successfully but it always errors with the Printer creation.
The CSV file where it is picking the information up from looks like this:
PrinterName,PrinterPort,IPAddress,Location,Comment,PrintDriver,
Testprint1,Testport1,10.10.10.10,IT_Test,Test_1,HP LaserJet 4200 PCL 5e,
The error message I get is this:
Exception calling "Put" with "0" argument(s): "Generic failure "
At C:\myversion.ps1:53 char:19
+ $objNewPrinter.Put <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
The code I am using is this:
trap { $error[0].Exception | get-member } $objNewPrinter.Put()
Write-Host ("`tCreating " + $strPrinterName.Count + " Printer's`t")
$objPrint = [WMICLASS]"\\timvista\ROOT\cimv2:Win32_Printer"
$objPrint.psbase.scope.options.EnablePrivileges = $true
## Loop through and create each printer
For($i=0; $i -lt $PrinterName.count; $i++)
{
$objNewPrinter = $objPrint.createInstance()
$objNewPrinter.DeviceID = $PrinterName[$i] ## This is the printer name
$objNewPrinter.DriverName = $PrintDriver[$i]
$objNewPrinter.PortName = $PrinterPort[$i]
$objNewPrinter.Location = $Location[$i]
$objNewPrinter.Comment = $Comment[$i]
$objNewPrinter.ShareName = $PrinterName[$i]
$objNewPrinter.Put()
$objPrint
## Add Security group
## Not completed yet
}
Does anyone have any thoughts about what a generic failure is and how to go about troubleshooting it?

Tim, the Generic failure error is raised when bad parameters are passed to a WMI method, so two advices, first try using a real port name not Testport1 and check for the DriverName must be the exact name of a existing driver.

Related

Why is Export-PnPFlows Skipping Flows?

This is my first post, so please pardon formatting errors!
I've been trying to export my tenant's Power Automate flows via Export-PnPFlow. I have a few hundred flows, so doing it by hand isn't really feasible.
The script works well enough for some flows, but is throwing an error for others, but I can't see why.
It does not seem to be caused by if it's enabled/disabled, owned by a certain user, in a certain environment, or in/out of a solution.
The ones that work, work perfectly; the others give the following error:
Export-PnPFlow : {"error":{"code":"ConnectionAuthorizationFailed","message":"The caller object id is '08#####-#####-####-###'. Connection '2#####-#####-####-####' to 'shared_logicflows' cannot be used to activate this flow, either because
this is not a valid connection or because it is not a connection you have access permission for. Either replace the connection with a valid connection you can access or have the connection owner activate the flow, so the connection is shared with you in the context of
this flow."}}
At C:\Users\jutrust\script.ps1:13 char:21
+ ... Export-PnPFlow -Environment $environment -Identity $flow. ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Export-PnPFlow], HttpRequestException
+ FullyQualifiedErrorId : System.Net.Http.HttpRequestException,PnP.PowerShell.Commands.PowerPlatform.PowerAutomate.ExportFlow
My question is, is it possible that these flows are deleted and that's why I get this error? If so, how can I check?
Code below.
Connect-PnPOnline -url https://########.sharepoint.com
$environments = get-pnppowerplatformenvironment
foreach($environment in $environments)
{
$flows = Get-PnPFlow -Environment $environment -AsAdmin
foreach ($flow in $flows)
{
$filename = $flow.Properties.DisplayName.Replace(" ", "")
$timestamp = Get-Date -Format "yyyymmddhhmmss"
$exportPath = "$($filename)_$($timestamp)"
$exportPath = $exportPath.Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
Export-PnPFlow -Environment $environment -Identity $flow.Name | Out-File "C:\Users\jutrust\documents\$exportPath.json"
}
}
Help!
Edit: Updated error code

Add elements to arry in powershell

I want to simply add some numbers to an array and then sort them via powershell, however, the following code seems to be wrong
$myArray = New-Object System.Collections.ArrayList
Foreach ($Name in $VMName) {
$Tokens = $Name.Split(".")
$myArray.Add($Tokens[$Tokens.Count-1])
}
Write-Host($myArray | Sort-Object)
The error is
+ $myArray.Add($Tokens[$Tokens.Count-1])
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NotSupportedException
How can I fix that?
The variable $Name is something like 101.u18.uab.14 or 103.win10.template or 102.win7.pink.18 and so on. Each $Name has some . symbols and I want to tokenize them and get the last element for each of them. So, in this example, I want to see a sorted 14 18 template.
UPDATE:
The provided methods seems to be incorrect.
1- This method by Steven
$myArray = New-Object System.Collections.ArrayList
Foreach ($Name in $VMName) {
$Tokens = $Name.Split(".")
[Void]$myArray.Add($Tokens[-1])
}
shows this error
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
At C:\Users\user\Desktop\get_ip_list.ps1:20 char:5
+ [Void]$myArray.Add($Tokens[-1])
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NotSupportedException
2- This method by Santiago
$myArray = [Collections.Generic.List[string]]::new()
Foreach ($Name in $VMName) {
[Void]$myArray.Add($Name.Split(".")[-1])
}
Shows the following error
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
At C:\Users\user\Desktop\get_ip_list.ps1:19 char:5
+ [Void]$myArray.Add($Name.Split(".")[-1])
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NotSupportedException
If I have missed your point in the above codes, please let me know.
I think you are missing the first line from the error. However it looks like you are simply trying to add the last elements from the $Tokens array. In that case you don't need to reference the index like that, below should work:
$myArray = New-Object System.Collections.ArrayList
Foreach ($Name in $VMName) {
$Tokens = $Name.Split(".")
[Void]$myArray.Add($Tokens[-1])
}
Notice the addition of [Void] this will stop the .Add() method from returning the index number it just added to.
Also note you can create array list objects using casting like:
$myArray = [Collections.ArrayList]#()
Update to Address Continued Errors:
The only thing I can think of to cause the error "Collection was of a fixed size." is if you've previously type constrained the variable.
Example:
[String[]]$myArray = #()
# Posibly a whole bunch of other things happening maybe in the console or IDE.
$myArray = [Collections.ArrayList]#()
$myArray.Add('something')
Results:
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
At line:1 char:1
+ $myArray.Add('something')...
In this case they type of the $myArray will not change to [Collections.ArrayList]. The problem will be transparent up until you try to use the .Add() method that won't work. This is because an array list is easily and therefore silently cast back to a [String[]] or [Object[]].
Note: If you were to run $myArray.IsFixedSize it would return "True".
My guess as to what's happening; at some point while developing your code or perhaps in the larger script, $myArray got type constrained, and stuck in the scope. This can definitely happen especially given the scope overlap in IDE's like PowerShell's ISE, and I think it happens in VSCode as well. If this is part of a larger script look for instances of $myArray to see if it's indeed type constrained and make corrections as needed. Otherwise a simply restarting your session might do the trick.
Honestly, not sure how could you be getting that error unless the array we're looping through is actually something different. Steven's answer should work fine, I'll put this code below just to show that the results we get are the ones you expect:
$col = [Collections.Generic.List[String]]::new()
$vmName = #(
'101.u18.uab.14'
'103.win10.template'
'102.win7.pink.18'
)
ForEach($name in $vmName)
{
$col.Add($name.Split('.')[-1])
}
if you want absolutly use array you can simply do it :
$Array=#()
$VMName | %{
$Value=($_.Split('.'))[-1]
$Array+= $Value
}
$Array| sort
Otherwise you can simply do it :
$VMName | %{($_.Split('.'))[-1]} | sort

How to get this PowerShell command output into an iterable collection or array

This answer shows how to output a list of computer-names on the domain:
(([adsi]"WinNT://$((Get-WMIObject Win32_ComputerSystem).Domain)").Children).Where({$_.schemaclassname -eq 'computer'})
If the Pathproperty is appended
... .Where({$_.schemaclassname -eq 'computer'}).Path
it outputs a list in this format:
WinNT://{domainname}.net/{machine-name}
How would that succession of fully qualified machine names be made into an array or a collection that could be iterated by the script found here?
Can that command (i.e. its output) simply be assigned to an array variable?
[array]$ComputerNames = ... (([adsi]"WinNT://$((Get-WMIObject <snip> ).Path
I suspect not, since when I try that
$ComputerNames = ... (([adsi]"WinNT://$((Get-WMIObject <snip> ).Path
foreach($computer in $ComputerNames) {
if($regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer)) {
I get an error:
Exception calling "OpenRemoteBaseKey" with "2" argument(s): "The network path was not found."
At C:\Users\{myusername}\Get-NetFrameworkVersion.ps1:40 char:8
+ if($regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('Lo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IOException
My ultimate goal is to obtain the .NET versions installed on all PCs on the domain.

PowerShell error 'can't call null-value expresssion' [duplicate]

I am simply trying to create a powershell script which calculates the md5 sum of an executable (a file).
My .ps1 script:
$answer = Read-Host "File name and extension (ie; file.exe)"
$someFilePath = "C:\Users\xxx\Downloads\$answer"
If (Test-Path $someFilePath){
$stream = [System.IO.File]::Open("$someFilePath",[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
$hash = [System.BitConverter]::ToString($md5.ComputeHash($stream))
$hash
$stream.Close()
}
Else{
Write-Host "Sorry, file $answer doesn't seem to exist."
}
Upon running my script I receive the following error:
You cannot call a method on a null-valued expression.
At C:\Users\xxx\Downloads\md5sum.ps1:6 char:29
+ $hash = [System.BitConverter]::ToString($md5.Compute ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
To my understanding, this error means the script is attempting to do something, but another part of the script does not have any information to permit the first part of the script to work properly. In this case, $hash.
Get-ExecutionPolicy outputs Unrestricted.
What is causing this error?
What exactly is my null valued expression?
Any help is appreciated. I apologize if this is trivial and will continue my research.
References:
http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/27/troubleshoot-the-invokemethodonnull-error-with-powershell.aspx
How to get an MD5 checksum in PowerShell
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

Calling [ADSI] with external parameter

I am not very familiar with powershell scripting and I'm stuck on this problem -
I need to make some operations on object retrieved like this:
$object = [ADSI]'LDAP://CN=Test User,OU=Dept,OU=Users,DC=example,DC=org'
...
$object.Commit()
this works fine, but I have to use distinguished name stored in variable - my test script looks like this, but its not working:
$object = [ADSI]'LDAP://$variable'
...
$object.Commit()
the first call to [ADSI] itself doesn't cause error, but any following operation crashes with message:
The following exception occurred while retrieving member "commit": "The server is not operational.
"
At line:1 char:10
+ $object.commit <<<< ()
+ CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMember
I'm pretty sure, that the parameter is sent in some wrong way, but I don't know, how to fix it, can anybody help?
tahnks
Try:
$object = [ADSI]"LDAP://$variable"
Single quotes don't expand variables.