Create folder on remote computer using PowerShell - 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

Related

Powershell Force windows service that has dependency service to stop

I'm currently working on a powershell script to stop certain windows services and set its startup type to disabled.
My script works fine for services with status stopped however for services that has dependency service running cannot be stopped. I get bunch of errors. I tried to append -Force switch,it aint working too. What could be wrong.
Below is my script.
# Function defintion
function Shut_Services_Down {
# Services array
$services_to_shut_down = #("spooler", "XblGameSave", "Fax")
# Loop each service in the array
foreach ( $node in $services_to_shut_down ){
Set-Service -Name $node -Status stopped -StartupType Disabled -Force
}
}
# Call the function
Shut_Services_Down
error 1
Set-Service : A parameter cannot be found that matches parameter name 'Force'.
At C:\users\admin\desktop\psscripts\services.ps1:9 char:71
+ ... Set-Service -Name $node -Status stopped -StartupType Disabled -Force
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
Set-Service : A parameter cannot be found that matches parameter name 'Force'.
At C:\users\admin\desktop\psscripts\services.ps1:9 char:71
+ ... Set-Service -Name $node -Status stopped -StartupType Disabled -Force
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
Set-Service : A parameter cannot be found that matches parameter name 'Force'.
At C:\users\admin\desktop\psscripts\services.ps1:9 char:71
+ ... Set-Service -Name $node -Status stopped -StartupType Disabled -Force
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
error 2, after removing -Force switch
PS C:\users\admin\desktop\psscripts> .\services.ps1
Set-Service : Cannot stop service 'Print Spooler (spooler)' because it has dependent services.
At C:\users\admin\desktop\psscripts\services.ps1:9 char:9
+ Set-Service -Name $node -Status stopped -StartupType Disabled
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.ServiceProcess.ServiceController:ServiceController) [Set-Service], ServiceCommandException
+ FullyQualifiedErrorId : ServiceHasDependentServicesNoForce,Microsoft.PowerShell.Commands.SetServiceCommand
Solution
# Function defintion
function Shut_Services_Down {
# Services array
$services_to_shut_down = #("spooler", "XblGameSave", "Fax")
# Loop each service in the array
foreach ( $node in $services_to_shut_down )
{
Stop-Service -Name $node -Force -Confirm:$false
Set-Service -Name $node -Status stopped -StartupType Disabled
}
}
# Get-Service -Name "spooler" | Format-List -Property Name,DependentServices
# Call the function
Shut_Services_Down

Powershell scripting1

I am running this Script to get the directory listing
It was working few days ago but I keep having this error
New-PSSession : 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 C:\DEV\Powershell3\directory-listing.ps1:11 char:38
+ $session=New-PSSession -ComputerName $servers
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.NewPSSessionCommand
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
At C:\DEV\Powershell3\directory-listing.ps1:31 char:25
+ Invoke-Command -Session $session -ScriptBlock $scb
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
$servers=get-content C:\temp\servers.txt
$session=New-PSSession -ComputerName $servers
$scb = {
Write-host "working on $env:COMPUTERNAME" -ForegroundColor Red
$volumes=Get-WmiObject win32_volume -Filter "drivetype=3"
foreach($volume in $volumes) {
$driveletter=$volume.driveletter
if($driveLetter -ne $null) {
$drivename=$volume.name
(Get-ChildItem -path $drivename -Directory) |Select-Object Name,FullName
}
}
}
Invoke-Command -Session $session -ScriptBlock $scb

Erroraaction in uploading file by FTP

