我正在尝试创建执行一些操作的登录脚本。我需要它来完成以下内容。
我需要这样做是因为我们在网络上更改了一些打印机名称,并且我们希望使用新名称重新映射所有打印机并安装一些其他打印机。我目前有一个调用.ps1文件的批处理文件。这是两个文件中的代码。
Login.bat
@echo off
powershell -command Set-ExecutionPolicy Unrestricted -force
Powershell -command " & '\\server\share\MyPSScript.ps1'"
Login.ps1
# Save current default printer.
Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true" | foreach {$_.portname} -OutVariable CurDefPrinter
# Deletes all network printers.
Get-WmiObject Win32_Printer | where{$_.Network -eq ‘true‘} | foreach{$_.delete()}
# Maps all network printers.
add-printer -connectionname "\\server\ricoh"
add-printer -connectionname "\\server\hp"
# Set default printer
(Get-WmiObject -Class Win32_Printer -Filter "portame='$CurDefPrinter'").SetDefaultPrinter()
当我运行时,我收到此错误。
C:\Temp\Scripts>Login.bat
C:\Temp\Scripts>REM @echo off
10.0.0.155
Get-WmiObject : Invalid query "select * from Win32_Printer where portame='10.0.0.155'"
At \\server\share\login.ps1:12 char:2
+ (Get-WmiObject -Class Win32_Printer -Filter "portame='$CurDefPrinter' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
You cannot call a method on a null-valued expression.
At \\server\share\Login.ps1:12 char:1
+ (Get-WmiObject -Class Win32_Printer -Filter "portame='$CurDefPrinter' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
非常感谢任何帮助!
答案 0 :(得分:0)
你拼错了PortName错误,所以没有回复任何内容你在($null)
上调用方法
(Get-WmiObject -Class Win32_Printer -Filter "portname='$CurDefPrinter'").SetDefaultPrinter()
答案 1 :(得分:0)
如果您不需要使用“查询和过滤”选项,则可以这样执行:
#to get the current default printer
$default = Get-WmiObject -Class Win32_Printer | Where-Object {$_.Default -eq "true"}
#to reset the default printer
$default.SetDefaultPrinter()
至少它在我的环境中有效。