Add User Name to File Path - powershell

I am attempting to add a username to file path so I can create a directory that contains their username.
This is how I want my User Folder to Look:
D:\Test Space\ArtP$
When I do this in a Shell:
PS > $samAccountName = "ArtP"
PS > $user_folder = "D:\Test Space\$samAccountName$"
PS > $user_folder
D:\Test Space\ArtP$
It works as expected. I then try this in a script that is supposed to do this on a remote server:
$samAccountName = "ArtP"
$user_folder = "D:\Test Space\$samAccountName$"
invoke-command -computername remote_server -scriptblock {
new-item -path $user_folder -type directory -Force
}
I get the following error:
Cannot bind argument to parameter 'Path' because it is null.
+ CategoryInfo : InvalidData: (:) [New-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.NewItemComm
and
It is saying my path is null and I believe there is some discrepancy about how the shell interprets quotes and how the script is. How do I get my user name in the file path above properly?

Refer to the section about Passing Local Values in How to pass arguments for remote commands
$samAccountName = "ArtP"
$user_folderLocalValue = "D:\Test Space\$samAccountName"
With Param:
invoke-command -computername remote_server -scriptblock {
param($user_folder)
new-item -path $user_folder -type directory -Force
} -Args $user_folderLocalValue
or with $args
invoke-command -computername remote_server -scriptblock {
new-item -path $args[0] -type directory -Force
} -Args $user_folderLocalValue

Related

Create folder on remote computer using PowerShell

The intention is to create a folder on a remote computer C drive.
I'm trying to run this:
$stageSvrs | %{
Invoke-Command -ComputerName $_ -ScriptBlock {
$setupFolder = "c:\Support\test1"
Write-Host "Creating Support Folder"
New-Item -Path $setupFolder -type directory -Force
Write-Host "Folder creation complete"
}
}
but I get the following error:
Invoke-Command : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
At \\company.local\share\share\userdata\username\Documents\WindowsPowerShell\CreateFolder.ps1:2 char:39
+ Invoke-Command -ComputerName $_ -ScriptBlock {
+ ~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand

Unable to execute some commands in ps1 file from powershell

I have a windows service running on one of the Azure VMs.
So whenever a deployment has to be done, we copy the binaries manually. So now, I'm writing a script to do that.
Besically the binaries are in the form of a zip folder in MachineA. That zip folder is copied to MachineB (where windows service is running).After copying, the files are extracted and then zip folder is deleted. Then after the service is started.
To do this I have the below script.
#get session details
$UserName = "$IPAddress\$adminUsername"
$Password = ConvertTo-SecureString $adminPassword -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($UserName, $Password)
$s = New-PSSession -ComputerName $IPAddress -Credential $psCred
#stop the service
Invoke-Command -Session $s -ScriptBlock {Stop-Service -Name "ServiceName" -Force}
#delete existing binaries in destination machine
$tempDestPath = $destinationPath + "\*"
Invoke-Command -Session $s -ScriptBlock {param($tempDestPath)Remove-Item $tempDestPath -Recurse} -ArgumentList $tempDestPath
#copy binaries zip folder in destination machine
Copy-Item -Path $sourcePath -Destination $destinationPath -ToSession $s -Recurse
#extract zipfolder in destination machine
$zipFilePath = $destinationPath + "\" + $fileName
Invoke-Command -Session $s -ScriptBlock {param($zipFilePath,$destinationPath) Expand-Archive $zipFilePath -DestinationPath $destinationPath}-ArgumentList $zipFilePath,$destinationPath
#delete zipfolder in destination machine after extraction
Invoke-Command -Session $s -ScriptBlock {param($zipFilePath)Remove-Item –path $zipFilePath}-ArgumentList $zipFilePath
#start the service
Invoke-Command -Session $s -ScriptBlock {Start-Service -Name "ServiceName"}
This is working fine when I open Windows powershell in MachineA and execute these commands one by one.
But when I put the exact same commands in a ps1 file and execute that file, I'm getting the below error:
At C:\ScriptTest\test.ps1:13 char:95
+ ... -ScriptBlock {Start-Service -Name "ServiceName"}
+ ~~
The string is missing the terminator: ".
At C:\ScriptTest\test.ps1:11 char:42
+ Invoke-Command -Session $s -ScriptBlock {param($zipFilePath)Remov ...
+ ~
Missing closing '}' in statement block or type definition.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
Where am I missing this terminator. I'm not able to figure out. Any help is highly appreciated.
Turns out a - in one of the commands is wrong.
I have replaced this line
Invoke-Command -Session $s -ScriptBlock {param($zipFilePath)Remove-Item –path $zipFilePath}-ArgumentList $zipFilePath
with this line
Invoke-Command -Session $s -ScriptBlock {param($zipFilePath)Remove-Item -path $zipFilePath}-ArgumentList $zipFilePath
The hyphen in from of the path is slightly different.I was able to figure out from this answer

Trouble using Invoke-Command with ScriptBlock and -ArgumentList

I'm new to powershell and can't figure why I get the following error
Invoke-Command : A positional parameter cannot be found that accepts argument
'D:\Deploy\file.zip'.
At D:\source\Scripts\Build-Deploy\Build-Deploy\ServersDeploy.ps1:105 char:5
Invoke-Command -ComputerName $servers -ScriptBlock {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
This is the script being run
params([string[[]]$servers, [string]$dest_package_path, [string]$src_package_path,[string]$deploy_script)
Invoke-Command -ComputerName $servers -ScriptBlock {
param($dest_package_path,$src_package_path,$deploy_script)
Write-Output "Destination path = $dest_package_path"
Write-Output "Copying zip $src_package_path to the destination host"
New-Item -ItemType Directory -Force -Path $dest_package_path
Write-Output "Directory Created"
Copy-Item -Path $src_package_path -Destination $dest_package_path -Force
Write-Host "Copying remote deploy scripts to the destination host"
Copy-Item -Path $deploy_script -Destination $dest_package_path -Force
} -ArgumentList $dest_package_path $src_package_path $deploy_script
Because you separated the arguments with spaces instead of a comma. That makes them new arguments to Invoke-Command.
-ArgumentList a single parameter that takes an array:
Invoke-Command -ComputerName $servers -ScriptBlock {
# Stuff
} -ArgumentList $dest_package_path,$src_package_path,$deploy_script

PowerShell - Error in path while Set-FsrmQuota

I'm trying to make a script that changes the quota of a specific directory on a remote server. For that I'm using the following code ($Quota and $chosen_username enter as parameters):
$prefix_path = "C:\Shares\Users\";
$path = $prefix_path + $chosen_username;
if($Quota){
invoke-command -computername $servername {Set-FsrmQuota -path $path -Size $Quota+"GB"}
}
if((invoke-command -computername $servername {Get-FsrmQuota -path $path} | select #{n='QuotaSize'; e={$_.Size / 1gb -as [int]}}).QuotaSize -eq $Quota){
return "Success."
} else {
return "Failed."
}
And it is giving me this error:
Cannot bind argument to parameter 'Path' because it is an empty string.
+ CategoryInfo : InvalidData: (:) [Set-FsrmQuota], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Set-FsrmQuota
+ PSComputerName : ServerName
I've done debug and the value of $path is correct.
When using invoke-command on a remote computer, the local variables are unknown for the remote host, so you have to use either:
the using prefix for PS >= 3
invoke-command -computername $servername {Set-FsrmQuota -path $using:path -Size $using:Quota+"GB"}
the argumentlist parameter for PS < 3
invoke-command -computername $servername {Set-FsrmQuota -path $args[0] -Size $args[1]+"GB"} -argumentlist $path,$quota

using PsFtp to upload a file to FTP Powershell

I've been wracking my brain on this issue and can't seem to fix it. I'm trying to upload a file to FTP using PSFTP.
The script I'm using:
#------------------------------------------------------
#local variables
$ftp_server = "SERVERNAME"
$ftp_path = "/FTPPATH/PATH"
$local = "C:\ftp\"
$local_in = Join-Path $local "In"
$local_out = Join-Path $local "Out"
$session = "my_ftp_session"
# set up credentials object
$username = "FFandP"
$password = Get-Content "$local_out\Credentials.txt" | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
Set-FTPConnection -Server $ftp_server -Credentials $cred -Session $session -KeepAlive -confirm -UseBinary
Get-ChildItem -Path $local_out |
% {
$ftp_file = "$ftp_path/$($_.Name)" # determine item fullname
Add-FTPItem -Path $ftp_file -LocalPath $_.FullName -Session $session -
}
# -------------------------------------------------
And the error I receive:
Add-FTPItem : Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (550) File
unavailable (e.g., file not found, no access)."
At line:22 char:1
+ Add-FTPItem -Path $ftp_file -LocalPath $_.FullName -Session $session
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Add-FTPItem
I've tried running the Add-FTPitem command by itself, but I get the same error.
I can upload to the FTP using FileZilla. I have also tried removing the variables and using hard-coded paths; I get the same error.
Any ideas?
The answer in #Josh's comment solved it for me. Run Add-FTPItem with the -Overwrite parameter.
Add-FTPItem -Path $remotePath -LocaPath $myPath -Overwrite
It took me a moment to figure out this problem, but here is my solution (I had the same problem).
When using Add-FTPItem the -Path parameter must not include the filename itself.
Add-FTPItem
-Path "ftp://SomeServer/SomeDir/"
-LocalPath "C:\SomeFilename.ext"
-Session $session
So in your example it should be:
Add-FTPItem -Path $ftp_path -LocalPath $_.FullName -Session $session
The filename will be added to the remote FTP path. In case you don't want to have the same name you must either rename the file locally first or remotely after.
Change block
Get-ChildItem -Path $local_out | %{ .... }
to one line
Get-ChildItem -Path $local_out | Add-FTPItem -Path $ftp_path