I`m following the documentation:
https://googlecloudplatform.github.io/google-cloud-powershell/#/google-compute-engine/GceInstance/Set-GceInstance
I cant get the following code working:
$disk = Get-GceDisk disk-snapshot-instance-1
Set-GceInstance -Name instance-1 -AttachDisk $disk
When I replace $disk for disk-snapshot-instance-1 I get the same error:
Set-GceInstance : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ Set-GceInstance -Name instance-1 -AttachDisk $disk
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-GceInstance], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Google.PowerShell.ComputeEngine.SetGceInstanceCmdlet
The thing I don't understand is that it works for me to remove a disk when attaching it manually through the G-cloud interface.
Set-GceInstance -Name instance-1 -RemoveDisk $disk
My question:
Why can't I attach a disk to an instance with the above code, while removing the disk works?
The correct commands are:
Set-GceInstance $instance -AddDisk $disk1 -Zone $zone
Set-GceInstance $instance -RemoveDisk $disk1 -Zone $zone
I create an instance with 2 disks using gcloud and then:
Get-GceDisk | Format-List -Property Name
This returns:
Name : disk-1
Name : disk-2
Name : instance-1
Then I can:
$zone = "us-west1-c"
$disk2 = Get-GceDisk disk-2
Set-GceInstance instance-1 -RemoveDisk $disk2 -Zone $zone
Set-GceInstance instance-1 -AddDisk $disk2 -Zone $zone
HTH
Related
I am trying use the Get-AzTableRow to retrieve a Azure Table row, followed by updating it. But the cmdlet is throwing the below errors:
PS C:\WINDOWS\system32> Get-AzTableRow -ColumnName "NsgName" -Value "subnet1invnet4-nsg" -Operator "Equal"
You cannot call a method on a null-valued expression.
At C:\Users\sayghosh\Documents\WindowsPowerShell\Modules\AzTable\2.0.2\AzureRmStorageTableCoreHelper.psm1:52 char:4
+ $Results = $Table.ExecuteQuerySegmentedAsync($TableQuery, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PS C:\WINDOWS\system32> Get-AzTableRow -table $storageCloudTable
Cannot find an overload for "ExecuteQuerySegmentedAsync" and the argument count: "2".
At C:\Users\sayghosh\Documents\WindowsPowerShell\Modules\AzTable\2.0.2\AzureRmStorageTableCoreHelper.psm1:52 char:4
+ $Results = $Table.ExecuteQuerySegmentedAsync($TableQuery, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Any lead here will be helpful.
Check out the below script to set the storage context and using cloudtable to read the table row and updating it.
#To install the AzTable module if not already installed
#Install-Module AzTable
#set the subscription contenxt if not already set
#Set-AzContext -Subscription "Subscription Name"
$storageAccountName = "storageaccountName"
$tableName = "storagetableName"
$partitionKey1 = "partitionKey"
$resourceGroup = "ResourceGroup Name"
$storageAccount = Get-AzStorageAccount -ResourceGroupName $resourceGroup -Name $storageAccountName
# Get the Storage Contenxt
$ctx = $storageAccount.Context
# Usage of CloudTable is mandatory when working with AzTable PowerShell module.
$cloudTable = (Get-AzStorageTable -Name $tableName -Context $ctx ).CloudTable
# different ways to get the table row
#Get-AzTableRow -table $cloudTable -customFilter "(username eq 'bob2')"
#Get-AzTableRow -Table $cloudTable -ColumnName "username" -Value "bob2" -Operator Equal
#Create a filter and get the entity to be updated.
[string]$filter = [Microsoft.Azure.Cosmos.Table.TableQuery]::GenerateFilterCondition("username",
[Microsoft.Azure.Cosmos.Table.QueryComparisons]::Equal,"bob2")
$user = Get-AzTableRow -table $cloudTable -customFilter $filter
# Change the entity.
$user.username = "james"
# To commit the change, pipe the updated record into the update cmdlet.
$user | Update-AzTableRow -table $cloudTable
# To see the new record, query the table.
Get-AzTableRow -table $cloudTable -customFilter "(username eq 'james')"`
Additional Documentation reference
Hope this helps.
I am attempting to write two separate scripts. One script determines which EC2 instances are stopped, it starts them and documents what it starts to a text file.
The second script will read the text file and stop those instances. For debugging/simplicty sake I am starting out by combining the two scripts into a single script.
Here's my script:
$Instances = (Get-EC2Instance).instances
$start_instances = #()
$Instances | foreach {
$state = Get-EC2InstanceStatus -InstanceId $_.InstanceId -IncludeAllInstance $true
$state = $state.InstanceState.Name
if ($state -eq "stopped"){
$start_instances += $_.InstanceId
}
}
[System.IO.File]::WriteAllText("C:\users\myusername\desktop\so.csv", $($start_instances -join ','))
$shutdown_instances = [System.IO.File]::ReadAllText("C:\users\myusername\desktop\so.csv")
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Stop-EC2Instance -Instance $shutdown_instances
Starting and documenting what instances are running works fine. Its the stopping instances which is failing.
I'm getting the following error:
Stop-EC2Instance : Invalid id: "i-99edd755,i-8d647f58"
At C:\users\myusername\Desktop\aws-test.ps1:28 char:1
+ Stop-EC2Instance -Instance $shutdown_instances
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Stop-EC2Instance], AmazonEC2Exception
+ FullyQualifiedErrorId : Amazon.EC2.AmazonEC2Exception,Amazon.PowerShell.Cmdlets.EC2.StopEC2InstanceCmdl
Those instance IDs are indeed valid so I can't figure out why the heck its complaining. I was writing the instance IDs to a file via out-file and getting it via get-content but that seemed to have caused a different error.
I'm assuming the issue has something to do with the format of the data once i'm pulling it out of the text file.
Edit
So I've changed my script to:
$start_instances = $start_instances | Select-Object #{Name='Name';Expression={$_}}
$start_instances | Export-Csv -Delimiter ',' -NoTypeInformation -path C:\temp\instances.csv
$stop_instances = #(Import-Csv -path C:\temp\instances.csv)
$stop_instances | Stop-EC2Instance
But still get an error:
Stop-EC2Instance : No instances specified
At C:\temp\aws-test.ps1:22 char:19
+ $stop_instances | Stop-EC2Instance
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Stop-EC2Instance], AmazonEC2Exception
+ FullyQualifiedErrorId : Amazon.EC2.AmazonEC2Exception,Amazon.PowerShell.Cmdlets.EC2.StopEC2InstanceCmdlet
I've also tried:
Stop-EC2Instance -InstanceID $stop_instances
But that also dies:
Stop-EC2Instance : No instances specified
At C:\temp\aws-test.ps1:22 char:1
+ Stop-EC2Instance -InstanceId $stop_instances
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Stop-EC2Instance], AmazonEC2Exception
+ FullyQualifiedErrorId : Amazon.EC2.AmazonEC2Exception,Amazon.PowerShell.Cmdlets.EC2.StopEC2InstanceCmdlet
InstanceId parameter needs array.
You can declare an empty array first
$EC2Instance =#()
Then use Import-CSV and pipe it to append the empty array with each value from csv
Import-CSV C:\Temp\Instance.csv | Foreach-Object {$EC2Instance += $_.InstanceId}
echo $EC2Instance
$EC2instance will now have the required instance id's in an array
Then you can use it in the command
Stop-EC2instance -InstanceId $EC2instance
This worked for me.
I'm new to powershell and I'm trying to automate creating a DHCP reservation.
So far I'm able to get the IP address like so:
$IP = ( GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter).IpAddresses[0]
This returns a string like:
192.0.2.1
However, the Add-DhcpServer4Resrvation cmdlet does not accept an ip address as a string. It requires the IP address be a 'System.Net.IpAddress'
Add-DhcpServerv4Reservation -ComputerName $DHCPServer -ScopeId $DHCPScope -IPAddress $IP -Client
Id $MacAddress -Name $HVNAME
Add-DhcpServerv4Reservation : Cannot process argument transformation on parameter 'IPAddress'. Cannot convert value "
10.254.130.104
" to type "System.Net.IPAddress". Error: "An invalid IP address was specified."
At line:1 char:86
+ ... ope -IPAddress $IP -ClientId $MacAddress -Name $HVNAME
+ ~~~
+ CategoryInfo : InvalidData: (:) [Add-DhcpServerv4Reservation], ParameterBindingArgumentTransformationEx
ception
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Add-DhcpServerv4Reservation
How do you convert a string to a System,.Net.IPAddress?
According to this link, it should be easy like
> [ipaddress]"192.0.2.1"
However that doesn't work.
PS C:\Windows\system32> $FOO = [IPAddress]$IP
Cannot convert value "
10.254.130.104
" to type "System.Net.IPAddress". Error: "An invalid IP address was specified."
At line:1 char:1
+ $FOO = [IPAddress]$IP
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastParseTargetInvocation
tworkAdapter) Format-List -Property *.254.13༁爼ሂÌGEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter) | Format-List -Property * {༁牎ᐂÊGEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Get-VMNetworkAdapter | Format-List -Property *
ఁ牘ࠂÆ$IP = ( GEt-VM -ComputerName $HVCOMPUTERNAME -VMName $HVNAME | Gt-VMNex뿰bpte
Related question
Powershell, get ip4v address of VM
[IPAddress] Wont work if there are spaces in the string
Remove them with Trim()
$IP = [IPAddress]$IP.Trim()
A completely different approach for obtaining IP Address of a server is:
by passing the Workstation/Server name as a parameter to the input type System.Net.DNS cast
For example, if the FQDN name of the host is ABCTest-DEV, then the following script will reveal the IP address of ABCTest-Dev provided, the host has a DNS record already available in the domain.
$ipaddr = [System.Net.Dns]::GetHostAddresses('ABCTest-Dev')|Where AddressFamily -EQ 'InterNetwork'
Write-Host 'This IPV4 Address of the Host is: '$ipaddr
I want to execute below code in the either local or remote machine whith current user.
$BackUpSqlAgentAndRemoveOldbackup = {
param([string]$AppServer,[string]$SqlInstance,[string]$BackupShare,[string]$alias)
[Environment]::UserName #I got same user name in all cases.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo') | Out-Null
$server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $SqlInstance
$backupName = 'SqlAgentJob_' + $SqlInstance + '_' + (Get-Date –format ‘yyyyMMdd_HHmm’) + '_' + $alias + '.sql'
$backupPath = join-path $BackupShare $backupName
$oldBackups = Get-ChildItem $backupShare | where { ( $_.name -like 'SqlAgentJob_*.sql' ) }
$server.JobServer.Jobs.Script() | Out-File -filepath $backupPath
foreach ( $item in $oldBackups ) { remove-item $item.fullName }
}
the #argList is
#('hafcapp-1', 'hafcsql-1', '\\Host5FileSrv\Backup\test','auto')
I notice that
this one, it works well (no -comupterName and -session)
Invoke-Command -ScriptBlock $BackUpSqlAgentAndRemoveOldbackup -argumentList $argList
this one, it throw execption (I also tried "-session", get same result)
Invoke-Command -computerName localhost -ScriptBlock $BackUpSqlAgentAndRemoveOldbackup -argumentList $argList
the exception is as below, it seems the it can not access the folder.
Cannot find path '\\Host5FileSrv\Backup\test' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\Host5FileSrv\Backup\test:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (Script:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Cannot bind argument to parameter 'Path' because it is null.
+ CategoryInfo : InvalidData: (:) [Remove-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RemoveItemCommand
does anyone know how can I do if I want to add computerName or session?
(notes:[Environment]::UserName return identical user)
You have run into the double hop problem. Your credentials can be transferred to the next machine (first hop), but no further (second hop). This means that you can't use the credentials of the machine where you are executing Invoke-Command on, the remote machine (localhost) to connect to a file share (\Host5FileSrv\Backup). Even if you use localhost as computername, it is still remoting. A solution could be CredSSP. See here and here for more information.
This looks like a "second hop" remoting problem, and you'll need to configure WinRM on the computers involved to use CredSSP
http://msdn.microsoft.com/en-us/library/windows/desktop/ee309365(v=vs.85).aspx
I have the following script, but am getting an error -
Script -
$CNAMES = Get-Content "C:\Temp\alias.txt"
$Query = "Select * from MicrosoftDNS_CNAMEType"
$Record = Get-WmiObject -Namespace "root\microsoftdns" -Query $Query -ComputerName 10.10.10.1 | Where-Object{$_.Ownername -match $CNAME}
Foreach($CNAME in $CNAMES)
{
$Record.RecordData = "some.server.net"
$Record.put()
}
Error -
Property 'RecordData' cannot be found on this object; make sure it exists and is settable.
At C:\temp\DNSUpdateCNAMETarget_02.ps1:7 char:9
+ $Record. <<<< RecordData = "some.server.net"
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
Method invocation failed because [System.Object[]] doesn't contain a method named 'put'.
At C:\temp\DNSUpdateCNAMETarget_02.ps1:8 char:12
+ $Record.put <<<< ()
+ CategoryInfo : InvalidOperation: (put:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
TIA
I didn't try (cause i don't have a MS-DNS at hand right now) but i'd suspect that you need
$Record.PSBase.Put()
to make it work.
EDIT:
As it looks $Record holds an array of System.Object so will have to cast it a suitable type to access .RecordData and .Put()
Your script queries for records of type MicrossoftDNS_CNAMEType which only support CreateInstanceFromPropertyData.
I would try sending you $Record to Get-Member
Get-WmiObject -Namespace "root\microsoftdns" -Query $Query -ComputerName 10.10.10.1 | Get-Member
to find out, what you are dealing with.