powershell get-content path null error - powershell

$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

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

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

Running PS1 from windows 10 command prompt

I'm trying to run a PowerShell from command prompt but received an error.
PS in command prompt:
powershell -command "Get-Date (Invoke-Command { (New-Object -com """Microsoft.Update.AutoUpdate""").Results.LastInstallationSuccessDate} -ErrorAction SilentlyContinue).date -format yyyyMMdd | Out-File -FilePath C:\temp\winupdatelatest.txt"
Error:
Get-Date : Cannot bind parameter 'Date' to the target. Exception setting "Date": "Cannot convert null to type
"System.DateTime"."
At line:1 char:10
+ Get-Date (Invoke-Command { (New-Object -com "Microsoft.Update.AutoUpd ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (:) [Get-Date], ParameterBindingException
+ FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.PowerShell.Commands.GetDateCommand
Please help.

PowerShell Path Parameter Invoke-Command (UnauthorizedAccessException)

When running this simple script I am receiving the error message:
+ CategoryInfo : OpenError: (:) [Import-Csv], UnauthorizedAccessException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand
Param(
[string]$Path,
[string]$Credential
)
Invoke-Command –cn DC –Credential $Credential -ArgumentList $Path –ScriptBlock `
{import-csv -Path $args[0] | select-object –property `
#{name='Identity';expression={$_.username}},#{name='Fax';expression={$_.'fax number'}} `
| foreach{Set-ADUser -Identity $_.identity -Fax $_.fax -Confirm:$false}}
Any idea why this may be happening? I have correct permissions the the path that I am using.
I found the issue and it was because I was not including the CSV file in my path. I was pointing to C:\Files\CSV instead of C:\Files\CSV\fax-users.csv.