icm New-Item Not Creating Subfolder

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Aaron Hardy Aaron Hardy 3 months ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #45159
    Profile photo of Aaron Hardy
    Aaron Hardy
    Participant

    Likely a simple fix; for some reason the first icm works fine, but the second one does not do anything. It's as though Test-Path is not including the subdirectory specified in $c, though it does contain a string value.

    In a nutshell:
    1. Loop through list of remote computers in text file.
    2. Check if given remote computer is online.
    3. If remote computer online, icm on remote computer to create C:\folder if it does not already exist (this works).
    4. icm on backup server (hardcoded name) to create subfolder X:\backups\folder\ComputerName if does not already exist (this does not work).
    5. Else, return message.

    foreach ($c in $Computers) {
    		
    		if ((Test-Connection -ComputerName "$c" -Quiet -Count 1))
    		{	
    			Invoke-Command -ComputerName $c -Command {
    				if (-not (Test-Path C:\folder))
    				{
    # This works on remote server ($c).
    					New-Item -Path C:\folder -ItemType Directory
    				}
    			};
    			
    # This does not work on backup server. Permissions are correct. $c is assigned as the subfolder name.
    			Invoke-Command -ComputerName "BACKUPSERVER" -Command {
    				if (-not (Test-Path ("X:\Backups\folder\$c")))
    				{
    					New-Item -Path "X:\Backups\folder" -Name "$c" -ItemType Directory -Force
    				}
    			}
            }
            else
            {
                Write-Warning "Unable to establish connection with system $c ($Date)"
                Write-Output ''
            }
        }

    Would appreciate some insight to this.

    #45169
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Variable $c has no meaning on the remote machine. You've defined it locally. Either use $using:c, or look into the -ArgumentList parameter of Invoke-Command.

    See https://devopscollective.gitbooks.io/the-big-book-of-powershell-gotchas/content/manuscript/remote-variables.html

    #45173
    Profile photo of Aaron Hardy
    Aaron Hardy
    Participant

    Thanks Don!

    I knew better and somehow kept overlooking it. Helps to take a break sometimes.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.