PowerShell keeps on saying network path not found - powershell

I created a simple PowerShell code that copies a folder from one computer to another, but I keep getting a "Network path not found" is there something I am doing wrong?
# PowerShell Read-Host Input Box
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }
Clear-Host
$ComputerName1 = Read-Host "What is the name of your computer?"
$ComputerName2 = Read-Host "What is the name of the computer you are fixing?"
$Yours = $ComputerName1
$Theirs = $ComputerName2
robocopy "\\$ComputerName1\c:\Temp\Test" "\\$ComputerName2\c:\Temp\"

Related

Passing PowerShell variables to filepath

Completely new to Powershell but not new to programming. Anyway, Im trying to edit this script that was already created and it is almost working. I dont understand how to make Powershell pass a user assigned variable into the filepath for my invoke-command (\MICROS\Res\pos\scripts\$ScriptName) . Any help you can offer will be greatly appricated.
#Gather user input for name of script
$ScriptName=Read-Host "Enter the name of the script that you want to run [Examples: HH_Off.bat]"
#Loop through store array
foreach ($CurrentStore in $store) { #START LOOP
#How to call current store Name: $CurrentStore.Name
#How to call current store IP: $CurrentStore.IP
#How to call current store City: $CurrentStore.City
if ($RunListArray -contains $CurrentStore.ID){ #If the current store is in the input list
Write-Host " *** "$CurrentStore.City"("$CurrentStore.Name")"
$NetworkDrivePath = "\\" + $CurrentStore.IP + "\D$"
#Create Network Drives
New-PSDrive -Name $CurrentStore.Name -PSProvider FileSystem -Root $NetworkDrivePath -credential $mycred
#Check if site is responding
If (Test-Path -Path $NetworkDrivePath)
{
Write-Host " *** *** NETWORK DRIVE FOUND!!! PROCEEDING..."
Invoke-Command {powershell.exe -noprofile -ExecutionPolicy ByPass \MICROS\Res\pos\scripts\$ScriptName} -computername $CurrentStore.IP -credential $mycred
#REMOVE PS DRIVE
Remove-PSDrive $CurrentStore.Name
}
Else {
Write-Host " *** *** NETWORK DRIVE NOT FOUND, SENDING ERROR EMAIL"
$Subject = "*Testing*Powershell Error Send Files Script" + $CurrentStore.Name + " (" + $CurrentStore.City + ")"
$Body = "Network path " + $NetworkDrivePath + " is not accessible."
SendErrorEmail $Subject $Body
}
} #END LOOP
}
The variable is defined in the local (calling) session and not in the remote (Invoke-Command) session. It's referred to as scope. You can reach into the calling scope with the variable modifier $using: like this
Invoke-Command {powershell.exe -noprofile -ExecutionPolicy ByPass \MICROS\Res\pos\scripts\$using:ScriptName} -computername $CurrentStore.IP -credential $mycred
Or as a named or unnamed parameter with -ArgumentList
#named parameter
Invoke-Command {Param($script)powershell.exe -noprofile -ExecutionPolicy ByPass \MICROS\Res\pos\scripts\$script} -computername $CurrentStore.IP -credential $mycred -ArgumentList $ScriptName
#unnamed parameter
Invoke-Command {powershell.exe -noprofile -ExecutionPolicy ByPass \MICROS\Res\pos\scripts\$args[0]} -computername $CurrentStore.IP -credential $mycred -ArgumentList $ScriptName
Formatted and using splatting for readability
$sb = {
Param($script)
powershell.exe -noprofile -ExecutionPolicy ByPass \MICROS\Res\pos\scripts\$script
}
$params = #{
ScriptBlock = $sb
ComputerName = $CurrentStore.IP
Credential = $mycred
ArgumentList = $ScriptName
}
Invoke-Command #params
Also you probably can and should avoid the extra call to powershell.exe.

Start-Process powershell cannot find specified

