Why is a powershell script restarting automatically - powershell

I'm using a Powershell script to run another sql script. My issue is that this script is running at some point but then it stops and restart from the beginning.
Do you have any idea why is it doing this?
Here's the Ps1 script I'm talking about:
Invoke-Sqlcmd -InputFile "$script.sql" `
-Database $database `
-Server $server `
-UserName $username `
-Password $password `
-QueryTimeout 65534 `
-Verbose | Out-Null) 4> "$script.log"
is it related somehow to the Timeout I've set?
Thanks a lot!

Related

How to remotely start service on Azure VM with powershell 5.1

How can I start a service on an Azure VM remotely? It seems impossible to do without Powershell being "Run as Administrator". Is there a way to launch as admin?
(I would pass in Get-Credential parameter, but unfortunately the 5.1 version Set-Service command does not accept that as a parameter like it does in Powershell version 7.x, and i am limited to 5.1 for now.)
My credentials do have admin level rights on the VM, but i can't seem to figure out a way to pass that via a command.
I am triggering the call like this, where $action is either 'stop' or 'start':
$runCommand = Invoke-AzVMRunCommand `
-ResourceGroupName $rg `
-VMName $vm `
-CommandId 'RunPowerShellScript' `
-ScriptPath $scriptPath `
-Parameter #{action = $action}
The linked script would then execute something like this:
$serviceNames = #("service1, service2")
foreach($serviceName in $serviceNames){
$service = Get-Service -Name $serviceName
if($service){
if($action -ieq "start"){
Set-Service -InputObject $service -Status "Running"
}
}
else{
Write-Output "Service $serviceName not found!"
}
}
When i run from my laptop - it hangs.
When i run from Azure portal via "Run Command" - it hangs.
When i run from the VM itself - it says:
"Service '' cannot be configured due to the following error:
Access is denied
When i run from the VM itself but start Powershell as admin - It works!
Make sure you have to connect with local administrator password which you already configured with your VM.
If you are not able to connect the VM you need to reset your local administrator password/ Remote Desktop Service Configuration as per MS-DOC. We can reset either Azure Portal / VM Access extension and PowerShell.
If you want to connect the Azure VM from your local, you have to signed in with respective Azure subscription.
Use Set-AzVMAccessExtension to reset the local administrator account password.
VM has a single Access Agent. Use the same VM Access Agent which you used earlier.
Workaround
Way 1
Add the user to your VM
$Uname = "<UserName>"
$password = "<Password>"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
New-LocalUser $Uname -Password $securePassword -FullName $Uname -Description "test admin account"
Add-LocalGroupMember -Group "Administrators" -Member $Uname
Way 2
Reset the local Administrator password
$vm = Get-AzVM -ResourceGroupName "<ResourceGroup Name>" -Name "<Resource name>"
$Uname = "<UserName>"
$password = "<Password>"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credentials= New-Object System.Management.Automation.PSCredential ($Uname, $securePassword)
Set-AzVMAccessExtension -Credential $credentials -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name -Location $vm.Location -Name VMAccessAgent -TypeHandlerVersion "2.0"
Access the Script file using specific login
Connect-AzAccount
$vm = Get-AzVM -Name "<your vm name>" -ResourceGroupName "<your vm resource group>"
$runCommand = Invoke-AzVMRunCommand `
-ResourceGroupName $rg `
-VMName $vm `
-CommandId 'RunPowerShellScript' `
-ScriptPath $scriptPath `
-Parameter #{action = $action}

Powershell: Cannot read and write a variable on Hyperv-V VM from host

Using this Powershell script I try to write and read a variable on VM from host.
$Username = 'administrator'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
#Added value to a variable on VM
Invoke-Command -VMName VM_Windows_2016 -Credential $Cred -ScriptBlock {$InstallPath="C:\Install\install-1.ps1"}
#Trying to read the variable on VM but with no result
Invoke-Command -VMName VM_Windows_2016 -Credential $Cred -ScriptBlock {Write-Host($InstallPath)}
As you see the result is empty. Can anyone help me to show how to write and read an variable on VM from host machine? Thanks!
When using Invoke-Command to run a command remotely, any variables in the command are evaluated on the remote computer. So when you run the first Invoke-Command you are only defining the variable $InstallPath and terminating the remote PS session. When you are run the Invoke-Command second time it create entirely new PS session, hence InstallPath would be null. Instead of this you can define and read the variable in a single Cmdlet like this.
$remoteScriptblock = {
$InstallPath = "C:\Install\install-1.ps1"
Write-Host($InstallPath)
}
Invoke-Command -VMName VM_Windows_2016 -Credential $Cred -ScriptBlock $remoteScriptblock
If you still want to run this in multiple Cmdlets you may consider Run a command in a persistent connection

Jenkins Deployment - Powershell SCP Script

