Change printer paper tray settings via powershell - powershell

I attempted to use the WMI-Object to change the paper tray settings in powershell. However I've just learned that the value i'm trying to change is read-only apprently. Could someone help me accomplish task via powershell or VBScript?
$printers = Get-WMIObject -Class Win32_PrinterConfiguration | Where-Object {$_.Name -EQ "CHK.Checks"}
$printers.MediaType = 270
$printers.Put()
I attempted this and it did not work.
Please help!
Thanks in advance!

Since the value is read-only you won't be able to use WMI to set that. .Net has the System.Printing has an input bin setting, which isn't perfect but works. I've made a function around this in my PSPrintTools module. I think Tray1, Tray2 work as values as well, but I don't remember off the top of my head. Outside of this then you get into editing the PrintTicket XML. Here's the relevant code for just that feature:
$Printer = "Example Printer Name"
$InputBin = "AutoSelect","AutoSheetFeeder","Cassette","Manual","Tractor" #choose one
Add-Type -AssemblyName System.Printing
$Permissions = [System.Printing.PrintSystemDesiredAccess]::AdministrateServer
$QueuePerms = [System.Printing.PrintSystemDesiredAccess]::AdministratePrinter
$PrintServer = new-object System.Printing.LocalPrintServer -ArgumentList $Permissions
$NewQueue = New-Object System.Printing.PrintQueue -ArgumentList $PrintServer,$Printer,1,$QueuePerms
$InputBinCaps = $NewQueue.GetPrintCapabilities().InputBinCapability
if ($null -ne $InputBinCaps) {
if ($InputBinCaps.Contains([System.Printing.InputBin]::$InputBin)) {
$NewQueue.DefaultPrintTicket.InputBin = [System.Printing.InputBin]::$InputBin
$NewQueue.UserPrintTicket.InputBin = [System.Printing.InputBin]::$InputBin
} else {
Write-Error "$InputBin unavailable on $Printer"
}
}
$NewQueue.commit()
$NewQueue.dispose()
$PrintServer.commit()
$PrintServer.dispose()

Related

Why does my script work in powershell ISE but not when it is in a .ps1 file?

It used to work but now it suddently terminates less than a second after being opened. I set the execution policy to unrestricted & re-installed Windows yet it still does not work...
The .ps1 shows up for 1 second in task manager before windows security health service when it's run using .vbs & then disappears: https://i.imgur.com/VNX7NKx.png
Here's the script (its purpose is to show notification messages):
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$notifyobj = New-Object System.Windows.Forms.NotifyIcon
$notifyobj.icon = "c:/users/work/Pictures/icon.ico"
$notifyobj.BalloonTipTitle = "New Message"
$notifyobj.BalloonTipText = "C"
$notifyobj.Visible = $True
$notifyobj.ShowBalloonTip(1000)
$notifyobj.Dispose()
More info on this thread.
Odd for sure, and there should have been really no reason you should have had to reinstall Windows for your effort. So, something else is impacting this. Hard to say what though.
Try this version to see if you have any / more success. It takes a different approach, but works on my systems.
Function Show-Notification
{
Param
(
[string]$MessageType,
[string]$MessageText,
[string]$MessageTitle
)
#load Windows Forms and drawing assemblies
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
#define an icon image pulled from PowerShell.exe
$Icon=[system.drawing.icon]::ExtractAssociatedIcon((join-path $pshome powershell.exe))
$Notify = New-Object System.Windows.Forms.NotifyIcon
$Notify.icon = $Icon
$Notify.visible = $True
#define the tool tip icon based on the message type
switch ($messagetype)
{
"Error" {$MessageIcon = [System.Windows.Forms.ToolTipIcon]::Error}
"Info" {$MessageIcon = [System.Windows.Forms.ToolTipIcon]::Info}
"Warning" {$MessageIcon = [System.Windows.Forms.ToolTipIcon]::Warning}
Default {$MessageIcon = [System.Windows.Forms.ToolTipIcon]::None}
}
#display the balloon tipe
$Notify.showballoontip($Notification_timeout,$MessageTitle,$MessageText,$MessageType)
}
Show-Notification -MessageType Info -MessageText 'some message' -MessageTitle 'New Alert'
Update
Modifying your posted code to match a few items in mine, allows your code to work in the ISE, console as expected.
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$notifyobj = New-Object System.Windows.Forms.NotifyIcon
# I don't have your icon, so, using what I know I can reach
$notifyobj.Icon = [system.drawing.icon]::ExtractAssociatedIcon((join-path $pshome powershell.exe))
$notifyobj.BalloonTipTitle = "New Message"
$notifyobj.BalloonTipText = "C"
$notifyobj.Visible = $True
$notifyobj.ShowBalloonTip(1000)
$notifyobj.Dispose()

