我将如何将其转换为 powershell?

问题描述

on error resume next                                             'allows the script to continue if an error occurs.
Set fso = CreateObject("Scripting.FileSystemObject")             'creates scripting object
Set objNetwork = CreateObject("wscript.Network")                 'creates an object for network scripting

'the next section maps network drives if they don't already exist

If Not fso.DriveExists("z") Then                                 'checks for an existing drive x
  objNetwork.MapNetworkDrive "z:","\\ptfg-fs-005p\204ISShare"         'maps network drive x to \\108wg-fs-05\204is
End If

If Not fso.DriveExists("Y") Then                                 'repeat of above for other drive letters
  objNetwork.MapNetworkDrive "Y:","\\108arw-fs-02\global"
End If

If Not fso.DriveExists("K") Then                                 'repeat of above for other drive letters
  objNetwork.MapNetworkDrive "K:","\\108arw-fs-02\apps"
End If

'the next section maps network printers

ptrName = "\\ptfg-mp-001v\204isispcl000"                          'creates a variable for the part of a printer name that is a constant
ptrs = array("3","4","5","6","7","8")
for each x in ptrs                                               'start of loop that will create the next printer
    addPtr = ptrName & x                                         'adds current number from loop to printer constant name
    objNetwork.addWindowsPrinterConnection addPtr                'adds printer
next                                                             'end of add printer loop

wScript.quit                                                     'ends script

解决方法

在直接意义上,您可以在 PowerShell 中实例化 COM 对象,例如:

$objFSO     = New-Object -ComObject "Scripting.FileSystemObject"
$objNetwork = New-Object -ComObject "wscript.Network"

因此相同的属性和方法可用...

注意:虽然在 VBScript 中很常见,但通常不赞成使用匈牙利符号,即 str...obj...

以上是直接翻译,但我认为从长远来看,最好使用更多原生 PowerShell 功能来模拟相同的功能。

您可以使用 Test-Path cmdlet Documented here 来测试驱动器是否存在。它将返回一个布尔值,因此替代方案可能类似于:

If( -not ( Test-Path 'k:' ) ) {
 # Do something
}

映射驱动器的 PowerShell 本机方法是使用 New-PSDrive cmdlet。文档 here

示例:

New-PSDrive -PSProvider Microsoft.PowerShell.Core\FileSystem -Name K -Root "\\108arw-fs-02\apps" -Persist

你可以用类似的方式声明数组:

$Printers = "Printer1","Printer2" # Etc...

还要注意可以使用数组子表达式:

$Printers = @( "Printer1","Printer2" ) # Etc...

要添加打印机,您可以使用 Add-Printer cmdlet,记录在案的 here

示例:

 Add-Printer -ConnectionName \\printServer\printerName

有多种循环结构可供选择。您可以在 PowerShell 文档中研究它们,但 ForEach 构造看起来像:

ForEach( $Printer in $Printers) {
 # Map your printer...
}