Edit5: Adam's code works unless there are spaces in the path. That solution is at Powershell Opening File Path with Spaces
Edit4: Simplified further with a test for the path. Same Error.
If ($args[0] -eq "admin")
{
$TheScriptPath = "C:\Users\root\Desktop\script.ps1"
Test-Path ($TheScriptPath)
Start-Process "powershell -noexit" $TheScriptPath
}
Else { Write-Host "OK" }
Output when I call "powershell .\script.ps1 admin" is:
True
Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
At C:\Users\root\Desktop\script.ps1:11 char:2
Edit3: Nevermind. Previous solution stopped working. Script is:
if ($args[0] -eq "admin)
{
$TheScriptPath = $myInvocation.MyCommand.Definition
Start-Process powershell -Verb runAs -Workingdirectory $PSScriptroot $TheScriptPath
exit
}
Write-Host "Ok"
Error when I call "powershell .\script.ps1 admin" is:
Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
At C:\Users\root\Desktop\script.ps1:11 char:2
It's not even working when I hard-code the script path now, even with "-Verb runAs" removed.
Edit2: This is solved, I just can't accept my own answer for two days. Hopefully I remember to do that in case someone else comes along with this question.
Edit1: My script now reads:
If ($args[0] -eq "go")
{
$ThePath = $myInvocation.MyCommand.Definition
Start-Process powershell -Verb runAs $ThePath
Exit
}
Write-Host "OK"
It fails with the error below. However, if I hard-code the script path and write the script as:
If ($args[0] -eq "go")
{
Start-Process powershell -Verb runAs C:\Users\root\Desktop\script.ps1
Exit
}
Write-Host "OK"
It succeeds. I've also tried ""$myInvocation.MyCommand.Definition"" to no avail.
Original:
I have a powershell script that, at least in Windows 7, elevated the user and then ran the rest of the script. In Windows 10, however, it's giving me:
Exception calling "start" with "1" argument(s): "The system cannot find hte file specified"
At C:\Users\root\desktop\script.ps1:15 char:2
If ($True)
{
# We are not running "as Administrator" - so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
exit
}
Write-Host "Ok"
The script exists at this path, as it actually attempting to invoke itself. I'm at a loss here.
I'm running Powershell v5.1.15063.1155 on Windows 10 (v10.0.15063 Build 15063). If I run the following:
$context = [Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $context.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process powershell -Verb runAs -ArgumentList $myInvocation.MyCommand.Definition
exit
}
Get-Date
Sleep -Seconds 4
You can try this as a workaround as it works for me.
To your question, I'd think something is wrong with the the ProcessStartInfo object you created ($newProcess). I've seen that error when the executable name supplied as a parameter can't be found. For example, if I run the following:
$newProcess = new-object System.Diagnostics.ProcessStartInfo "cocain";
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
$newProcess.Verb = "runas";
[System.Diagnostics.Process]::Start($newProcess);
I get the error you described:
You're sure Powershell is in your path (where.exe powershell)? I know its a reach.

Calling script in elevated mode with more than one named argument

Test.ps1
Param (
[String]$CountryCode,
[String]$FilesPath,
[String]$KeepassDatabase,
[String]$KeepassKeyFile,
[String]$EventLog,
[String]$EventSource
)
Write-Host 'Ok' -ForegroundColor Yellow
Write-Host $PSBoundParameters
Start-Sleep -Seconds 5
The goal is to call the script with named parameters in elevated mode. When using named parameters without $Credential, it works fine. The window pops up and the word Ok is displayed:
$StartParams = #{
ArgumentList = "-File `"Test.ps1`" -verb `"runas`" -FilesPath `"S:\Files`" -CountryCode `"XXX`""
}
Start-Process powershell #StartParams
When I add the Credential argument it also pops-up but I can't see anything:
$StartParams = #{
Credential = Get-Credential
ArgumentList = "-File `"Test.ps1`" -verb `"runas`" -FilesPath `"S:\Files`" -CountryCode `"XXX`""
}
Start-Process powershell #StartParams
Am I missing something super obvious here? Even when using the same credentials as the logged on user, I can't see the text.
You need to specify an absolute path to the file. The new PowerShell-process (which will run as admin) doesn't run in the same working directory as your current session.
Try:
$StartParams = #{
FilePath = "powershell.exe"
Credential = Get-Credential
Verb = "RunAs"
ArgumentList = "-File `"c:\temp\Test.ps1`" -FilesPath `"S:\Files`" -CountryCode `"XXX`""
}
Start-Process #StartParams
If you only know the relative path, use Resolve-Path to convert it. Ex:
ArgumentList = "-NoExit -File `"$(Resolve-Path test.ps1 | Select-Object -ExpandProperty Path)`" -FilesPath `"S:\Files`" -CountryCode `"XXX`""
You should also look into string format or here-string so you can avoid escaping every double quote. It makes your life easier:
#Using here-string (no need to escape double quotes)
ArgumentList = #"
-NoExit -File "$(Resolve-Path test.ps1 | Select-Object -ExpandProperty Path)" -FilesPath "S:\Files" -CountryCode "XXX"
"#
#Using string format
ArgumentList = '-NoExit -File "{0}" -FilesPath "{1}" -CountryCode "{2}"' -f (Resolve-Path test.ps1 | Select-Object -ExpandProperty Path), "S:\Files", "XXX"

Running a powershell script from another one. Test-path giving false