Good evening,
I'm trying to write a Powershell script that will connect to a remote server via SCP and upload or download files/folders. Ultimately this is the script that I would like Jenkins to run.
So far I'm using Posh-SSH and having good success. The only issue is, no matter what I have tried so far, it will always prompt me for my credentials. This, obviously, makes it not entirely automatic.
I have attached a few things I've tried. Hopefully someone can help me out with this!
The basic command I'm testing with:
get-scpfolder -computername '111.111.111.111' -credential $credential
-remotefile "/var/myFolder" -localfile 'C:\Users\Me\destFolder'
Again, this works, but it requires me to enter my credentials.
I saw this command online:
$Password = "pass"
$User = "admin"
$ComputerName = "111.111.111.111"
$Command = "get-scpfolder -computername $ComputerName -credential $Credentials -localfolder 'C:\Users\Me' -remotefolder '/var/destFolder"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$SessionID = New-SSHSession -ComputerName $ComputerName -Credential $Credentials #Connect Over SSH
Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command # Invoke Command Over SSH
However this returns ExitStatus 1 and nothing happens. I have tried a few variations of the $Command including the credentials or not, for example, and I can't get any of it to work.

Powercli script to join computer to the Domain

I'm tring to run Powercli script from VM that have all the modules nedded.
The script should insert other VM to domain.
$ScriptText ="Add-Computer -DomainName foofoo.com -DomainCredential " + $DomainC +" -OUPath 'OU=CACI,OU=Computers,OU=bla,OU=Regions,DC=bla,DC=com'"
echo $Script
Invoke-VMScript -vm $VMName -GuestCredential $AdminC -ScriptText $ScriptText
all the variables inserted correctly.
runing
Add-Computer -DomainName foofoo.com -DomainCredential $DomainC -OUPath 'OU=CACI,OU=Computers,OU=bla,OU=Regions,DC=bla,DC=com'
from the other vm poweshell console is running well and the output message WARNING: The changes will take effect after you restart the computer ..
$Script return:
Add-Computer -DomainName foofoo.com -DomainCredential System.Net.NetworkCredential -OUPath 'OU=CACI,OU=Computers,OU=bla,OU=Regions,DC=bla,DC=com'
but after that this script stuck and I have no error or other output.
Any idea what is the reason for that ?
The Add-Computer CMDlet takes a credential object for the domain credential parameter. By trying to convert that to a string in your $scripttext variable - you're losing the credential type in the conversion. You need to make a credential object inside your script text rather than passing in a variable containing the credential object. This adds some complexity because you generally want to pull a password from a secure vault. The below examples shows how to include the password as a plain text - but this isn't really advised for obvious reasons.
$scripttext = #'
$user = "UserName"
$password = ConvertTo-SecureString "bar" -AsPlainText -Force
$DomainC = New-Object PSCredential $user, $password
Add-Computer -DomainName foofoo.com -DomainCredential $DomainC -OUPath 'OU=CACI,OU=Computers,OU=bla,OU=Regions,DC=bla,DC=com'
'#
Invoke-VMScript -vm $VMName -GuestCredential $AdminC -ScriptText $ScriptText

Attach to an Azure ShareFile using WinRM and net use

Context:
I have setup an ARM deployment from the 201-winrm-windows in azure-quickstart-template.
The deployment run fine
I can access the VM using WinRM
I can run a script remotely using WinRM
The problem is that I'm trying to setup a storage file on that VM. The official documentation ask to run this command:
net use <drive-letter>: `
\<storage-account-name>.file.core.windows.net<share-name> `
/u:<storage-account-name> <storage-account-key>
# Result:
The command completed successfully.
The issue:
When the command is run locally (local powershell on the VM), I have a success message and the mount appear.
When the command is run through WinRM, I have the same success message but when I connect to the VM, I cannot access the mount.
My code:
$resourceGroupName = "resourcegroupname"
$username = "username"
$storageAccountName = "storageaccountname"
$zone = "westeurope"
$hostName = "$resourceGroupName.$zone.cloudapp.azure.com"
$shareFileName = "test"
$winrmPort = '5986'
$storageAccountKey = "......................"
$cred = new-object `
-typename System.Management.Automation.PSCredential `
-argumentlist $username, $password
$soptions = New-PSSessionOption -SkipCACheck
Invoke-Command `
-ComputerName $hostName `
-Credential $cred `
-Port $winrmPort `
-SessionOption $soptions `
-filepath .\provision.ps1 `
-UseSSL `
-ArgumentList `
$storageAccountName, `
$storageAccountKey, `
$shareFileName
And the provision file .\provision.ps1:
Param (
[Parameter(Mandatory=$True,Position=0)]
[string]$accountStorageName,
[Parameter(Mandatory=$True,Position=1)]
[string]$accountStorageKey,
[Parameter(Mandatory=$True,Position=2)]
[string]$shareFileName
)
net use w: `
\\$accountStorageName.file.core.windows.net\$shareFileName `
/user:$accountStorageName $accountStorageKey
Note:
my issue is similar to this one but the author have no response.
The problem you are hitting into in this case is that, WinRM runs as NetworkService. When you 'net use' through WinRM, the mount operation is done for NetworkService user, and you cannot access it through another user you connect to VM with. You'll need to ensure that the mount operation is done through same user context that you'll need to access the share as.
Just tried what you've done but I can access the mount successfully. A small difference is that I connect to the VM first and then mount the file share, I didn't combine these two steps into one like you did, not sure whether this is the issue but just like to share with you and for your reference.
I uploaded a file in my file share and I can access the file share and get the file as below snapshot shows:
Update access from RDP: