PowerShell v2 Adding a Printer - powershell

I'm trying to create a PowerShell Script that allows me to add and configure a printer with 3 instances of the printer. This is what I have so far:
# Printer Info
$printerID = "HP Designjet Z3200 24in Photo"
$printerID1 = "HP Designjet Z3200 24in Photo - Canvas"
$printerID2 = "HP Designjet Z3200 24in Photo - Cover"
$printerIP = Read-Host 'What is the Poster Printer IP Address?'
$printerPort = "IP_$printerIP"
$printerModel = "HP Designjet Z3200 24in Photo"
# Speak with Ted about a specific place to put the poster driver pre-extracted
$driverINFPath = "C:\Velocity\HP WFP\Driver\hpdjz3200serieswx64pcl\hpi32pxs.inf"
# Build a new Local TCP Printer Port, naming it with values unique to the Printer ID:
$newPort = ([wmiclass]"Win32_TcpIpPrinterPort").CreateInstance()
$newPort.HostAddress = $printerIP
$newPort.Name = $printerPort
$newPort.Put()
# Add the printer
printui.exe /if /b "$printerID" /f "$driverINFPath" /u /r "$printerPort" /m "$printerModel"
printui.exe /if /b "$printerID1" /f "$driverINFPath" /u /r "$printerPort" /m "$printerModel"
printui.exe /if /b "$printerID2" /f "$driverINFPath" /u /r "$printerPort" /m "$printerModel"
I copied the part from an earlier post for the port part of the script. I'm trying to figure out what the .Put() is and I cannot find it anywhere. Any help would be much appreciated.

...Windows PowerShell accesses WMI through the .NET Framework and
System.Management class. Rather than using SWbemObject, Windows
PowerShell uses the System.Management.ManagementObject class. For
better or worse, this class uses a method named Put to save changes to
a read-write property.
From TechNet, which actually is comparing VBScript Put_ to PowerShell Put() calls.

Related

Running PowerShell Script in CMD (with popup window)

Hi I normally just right click and edit my scripts, then just run them through PowerShell ISE using the green arrow.
But I have a need to start /wait a script in a batch file. I want my script to run and then have the rest of the batch file to wait till the PowerShell script is closed. (Hence the start /wait)
And it works fine, but my issue is this:
it opens up fine but no matter if I choose the letters by the options or the numbers I set in the choice script it will either restart or close out depending on the choice.
**I had nice pictures to go with this but I don't have enough rep so here is a bit of code :(
powershell.exe Set-ExecutionPolicy -ExecutionPolicy Bypass
#Main Choice Script
$IP = New-Object System.Management.Automation.Host.ChoiceDescription '&Edit IP', 'Change IP
Address'
$Intro= New-Object System.Management.Automation.Host.ChoiceDescription '&Change Introscreen',
'Change Introscreen'
$Gecko = New-Object System.Management.Automation.Host.ChoiceDescription '&Replace Gecko',
'Change Gecko Folder'
$PCName = New-Object System.Management.Automation.Host.ChoiceDescription '&Host Name', 'Fix
Host Name'
$Firewall = New-Object System.Management.Automation.Host.ChoiceDescription '&Firewall
Settings', 'Fix Firewall Setting'
$Close = New-Object System.Management.Automation.Host.ChoiceDescription '&Close', 'Exit'
$options = [System.Management.Automation.Host.ChoiceDescription[]]
($IP,$Intro,$Gecko,$PCName,$Firewall,$Close)
$title = 'IT Tool'
$message = 'What do you want to do?'
$result = $host.ui.PromptForChoice($title, $message, $options,-1)
switch ('$result')
{
0 { "IP" }
1 { "Intro" }
2 { "Gecko" }
3 { "PCName" }
4 { "Firewall" }
5 { "Close" }
}
I cant seem to get the options to function right, I'm thinking:
CMD is too basic to open a prompt for choice window.
My code isn't setup to run outside ISE
** I'm fine that the cmd window is just text and not a popup, I just would like it to work.
Any help or tips would be appreciated.
As you mentioned you are willing to use batch-file I decided to post an option.
If your options are single commands per entry (or if you are willing to chain commands) you can preset the commands and use choice to select the option.
Note! Here I added some dummy commands to demonstrate how it works:
#echo off & cls
setlocal enabledelayedexpansion
set "sel="Edit IP","Change Introscreen","Replace Gecko",Hostname,Firewall,Close"
set "opt_1=ping localhost"
set "opt_2=echo something"
set "opt_3=echo Replace command here"
set "opt_4=hostname"
set "opt_5=echo firewall command here"
set "opt_6=exit /b"
:menu
set cnt=
for %%i in (%sel%) do (
set /a cnt+=1
echo !cnt!^) %%~i
set "_opt!cnt!=%%~i"
)
for /l %%c in (1,1,%cnt%) do set ch=!ch!%%c
choice /C %ch% /M "Enter Selection:"
echo You chose !_opt%errorlevel%!
!opt_%errorlevel%!
pause
set ch= & cls & goto :menu
You could of course just use a plain text menu directly in your batch file, by using the built-in choice.exe utility.
#Echo Off
:Menu
ClS
Echo 1. Edit IP
Echo 2. Change Introscreen
Echo 3. Replace Gecko
Echo 4. Host Name
Echo 5. Firewall
Echo 6. Close
%SystemRoot%\System32\choice.exe /C 123456 /M "What do you want to do"
GoTo Item%ERRORLEVEL%
:Item1
Echo Changing IP Address
%SystemRoot%\System32\timeout.exe /T 2 1>NUL
GoTo :Menu
:Item2
Echo Changing Introscreen
%SystemRoot%\System32\timeout.exe /T 2 1>NUL
GoTo :Menu
:Item3
Echo Changing Gecko Folder
%SystemRoot%\System32\timeout.exe /T 2 1>NUL
GoTo :Menu
:Item4
Echo Fixing Host Name
%SystemRoot%\System32\timeout.exe /T 2 1>NUL
GoTo :Menu
:Item5
Echo Fixing Firewall Setting
%SystemRoot%\System32\timeout.exe /T 2 1>NUL
GoTo :Menu
:Item6
Echo Exiting
%SystemRoot%\System32\timeout.exe /T 2 1>NUL
Exit /B

Grab an unknown IP from ipconfig and edit an unknown .ini line with that IP with BATCH script

Currently i have a setup where a program wants my LAN IP to attach their data to and this LAN IP are always random when i reboot my system. My LAN IP is always different as i do use a VPN so it's kind of a hazzle everytime i either change network or reboot as i do need to run the program, change it, restart it.
I do have a script that will make a variable with the correct IP, as it's always the first IPv4 Address. I did find it on this site.
set ip_address_string="IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set ip_address_string="IP Address"
for /f "usebackq tokens=2 delims=:" %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do (
echo Your IP Address is: %%f
goto :eof
)
This is golden, but every .ini edit post i've found do not actually work for me as it prints the line infinetly instead of editing the line.
As the size of the .ini is unknown i do need a powershell script in order for it to work as BATCH has limitations.
One user on Stackoverflow had this code:
(Get-Content C:\ProgramData\Nuance\NaturallySpeaking12\nssystem.ini) | ForEach-Object { $_ -replace 'Default NAS Address=.*','Default NAS Address=BHPAPPDGN01V' } | Set-Content C:\ProgramData\Nuance\NaturallySpeaking12\nssystem.ini
The line that needs to be changed is mostly random. Well, not random, but it'll move sometimes as users can make some changes and it'll push the IP line down or up depending on the settings.
I'm a bit novice when it comes to BATCH and powershell and i haven't figured out a way to transfer information to powershell. For example, BATCH will grab the IP, make a variable, run a powershell script editing the .ini. I do remember having a code that grabbed the IP to clipboard but i cannot find it in this moment.
My current progress is
#echo off
setlocal EnableExtensions
echo Exiting PROGRAM...
taskkill /IM PROGRAM.exe
timeout /t 1 /nobreak>nul
:check
for /F %%a in ('tasklist /NH /FI "IMAGENAME eq PROGRAM.exe"') do if %%a == PROGRAM.exe goto waiting
echo Restarting PROGRAM...
start "" "%ProgramFiles%\PROGRAM\PROGRAM.exe"
timeout /t 1 /nobreak>nul
exit
:waiting
echo PROGRAM is still running. Retrying...
timeout /t 3 /nobreak>nul
goto check
I don't need setlocal EnableExtensions but i did try to get it to work and it was needed then.
Currently the script look if the program is running, if it is, kill it softly (wait for it to natively quit) then restart it. My goal is to kill it softly, edit the .ini and then restarting it with the changed made.
A pure PowerShell solution would be most likely the best for this task because of Windows command processor cmd.exe is not designed for editing files.
But here is a pure batch file solution for determining the current IPv4 address and write it into the INIĀ file if it contains currently a different address.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "IniFile=C:\ProgramData\Nuance\NaturallySpeaking12\nssystem.ini"
if exist "%IniFile%" goto GetIpAddress
echo ERROR: File missing: "%IniFile%"
echo/
pause
goto EndBatch
:GetIpAddress
set "ip_address_string=IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set "ip_address_string=IP Address"
rem The string above must be IP-Adresse on a German Windows.
for /F "tokens=2 delims=:" %%I in ('%SystemRoot%\System32\ipconfig.exe ^| %SystemRoot%\System32\findstr.exe /C:"%ip_address_string%"') do set "IpAddress=%%I" & goto IpAddressFound
echo ERROR: Could not find %ip_address_string% in output of ipconfig.
echo/
pause
goto EndBatch
:IpAddressFound
set "IniEntry=Default NAS Address"
rem Remove leading (and also trailing) spaces/tabs.
for /F %%I in ("%IpAddress%") do set "IpAddress=%%I"
rem Do not modify the INI file if it contains already the current IP address.
%SystemRoot%\System32\findstr.exe /L /X /C:"%IniEntry%=%IpAddress%" "%IniFile%" >nul
if errorlevel 1 goto UpdateIniFile
echo The file "%IniFile%"
echo contains already the line: %IniEntry%=%IpAddress%
echo/
goto EndBatch
:UpdateIniFile
for %%I in ("%IniFile%") do set "TempFile=%%~dpnI.tmp"
(for /F delims^=^ eol^= %%I in ('%SystemRoot%\System32\findstr.exe /N "^" "%IniFile%" 2^>nul') do (
set "Line=%%I"
setlocal EnableDelayedExpansion
set "Line=!Line:*:=!"
if not defined Line echo(
for /F delims^=^=^ eol^= %%J in ("!Line!") do (
set "FirstToken=%%J"
if "!FirstToken!" == "%IniEntry%" (
echo %IniEntry%=%IpAddress%
) else echo(!Line!
)
endlocal
))>"%TempFile%"
rem Replace the INI file by the temporary file, except the temporary file is empty.
if exist "%TempFile%" (
for %%I in ("%TempFile%") do if not %%~zI == 0 (
move /Y "%TempFile%" "%IniFile%" >nul
echo Updated the file "%IniFile%"
echo with the %ip_address_string% "%IpAddress%" for INI entry "%IniEntry%".
echo/
)
del "%TempFile%" 2>nul
)
:EndBatch
endlocal
Please read my answer on How to read and print contents of text file line by line?
It explains the awful slow code to update the INI file using just Windows Commands.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
echo /?
endlocal /?
findstr /?
for /?
goto /?
if /?
ipconfig /?
move /?
pause /?
rem /?
set /?
setlocal /?
See also Single line with multiple commands using Windows batch file for an explanation of operator &.
Read the Microsoft article about Using command redirection operators for an explanation of >, 2>nul and |. The redirection operator | must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded command line with ipconfig and findstr with using a separate command process started in background with %ComSpec% /c and the command line between the two ' appended.
Mofi had a great batch solution, but he mentioned that CMD was not really designed for file output like this. So here's a pure powershell solution that should do what you want. It does borrow a bit from the powershell snippet you included in your question.
$ip = Get-NetIPAddress -InterfaceAlias "Ethernet" #| Out-File PathTo:\net.ini
$content = get-content PathTo:\net.ini | ForEach-Object { $_ -replace "172.23.*","$($ip.IPAddress)"}
$content | Set-Content PathTo:\net.ini
Obviously this depends on you knowing the Interface Alias you want to grab, but you can find that easily with Get-NetIPAddress, and it shouldn't change. You'll also need to update the path information.

Retrieving Information from Task Manager using Powershell

Am currently working with a business automation software, the idea is Robots simulate user actions. Is there a way to access the task manager through powershell as the robots are meant to manipulate the task manager e.g Pass in a value to start a new task, end a process and view the performance of the cpu etc . I know this can be achieved using powershell scripts or better still vb script. Please how do I achieve this?
For the records, I am using a windows 7 machine with powershell version 3.0.
List running processes and terminate calculator.
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
For Each objItem in colItems
msgbox objItem.ProcessID & " " & objItem.CommandLine
If objItem.name = "Calculator.exe" then objItem.terminate
Next
Monitor for notepad exiting and restart it.
Also available is Win32_ProcessStartTrace and Win32_ProcessStartStopTrace
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set objEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM Win32_ProcessStopTrace")
Do
Set objReceivedEvent = objEvents.NextEvent
msgbox objReceivedEvent.ProcessName
If lcase(objReceivedEvent.ProcessName) = lcase("Notepad.exe") then
Msgbox "Process exited with exit code " & objReceivedEvent.ExitStatus
WshShell.Run "c:\Windows\notepad.exe", 1, false
End If
Loop
The WMIC command line program uses same classes as vbscript (and powershell), so you can use it for help.
wmic /?
wmic path win32_process /?
or using the only available in wmic aliases of process alias for win32_process
wmic process /?
wmic process call /?
wmic process get /?
and for other uses of wmic
wmic /node /?
wmic /format /?
Try get-process for a list of running processes.
With i.e. get-process myprocess |stop-process you can stop myprocess.
For new processes you can & them ( & C:\Windows\System32\taskmgr.exe) or use the start-process (check Get-help Start-Process for help ) cmdlet.
You can also use Invoke-WmiMethodfor this :
Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList taskmgr.exe'

for /f is not working in .bat file but it works with command prompt in windows 2003

for /f "tokens=1-7 delims=,: " %a in ('query user ^| find /i "disc"') do logoff %b
This above code is used for logoff remote desktop users where state is "Disconnected" in windows 2003.It will work perfect when I run in command prompt. But it will not run when I made a .bat file or .cmd file in windows 2003.so may know where i am going wrong?
Inside batch files the percent signs used in the for replaceable parameters need to be escaped
for /f "tokens=1-7 delims=,: " %%a in ('query user ^| find /i "disc"') do logoff %%b
User585,
Yes, inorder to implement the for loop inside a bat/cmd session, you need to place the variable with
%%a
like this
for /f %%a in (.\hosts) do quser /server:\\%%a

Powershell v2 - Installing Printer

I'm trying to automate printer installation on windows 7 x64, by using Powershell script. So far I have a script that successfully creates TCP/IP port but gives me an error - The arguments are invalid, when it executes printer installation part of the code. Any ideas on how to fix the problem and successfully install a printer through the Powershell? The code is as follows:
$hostAddress = "172.16.2.24"
$portNumber = "9100"
$computer = $env:COMPUTERNAME
$wmi= [wmiclass]"\\$computer\root\cimv2:win32_tcpipPrinterPort"
#$wmi.psbase.scope.options.enablePrivileges = $true
$newPort = $wmi.createInstance()
$newPort.hostAddress = $hostAddress
$newPort.name = "IP_" + $hostAddress
$newPort.portNumber = $portNumber
$newPort.SNMPEnabled = $false
$newPort.Protocol = 1
$newPort.put()
CMD.EXE /C "printui.exe /if /b "Test Printer" /f C:\inetpub\wwwroot\ftp\Prdrivers\HP Universal Print Driver\pcl6-x64-5.7.0.16448\hpbuio100l.inf /r "IP_172.16.2.24" /m "HP Laser Jet P3015""
Question Update: This is the working CMD code, so how do I incorporate it into the Powershell code above ?
printui.exe /if /b "HP Universal Printing PCL 6" /f "C:\inetpub\wwwroot\ftp\Prdrivers\HP Universal Print Driver\pcl6-x64-5.7.0.16448\hpbuio100l.inf" /u /r "IP_172.16.2.24" /m "HP Universal Printing PCL 6"
To embed double-quotes within a double-quoted string you need to escape them. Since you are not using variables, it is easier to use a single quoted string e.g.:
CMD.EXE /C 'printui.exe /if /b "Test Printer" /f C:\inetpub\wwwroot\ftp\Prdrivers\HP Universal Print Driver\pcl6-x64-5.7.0.16448\hpbuio100l.inf /r "IP_172.16.2.24" /m "HP Laser Jet P3015"'
If you ever need to use PowerShell variables inside this string, then you will need to switch back to double quotes and escape the necessary DQ characters e.g:
CMD.EXE /C "printui.exe /if /b `"$PrinterName`" /f C:\inetpub\wwwroot\ftp\Prdrivers\HP Universal Print Driver\pcl6-x64-5.7.0.16448\hpbuio100l.inf /r `"IP_172.16.2.24`" /m `"HP Laser Jet P3015`""
Sorry, but im not sure why you are calling CMD /C #PARAMS. I am just calling the printui.exe directly and it is working, and I only double quote the Args
# Printer Info, I keep this in an SQL DB, and return these values with a query:
$printerID = "<PrinterNameOrID>"
$printerIP = "<PrinterIP>"
$printerPort = "IP_$printerIP"
$printerModel = "<PrinterModelFromINF>"
$driverINFPath = "<UNCPathToDriverINF>"
# Build a new Local TCP Printer Port, naming it with values unique to the Printer ID:
$newPort = ([wmiclass]"Win32_TcpIpPrinterPort").CreateInstance()
$newPort.HostAddress = $printerIP
$newPort.Name = $printerPort
$newPort.PortNumber = "9100"
$newPort.Protocol = 1
$newPort.Put()
# Add the printer
printui.exe /if /b "$printerID" /f "$driverINFPath" /u /r "$printerPort" /m "$printerModel"
I know this has already been answered but you could borrow the code I have in this Excel Workbook (there is a link in the article). I realize it uses VBS but these are built in scripts in Windows and cutting / pasting into Excel has saved me many times and I've installed thousands of printers this way
best-tool-for-printer-creation-excel-vs-print-management-console
Try this:
runas /user:Contoso.com\user1 "printui.exe /if /b \"Test Printer\" /f \"C:\inetpub\wwwroot\ftp\Prdrivers\HP Universal Print Driver\pcl6-x64-5.7.0.16448\hpbuio100l.inf\" /r \"IP_172.16.2.24\" /m \"HP Laser Jet P3015\""