I have a requirement to run a script with admin rights by users. So I created 2 scripts where a user runs the first script which will call the second script with start-process with admin credentials. I am passing currently logged in user ID and user profile from first script to second script as arguments to make use of them in the second script. However everything is fine but getting error when accessing user's documents folder in the second script using a variable to the path.
First script as below.
$currentusername = $env:USERNAME
$currentuserprofile = $env:USERPROFILE
$adminusername = "domain\admin"
$adminPassword = 'pwd' | ConvertTo-SecureString -Force -AsPlainText
$credential = New-Object
System.Management.Automation.PsCredential($adminusername, $adminPassword)
$scriptpath = "path to second script.ps1"
Start-Process -filepath PowerShell.exe -Credential $credential -argumentlist "-noexit", "-executionpolicy bypass","-file $scriptpath",$currentusername,$currentuserprofile
Second Script.ps1
param (
#$currentusername = $args[3],
$currentuserprofile = $args[5]
)
$UserDir = "$currentuserprofile\Documents\"
Test-Path $UserDir
this test-path $UserDir is giving false.
Can anyone have had this issue or help me on to overcome this?
When you pass in argument to powershell.exe along with -file only the arguments AFTER the file path are passed onto the script. Reference
So technically, in your 2nd script, you only have the following arguments:
$args[0] # $currentusername
$args[1] # $currentuserprofile
That being said, generally you don't use $args and param together. It's one or the other.
you can either do this:
$currentusername = $args[0]
$currentuserprofile = $args[1]
$UserDir = "$currentuserprofile\Documents\"
Test-Path $UserDir
OR
param (
$currentusername,
$currentuserprofile
)
$UserDir = "$currentuserprofile\Documents\"
Test-Path $UserDir
Even though you're passing admin user credentials, by default, the process is not started with elevated permissions, add -verb RunAs to the start-process to achieve that.

Powershell script running fine on Windows 8 but not on Windows 7

I am very new to powershell and I'm not sure what I did wrong. It is running fine on my Windows 8 PC but when I send it to someone else (he has Windows 7; created this for him), he gets a not allowed to run scripts error.
Tried with -ExecutionPolicy RemoteSigned but still no luck.
##################
<# CONFIG START #>
##################
#replace the path with your steam path. For example: C:\Program Files (x86)\Steam\Steam.exe
$steam_path = "C:\Program Files (x86)\Steam\steam.exe"
#You can change it to Ethernet 1 or Ethernet 2 or Ethernet 3 etc depending on which adapter you want to disable.
#If you have custom name for them (you can rename them from control panel), have to use that name.
$adapter_name = "Ethernet 1"
<#
What program to run.
1: Steam Dota 2
2: Steam CS
3: Steam CSS
4: Steam CSGO
5: Custom Program 1
6: Custom Program 2
7: Custom Program 3
#>
$game_id = "5"
<# Custom Program path and arguments#>
$cp1_path = "C:\Program Files (x86)\counter-strike source\css.exe"
$cp1_arg = " "
$cp2_path = ""
$cp2_arg = " "
$cp3_path = ""
$cp2_arg = " "
$delay = 20
################
<# CONFIG END #>
################
"Checking admin permissions..."
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
"Administrator permissions required."
$arguments = '-ExecutionPolicy RemoteSigned -file "' + $myinvocation.mycommand.definition + '"'
# $arguments
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
"Exiting Steam..."
Start-Process -FilePath $steam_path -ArgumentList "-shutdown" -Wait:$true
Start-Sleep -s 2
"Disabling Network Adapter..."
Disable-NetAdapter -Name $adapter_name -Confirm:$false
Start-Sleep -s 5
"Starting Game..."
Switch($game_id)
{
1
{
Start-Process -filepath "steam://rungameid/570"
}
2
{
Start-Process -filepath "steam://rungameid/10"
}
3
{
Start-Process -filepath "steam://rungameid/240"
}
4
{
Start-Process -filepath "steam://rungameid/730"
}
5
{
Start-Process $cp1_path -ArgumentList $cp1_arg
}
6
{
Start-Process $cp2_path -ArgumentList $cp2_arg
}
7
{
Start-Process $cp3_path -ArgumentList $cp3_arg
}
}
Start-Sleep -s $delay
"Enabling Network Adapter..."
Enable-NetAdapter $adapter_name -Confirm:$false
exit
If you sent him the script, then RemoteSigned is doing it's job just fine. He got the script remotely (from you) and it is not signed, so it won't be executed.
Tell your friend to navigate to the ps1 script in Windows Explorer and right click, then choose "Unblock." He will then need to restart the PowerShell instance if it has failed to run the script already since this kind of information is cached by Windows.
The error indicates you didn't correctly set the execution policy. Firstly, you have run Powershell as an administrator. To do this, right click on the Powershell icon in the start menu and click on "Run as Administrator". Next you have to run the following command in Powershell:
Set-ExecutionPolicy RemoteSigned
You will be prompted to allow the change. Type "Y" and press return.
Finally, try running your script.