2014-06-10 76 views
2

我試着找了幾個,沒有運氣天的答覆後消失......映射網絡驅動器退出PowerShell腳本

我有一個PowerShell(V3.0)腳本檢查一個網絡驅動器並映射它,如果它尚未映射。腳本本身工作得很好,在腳本執行過程中映射和訪問驅動器,但腳本結束時,映射的驅動器將斷開連接。我正在使用應該保留驅動器映射的-Persist選項。

如果我從PowerShell提示符運行相同的命令,即使在退出PowerShell提示符時,驅動器也會映射並保持映射狀態。下面

# Drive letter to map to 
$destinationDriveLetter = "G" 
# Username to map the network drive 
$userName = "username" 
# Password to use when mapping 
$userPass = ConvertTo-SecureString "password" -AsPlainText -Force 

#check if Drive is already mapped 
if (Test-Path -LiteralPath $destinationDriveLetter":" -ErrorVariable errVar) { 
    Write-Host "Drive already mapped.`r`n" 
    Write-Host "Exiting script`r`n" 
    exit 
} 

Write-Host "Destination Driveletter $destinationDriveLetter not mapped. Doing it...`r`n" 

$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $userPass 
Write-Debug "Command: New-PSDrive -Persist -Name $destinationDriveLetter -PSProvider FileSystem -Root '\\server\share' -Credential $Credential -ErrorVariable errVar" 

New-PSDrive -Persist -Name $destinationDriveLetter -PSProvider FileSystem -Root '\\server\share' -Credential $Credential -ErrorVariable errVar 

if ($errVar) { 
    Write-Error "`r`nError mapping destination drive $destinationDriveLetter. Check!`r`n" 
} 
else { 
    Write-Host "Destination drive mapped successfully.`r`n" 
    # test if drive truly mapped and destination folder exist 
    Test-Path -LiteralPath $destinationDriveLetter":" -ErrorVariable errVar 
    # debugging, roar! 
    Write-Host "Drives during script:`r`n" 
    Get-PSDrive 
} 
# dirty fix to actually confirm that the drive is mapped during script execution 
pause 

示例代碼顯然,這裏的問題是在腳本中使用命令,但如何解決這一問題?我需要在服務器重啓後自動映射驅動器。使用UNC路徑將不起作用,因爲我使用的軟件不理解它們。

編輯:忘了說,OS我正在爲Windows Server 2012

+0

在這裏回答:http://stackoverflow.com/a/16665256/266876(使用-Scope Global) –

回答

1

下運行的是何種用戶帳戶的腳本?腳本必須以使用該驅動器的用戶身份運行。從獲取幫助:

get-help new-psdrive -parameter Persist 
<snipped> 
NOTE: Mapped network drives are specific to a user account. Mapped network drives that you create in sessions that 
are started with the "Run as administrator" option or with the credential of another user are not visible in session 
that started without explicit credentials or with the credentials of the current user. 
+1

腳本在需要使用驅動器的同一用戶下運行。我注意到另一個異常以及...如果我把驅動器映射到一個單獨的函數,驅動器映射消失,只要函數結束並且腳本返回到「main」。如果使用if-else比較(如果映射不做任何操作,否則映射它),那麼當腳本退出條件時,驅動器映射將丟失。 W00t? :) – ritzydh

+0

如果此腳本正在用戶的上下文中運行,則應刪除$憑證。這在3臺不同賬戶下的3臺電腦上運行,驅動器按預期持續運行。 – StephenP

0

我有同樣的,在我的情況下問題是,我從PowerShell命令窗口調用腳本。如果我通過右鍵單擊腳本「Run with Powershell」直接執行腳本,驅動器不會消失。

9

我發現即使使用-Persist參數,驅動器映射從登錄腳本運行時也會消失。

該問題已通過添加-Scope "Global"參數解決。

+1

謝謝soo。這真的有幫助。在我發表評論之前,我正在爲此工作幾個小時。 – Spencer

相關問題