Powershell - Not able to pass remote session variable back to local system

I am trying to figure out what I am doing wrong here. Very new to powershell so be gentle... Trying to run a PSSession on remote system (reading in from list of systems). Then trying to return the value for missing patches to my local system to then export to CSV. I am looking solely for a number to be returned. The value gets displayed in the Powershell window when inside the Invoke-command but then at the bottom of the script nothing is shown. Can anyone offer some advice how I can pass that value back to my system to then be able to export to a csv? Any advice would be greatly appreciated.
$array1 = Get-Content "C:\Users\******\Desktop\Server_List.txt"
$ReportResults = New-Object System.Collections.Generic.List[System.Object]
$Searchresult = #()
#parse thru each machine name in
foreach ($MachineName in $array1)
{
Write-host $MachineName
$session = New-PSSession -ComputerName $MachineName
Invoke-Command -Session $session {
Param($ReportResults)
#Get All Assigned updates in $SearchResult
$UpdateSession = New-Object -ComObject Microsoft.Update.Session
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$SearchResult = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and
IsInstalled=0")
Write-Host "total=$($SearchResult.updates.count)"
$ReportResults.add($SearchResult)
} -ArgumentList $ReportResults
Remove-PSSession $session
}
$ReportResults # | export-csv C:\Users\******\Desktop\Compprogs\Test.csv -
Notypeinformation
You've to "mark" parameter as ref. See this link for further info.
Alternativelly you can return your desired value via Write-Output. Example:
$returnValue = Invoke-Command -ScriptBlock {
Write-Output "Hello World"
}
# $returnValue should include "Hello World"
Write-Host $returnValue
Be aware that when you use Write-Ouput multiple times at Invoke-Command $returnValue will include ALL values wrote to the output steram via Write-Ouput.
Hope that helps

Setting the "Description" on a Document Library using PnP PowerShell for SharePoint Online

I am trying to set the description on a Document Library in SharePoint Online using the PnP-PowerShell Commands, but it seems to be very intermittent in working, so I wanted to check what the correct way to do it is?
I create a new library with:
New-PnPList -Template DocumentLibrary -Title "TempLibrary"
Then try to set the Description with:
$l = Get-PnPList -Identity TempLibrary
$l.Description = "My Description Here"
Now clearly that doesn't work since I need to send the changes back with CSOM I assume?
So then I tried the following:
$ctx = Get-PnPContext
$l = Get-PnPList -Identity TempLibrary
$l.Description = "My Description Here"
$ctx.ExecuteQuery()
But this still didn't seem to work.
Any thoughts anyone has on how to do this reliably would be greatly appreciated.
Many thanks,
D.
UPDATE
Eurgh... This seems to work, but is this right? Is it expected? Doesn't feel very PowerShell like...
New-PnPList -Title "Test5" -Template DocumentLibrary
$t = Get-PnPList -Identity Test5
$ctx.Load($t)
$ctx.ExecuteQuery()
$t.Description = "Test5 Description"
$t.Update()
$ctx.ExecuteQuery()
Without loading the list you will not be able to set the description or other properties so the code is correct.
$ctx.Load($t)
Why do you think this is not PS like? :) Curious...
Use the following script. Hope it helps.
Add - PSSnapin Microsoft.SharePoint.PowerShell
function CreateList($spWeb, $listName)
{
$spTemplate = $spWeb.ListTemplates["Document Library"]
$spListCollection = $spWeb.Lists
$spListCollection.Add($listName, $listName, $spTemplate)
}
Function SetDescription($spWeb, $listName)
{
$path = $spWeb.url.trim()
$spList = $spWeb.GetList("$path/Lists/$listName")
$spList.Description = "--Your Desired Description--"
$spList.Update()
}
$siteCollectionUrl = "--Your Site Collection Url--"
$listName = "--Your Desired List Name--"
$spWeb = Get - SPWeb - Identity $siteCollectionUrl
CreateList $spWeb $listName
SetDescription $spWeb $listName

Powershell to install .\file errors, but when given full location C:\Users.... doesn't error