I have a file with IP address of servers. And script reads adress ($line) by adress, but sometimes can occur address of server that will be down. It is necessary to script steel run till end of IP address. So I used -Erroraction Continue to Set_FTPConnection But script break anyway. How to solve this problem?
foreach ($line in $FTPServer)
{
Start-Transcript -Path $results
Write-Host -Object "ftp url: $line"
Set-FTPConnection -Credentials $FTPCredential -Server $line -Session MySession -UsePassive -ErrorAction Continue
$Session = Get-FTPConnection -Session MySession
$Session>>.\sessions.txt
#Write-Host $Error[0]
if($session.UsePassive -eq "True"){$connect="OK"}
else{$connect="FAIL"}
foreach ($item in (Get-ChildItem .\Upload))
{
#Get-FTPChildItem -Session $Session -Path /htdocs #-Recurse
Write-Host -Object "Uploading $item..."
$Send= Add-FTPItem -Session $Session -Path $FTPPlace -LocalPath .\Upload\$item -Overwrite -ErrorAction Continue #>> .\up.txt #.\Upload\test.txt
$item|gm >>.\up.txt
if($Send.Name -eq $item.Name){$Rec="OK"}
else{$Rec="!!!-FAIL-!!!"}
$array = $line, $item, $connect, $Rec
$FailTable=New-Object -TypeName PSObject -Property ([ordered]#{"FTP Server"=$array[0]; "File"=$array[1];"Connected"=$array[2];"Uploaded"=$array[3]})
Add-Content .\stats.txt $FailTable
}
Stop-Transcript
}
Errors:
From my code
Transcript started, output file is .\logs.txt
ftp url: 10.80.59.173
Set-FTPConnection : Exception calling "GetResponse" with "0" argument(s): "Unable to connect to the remote server"
At F:\DPI FTP\FTPUpload_v2.ps1:25 char:13
+ Set-FTPConnection -Credentials $FTPCredential -Server $li ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Set-FTPConnection
With Test-NetConnection
Start-Transcript : Transcription cannot be started.
At F:\DPI FTP\FTPUpload_v2.ps1:21 char:9
+ Start-Transcript -Path $results #if $session.usepa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : CannotStartTranscription,Microsoft.PowerShell.Commands.StartTranscriptCommand
ftp url: 10.80.59.173
Test-NetConnection : The term 'Test-NetConnection' is not recognized as the name of a cmdlet, function, script file, or operable program. Ch
eck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At F:\DPI FTP\FTPUpload_v2.ps1:23 char:13
+ If (Test-NetConnection $line -Port '21')
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Test-NetConnection:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Transcript started, output file is .\logs.txt
ftp url: 10.80.59.170
Test-NetConnection : The term 'Test-NetConnection' is not recognized as the name of a cmdlet, function, script file, or operable program. Ch
eck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At F:\DPI FTP\FTPUpload_v2.ps1:23 char:13
+ If (Test-NetConnection $line -Port '21')
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Test-NetConnection:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
With If:
WARNING: Could not connect to 10.80.59.173
Start-Transcript : Transcription cannot be started.
At F:\DPI FTP\FTPUpload_v2.ps1:20 char:9
+ Start-Transcript -Path $results #if $session.usepa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : CannotStartTranscription,Microsoft.PowerShell.Commands.StartTranscriptCommand
Stop-Transcript : An error occurred stopping transcription: The host is not currently transcribing.
At F:\DPI FTP\FTPUpload_v2.ps1:47 char:9
+ Stop-Transcript
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Stop-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.StopTranscriptCommand
Continue is actually the default setting. It means that if a non-terminating error occurs, it will show the error and then should be continuing with the command and rest of the script. You could try SilentlyContinue to see if that helps.
Alternatively you could test if the IP Address is connectable first. If you're using Windows 8/Server 2012 or newer and PowerShell v4+ you could use Test-NetConnection -Port 21 to do this specifically for the FTP port, if not you could use Test-Connection instead (which is a PS equivalent of Ping):
foreach ($line in $FTPServer)
{
Start-Transcript -Path $results
Write-Host -Object "ftp url: $line"
If (Test-Connection $line) {
Set-FTPConnection -Credentials $FTPCredential -Server $line -Session MySession -UsePassive -ErrorAction Continue
$Session = Get-FTPConnection -Session MySession
$Session>>.\sessions.txt
#Write-Host $Error[0]
if($session.UsePassive -eq "True"){$connect="OK"}
else{$connect="FAIL"}
foreach ($item in (Get-ChildItem .\Upload))
{
#Get-FTPChildItem -Session $Session -Path /htdocs #-Recurse
Write-Host -Object "Uploading $item..."
$Send= Add-FTPItem -Session $Session -Path $FTPPlace -LocalPath .\Upload\$item -Overwrite -ErrorAction Continue #>> .\up.txt #.\Upload\test.txt
$item|gm >>.\up.txt
if($Send.Name -eq $item.Name){$Rec="OK"}
else{$Rec="!!!-FAIL-!!!"}
$array = $line, $item, $connect, $Rec
$FailTable=New-Object -TypeName PSObject -Property ([ordered]#{"FTP Server"=$array[0]; "File"=$array[1];"Connected"=$array[2];"Uploaded"=$array[3]})
Add-Content .\stats.txt $FailTable
}
Stop-Transcript
} Else {
Write-Warning "Could not connect to $line"
}
}

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

powershell get-content path null error

$commonElementsLocation = ((Get-Location).Path + "\FolderMatchingCommonWords.txt")
if ($commonElementsLocation) {
$result += Start-Job -InitializationScript {
$commonElements = Get-Content -Path $commonElementsLocation
} -ScriptBlock $testScriptBlock -ArgumentList "testing" | Wait-Job | Receive-Job
}
Not sure what I am doing wrong here - probably a stupid mistake, but I put a condition around the Start-Job statement, and powershell still gives the following error:
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:1 char:39
+ $commonElements = (Get-Content -Path $commonElementsLocation)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentC
ommand
Running startup script threw an error: Cannot bind argument to parameter 'Path' because it is null..
+ CategoryInfo : OpenError: (localhost:String) [], RemoteException
+ FullyQualifiedErrorId : PSSessionStateBroken
In v3 add $using:
....(Get-Content -Path $using:commonElementsLocation...
You have already used a variable for a script block once with $testScriptBlock. You could just do that again for -InitializationScript?
$anotherSB = [scriptblock]::create("$commonElements = (Get-Content -Path $commonElementsLocation)")
$result += Start-Job -InitializationScript $anotherSB -ScriptBlock $testScriptBlock -ArgumentList "testing" | Wait-Job | Receive-Job