我試着找了幾個,沒有運氣天的答覆後消失......映射網絡驅動器退出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
在這裏回答:http://stackoverflow.com/a/16665256/266876(使用-Scope Global) –