I have a script below that errors when trying to access a file, however if I change the location of the .msi file in the -argumentlist to a full address it succeeds, but I can't have it run like that as the address will change when I submit it to be packaged for SCCM deployment.
Function Get-OSCComputerOU
{
$ComputerName = $env:computername
$Filter = "(&(objectCategory=Computer)(Name=$ComputerName))"
$DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher
$DirectorySearcher.Filter = $Filter
$SearcherPath = $DirectorySearcher.FindOne()
$DistinguishedName = $SearcherPath.GetDirectoryEntry().DistinguishedName
$OUName = ($DistinguishedName.Split(","))[1]
$OUMainName = $OUName.SubString($OUName.IndexOf("=")+1)
$OUMainName
}
$strOU = Get-OSCComputerOU
$strTrueOU=$strOU.split('_')[1]
$strCSV=Import-Csv \\SERVER\SHARE\FOLDER\CSV.csv
$strRoomChannel=$strCSV | where {$_.Room -eq $strTrueOU} | % channel
IF ($strRoomChannel){
$strRoomFoundArg="/i .\Installers\MSI.msi CHANNEL=$strRoomChannel"
Start-Process msiexec -ArgumentList $strRoomFoundArg -wait
} ELSE {
msg * "Channel is missing, and can not install correctly, please call tech support on Ext: to have this rectified, it's a quick fix."
}
When I use a full address such as below, it installs fine.....what's the deal.
Function Get-OSCComputerOU
{
$ComputerName = $env:computername
$Filter = "(&(objectCategory=Computer)(Name=$ComputerName))"
$DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher
$DirectorySearcher.Filter = $Filter
$SearcherPath = $DirectorySearcher.FindOne()
$DistinguishedName = $SearcherPath.GetDirectoryEntry().DistinguishedName
$OUName = ($DistinguishedName.Split(","))[1]
$OUMainName = $OUName.SubString($OUName.IndexOf("=")+1)
$OUMainName
}
$strOU = Get-OSCComputerOU
$strTrueOU=$strOU.split('_')[1]
$strCSV=Import-Csv \\SERVER\SHARE\FOLDER\CSV.csv
$strRoomChannel=$strCSV | where {$_.Room -eq $strTrueOU} | % channel
IF ($strRoomChannel){
$strRoomFoundArg="/i C:\Users\USERNAME\Desktop\Installers\MSI.msi CHANNEL=$strRoomChannel"
Start-Process msiexec -ArgumentList $strRoomFoundArg -wait
} ELSE {
msg * "Channel is missing, and can not install correctly, please call tech support on Ext: to have this rectified, it's a quick fix."
}
I get this error:
The difference between the two is that '.' is going to be resolved by the process you are calling, msiexec, which, like most processes, is going to use the process's CurrentDirectory for '.', which is different than the current location in PowerShell. You can see the difference if you compare Get-Location and [Environment]::CurrentDirectory] in PowerShell. They will be different if you start powershell and change the directory using Set-Location (aka cd).
The solution is to resolve the path in PowerShell before sending it over to msiexec:
$path = Convert-Path .\Installers\MSI.msi
$strRoomFoundArg = "/i `"$path`" CHANNEL=$strRoomChannel"
Start-Process msiexec -ArgumentList $strRoomFoundArg -wait
Turns out the script wasn't happy with the .\ in front of the MSI file.
If I kept the .\ I would get the error.
If I removed the .\ and just had MSI.msi then it worked fine.
I failed to mention that I had changed the active directory to my desktop to execute the script, my apologies #mike z
Thank you very much for your input however.

Powershell COM+ settings

I'm trying to set the following values with the powershell COMAdmin.COMAdminCatalog but I can't find the setting for the below in red. Any help would be appreciated.
Thanks
For the properties in question see the Authentication property and the AccessLevelChecks property for the Applications Collection under COM+ Administration Collections.
For a VBScript example on how to set the Authentication Level property see the answer to changing existing COM+ applications identity via vbs script.
It should be fairly straight forward to convert to PowerShell. Here's my guess:
$comAdmin = New-Object -comobject COMAdmin.COMAdminCatalog
$apps = $comAdmin.GetCollection("Applications")
$apps.Populate();
$app = $apps | Where-Object {$_.Name -eq "MyAppName"}
# Set Authentication to Packet Authentication
$app.Value("Authentication") = 4
# Set Security Level to Process and Component level
$app.Value("AccessChecksLevel") = 1
$apps.SaveChanges()
This was already answered, but here is my "Create New COM+ Application AND set property" script.
$comAdmin = New-Object -comobject COMAdmin.COMAdminCatalog
$apps = $comAdmin.GetCollection("Applications")
$apps.Populate();
$newComPackageName = "MyFirstCOMPackage"
$appExistCheckApp = $apps | Where-Object {$_.Name -eq $newComPackageName}
if($appExistCheckApp)
{
$appExistCheckAppName = $appExistCheckApp.Value("Name")
"This COM+ Application already exists : $appExistCheckAppName"
}
Else
{
$newApp1 = $apps.Add()
$newApp1.Value("Name") = $newComPackageName
$newApp1.Value("ApplicationAccessChecksEnabled") = 0 <# Security Tab, Authorization Panel, "Enforce access checks for this application #>
$saveChangesResult = $apps.SaveChanges()
"Results of the SaveChanges operation : $saveChangesResult"
}