Frage

I am trying to figure out how to write powershell script such that if powershell cannot connect to \10.10.10.10\C$\Users, it should attempt to connect to \10.10.10.10\C$\Documents and Settings

So far, I have the following code

$Win32OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName '10.10.10.10'
$SysDrv = $Win32OS.SystemDrive
$SysDrv = $SysDrv.Replace(":","$")
$ProfDrv = "\\" + '10.10.10.10' + "\" + $SysDrv
$ProfLoc = Join-Path -Path $ProfDrv -ChildPath "User"

try
{
    Get-ChildItem $ProfLoc | ? { $_.PsIsContainer} | Sort LastWriteTime -Descending | Select -expand  Name -First 1
}
catch [Exception]
{
     return "CannotFindLastUser"
}

If the path \10.10.10.10\C$\Users doesn't exist it gives an error

Get-ChildItem : Cannot find path '\\10.10.10.10\C$\Users' because it does not exist.

How to change code such that it attempts to connect to \10.10.10.10\C$\Documents and Settings, otherwise it throws a user-friendly message

EDIT

Here is the entire script where arguments is in the form 'sender-ip=10.10.10.10'

$line_array = @()
$multi_array = @()
[hashtable]$my_hash = @{}
$Sender_IP = $NULL
$Win32OS = $NULL
$Build = $NULL
$folder = $NULL
$SysDrv = $NULL

foreach ($i in $args){
   $line_array+= $i.split(" ")
}

foreach ($j in $line_array){
    $multi_array += ,@($j.split("="))
}

foreach ($k in $multi_array){
    $my_hash.add($k[0],$k[1])
}


$Sender_IP = $my_hash.Get_Item("sender-ip")

try{
    Test-Connection $Sender_IP -count 1 -ErrorAction Stop | out-null
}
catch [Exception]
{
    $userId = "userId=CannotPing"
    return $userId 
}

try{
    $OS = (Get-WmiObject Win32_OperatingSystem -ComputerName $Sender_IP).Name
}
catch [Exception]{
    $userId = "userId=CannotConnectToWMI"
    return $userId
}


$Win32OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Sender_IP
$SysDrv = $Win32OS.SystemDrive
$SysDrv = $SysDrv.Replace(":","$")
$ProfDrv = "\\" + $Sender_IP + "\" + $SysDrv
$ProfLoc = Join-Path -Path $ProfDrv -ChildPath "Users"

try{
    $userId = Get-ChildItem $ProfLoc | ? { $_.PsIsContainer} | Sort LastWriteTime -Descending | Select -expand  Name -First 1
    $userId = "userId="+$userId
    return $userId
}catch [Exception]
{
    $userId = "userId=CannotFindLastUser"
    return $userId
}
War es hilfreich?

Lösung

Use the Test-Path cmdlet to determine if a path exists and/or is available.

You may want to use Test-Connection to ping the server before testing the path.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top