Windows – Reauthenticate a Remote Connection via PowerShell Script

powershelluncwindows

I have a PowerShell v1 script that connects to a remote server via UNC path. After a reboot, authentication is needed because Windows apparently will not remember so the script cannot connect to the remote server

How is this situation handled programmatically from within a PowerShell script?

I need to

1) reauthenticate

2) connect to remote server via UNC path

Perhaps the "net" command???

How can I do this in my PowerShell script?

Get-ChildItem -Path "\\REMOTESERVER\Data\Files" -Filter "*.journal" | 
Where-Object { $_.Name -match 'Daily_Reviews\[\d{1,12}-\d{1,12}\].journal' } | 
Sort-Object -Property CreationTime | ForEach-Object 
{

    $sourcefile = $_.Name
    [...]


 }

Thanks

Best Answer

You can store credentials in your scripts. You can then use the PSCredential object with the New-PSDrive cmdlet to connect to the share. The PSDriveInfo object is then accessible to your script during the length of the session.

$username = 'domain\username'
$password = 'secret'

$password = $password | ConvertTo-SecureString -AsPlainText -Force

$credential = New-Object System.Management.Automation.PSCredential($username, $password)

New-PSDrive -Name journals -PSProvider FileSystem -Root '\\remoteserver\data\files' -Credential $credential | ForEach-Object { Set-Location "$_`:" }

Get-ChildItem -Filter "*.journal"