Make Choices to Enable / Disable Net Adapter Using Powershell - powershell

I'm Trying to use Powershell to make a choices to Enable/Disable Net Adapter "Ethernet"
I Coded This
$caption = "Choose Action";
$message = "What do you want to do?";
$enab = start-process powershell -verb runas -argument D:\ena.ps1
$disa = start-process powershell -verb runas -argument D:\dis.ps1
$choices = [System.Management.Automation.Host.ChoiceDescription[]]($enab,$disa);
$answer = $host.ui.PromptForChoice($caption,$message,$choices,0)
switch ($answer){
0 {"You entered Enable"; break}
1 {"You entered Disable"; break}
}
Error :
Object cannot be stored in an array of this type.
At D:\Untitled4.ps1:5 char:1
+ $choices = System.Management.Automation.Host.ChoiceDescription[];
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], InvalidCastException
+ FullyQualifiedErrorId : System.InvalidCastException
Exception calling "PromptForChoice" with "4" argument(s): "Value
cannot be null. Parameter name: choices" At D:\Untitled4.ps1:6 char:1
+ $answer = $host.ui.PromptForChoice($caption,$message,$choices,0)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
I have failed before this to do On/Off script using powershell (if the net adapter is enable then disable it and vice versa. is there any way to do this?

Using this: https://technet.microsoft.com/en-us/library/ff730939.aspx I think what you want to be doing is the following:
$caption = "Choose action:"
$message = "What state do you want for the network adapter?"
$enable = New-Object System.Management.Automation.Host.ChoiceDescription "&Enable", `
"Enables the Network Adapter"
$disable = New-Object System.Management.Automation.Host.ChoiceDescription "&Disable", `
"Disables the Network Adapter"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($enable, $disable)
$result = $host.ui.PromptForChoice($caption, $message, $options, 0)
switch ($result)
{
0 {
"You selected Enable."
start-process powershell -verb runas -argument D:\ena.ps1
}
1 {
"You selected Disable."
start-process powershell -verb runas -argument D:\dis.ps1
}
}
The approach you were taking wasn't working because you were trying to assign a process to a ChoiceDescription array. In the example above, you have to first create two ChoiceDescription objects before assigning them to the array

Related

PowersShell script doesn't work remotely with Invoke-Command but works perfectly locally

I have a script to check for and download windows updates. It isn't working remotely and I would like to know why. Here is the script:
$UpdateSession = New-Object -Com Microsoft.Update.Session
$updatesToDownload = New-Object -Com Microsoft.Update.UpdateColl
$updatesToInstall = New-Object -Com Microsoft.Update.UpdateColl
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$SearchResult = $UpdateSearcher.Search("IsInstalled=0 and Type='Software'")
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Installer = $UpdateSession.CreateUpdateInstaller()
# Check for updates ---------------------------------------------------------------------
if ($SearchResult.Updates.Count -gt 0) {
Write-Host("All updates found: " + $SearchResult.Updates.Count)
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++) {
$Update = $SearchResult.Updates.Item($X)
if ($Update.KBArticleIDs -eq '2267602') {
Write-Host("Updates with Ids 2267602 found: " + $Update.Title)
$updatesToDownload.Add($Update)
Write-Host("Update " + $Update.Title + " added to download list")
}
}
}
else {
# Write-Host(0) # No Security Intelligence Updates
Write-Host("No update found")
Exit
}
# Download updates ----------------------------------------------------------------------
if ($updatesToDownload.Count -gt 0) {
Write-Host("Start download process")
$Downloader.Updates = $updatesToDownload
$DownloadResult = $Downloader.Download()
Write-Host("Download ResultCode: " + $DownloadResult.ResultCode)
if ($DownloadResult.ResultCode -eq 2) {
For ($X = 0; $X -lt $updatesToDownload.Count; $X++) {
Write-Host("Adding updates to install list")
$Update = $updatesToDownload.Item($X)
if ($update.IsDownloaded -eq 'True') {
$updatesToInstall.Add($Update)
Write-Host("Update " + $Update.Title + " added to install list")
}
}
}
}
else {
# Write-Host(0) # No Security Intelligence Updates
Write-Host("No update to download found")
Exit
}
The script works perfectly when I run it on a computer using administrator account.
But when I try to run it remotely using below short script and the same administrator credentials it starts and do "Check for updates" bloc and stops with error.
$password = ConvertTo-SecureString "some_password" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("computer_name\administrator", $password)
$sess = New-PSSession -ComputerName "computer_name" -Credential $cred
Invoke-Command -Session $sess -FilePath "D:\Test.ps1"
Where "D:\Test.ps1" is path to a file with script mentioned above.
Error message:
The property 'Updates' cannot be found on this object. Verify that the property exists and can be set.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
+ PSComputerName : computer_name
You cannot call a method on a null-valued expression.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName : computer_name
I have checked remote credentials using other script (below) and the result is True yet updates script doesn't work.
[bool] (net session 2>$null)
[Security.Principal.WindowsPrincipal]::new(
[Security.Principal.WindowsIdentity]::GetCurrent()
).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
What did I do wrong? Why doesn't the script work remotely?

How to use SSISDeploy command in powershell script

I'm running SSISDeploy command (documentation is here) in my CMD:
SSISDeploy.exe -s:"download\Integration Services.ispac" -d:catalog;/SSISDB/TEST/DEVOPS;"TEST03,1234" -at:win
all working good, and now I need to run it thought powershell script (against windows server 2019 slave), so I tried this syntax:
$SSISDeploy = Start-Process -FilePath SSISDeploy.exe -ArgumentList '/source:"download\Integration Services.ispac"',"/destination:catalog;${Target};"${Env}"" -at:win -wait -PassThru -Credential $cred -RedirectStandardOutput ssisstdout.txt -RedirectStandardError ssisstderr.txt
but it fails with exception:
Start-Process : A positional parameter cannot be found that accepts argument 'TEST03,1234'.
+ ... SISDeploy = Start-Process -FilePath SSISDeploy.exe -ArgumentList '/so ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.StartProcessCommand
Can you suggest what's wrong with the syntax?
$StartProcessProps = #{
FilePath = 'SSISDeploy.exe'
ArgumentList = '-s:"download\Integration Services.ispac" -d:catalog;{0};{1} -at:win' -f $Target, $Env
Wait = $true
PassThru = $true
Credential = $cred
RedirectStandardOutput = 'ssisstdout.txt'
RedirectStandardError = 'ssisstderr.txt'
}
$SSISDeploy = Start-Process #StartProcessProp

Getting error when connecting two Azure Analysis Services from child scripts

I am working on PowerShell scripts. I have two scripts in those scripts I am connecting with two Azure Analysis Servers one by one. And these scripts are calling by the main script. I am getting errors
"Exception calling "Connect" with "1" argument(s): "Object reference not set to an instance of an object."
My Scripts code is below
Child1.ps1
param(
[String]
$envName1,
[String]
$toBeDisconnect1
)
$loadInfo1 = [Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")
$server1 = New-Object Microsoft.AnalysisServices.Server
if($toBeDisconnect1 -eq "No")
{
$server1.Connect($envName1)
return $server1
}
elseif($toBeDisconnect1 -eq "Yes")
{
$server1.Disconnect()
Write-Host $server1 " has been disconnected."
}
Child2.ps1
param(
[String]
$envName1,
[String]
$toBeDisconnect1
)
$loadInfo1 = [Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")
$server1 = New-Object Microsoft.AnalysisServices.Server
if($toBeDisconnect1 -eq "No")
{
$server1.Connect($envName1)
return $server1
}
elseif($toBeDisconnect1 -eq "Yes")
{
$server1.Disconnect()
Write-Host $server1 " has been disconnected."
}
MainParent.ps1
param(
$filePath = "C:\Users\user1\Desktop\DBList.txt"
)
$command = "C:\Users\User1\Desktop\test1.ps1 –envName1
asazure://aspaaseastus2.asazure.windows.net/mydevaas -toBeDisconnect1 No"
$Obj1 = Invoke-Expression $command
Start-Sleep -Seconds 15
$command1 = "C:\Users\User1\Desktop\test2.ps1 –envName2
asazure://aspaaseastus2.asazure.windows.net/myuataas -toBeDisconnect2 No"
$Obj2 = Invoke-Expression $command1
Error is below in MainParent.ps1
Exception calling "Connect" with "1" argument(s): "Object reference not set to an instance of an
object."
At C:\Users\User1\Desktop\test1.ps1:13 char:5
+ $server1.Connect($envName1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NullReferenceException
Exception calling "Connect" with "1" argument(s): "Object reference not set to an instance of an
object."
At C:\Users\User1\Desktop\test2.ps1:13 char:5
+ $server2.Connect($envName2)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NullReferenceException
My AzureAnalysis Services dll version is 13.0.4495.10. I am sharing this info, may be it can be a issue.
It seems Invoke-Expression is not passing the param envName1. I would rather call the child script normally like below:
$Obj1 = &"C:\Users\User1\Desktop\test1.ps1" -envName1 "asazure://aspaaseastus2.asazure.windows.net/mydevaas" -toBeDisconnect1 No | select -Last 1
$Obj2 = &"C:\Users\User1\Desktop\test2.ps1" -envName2 "asazure://aspaaseastus2.asazure.windows.net/myuataas" -toBeDisconnect2 No | select -Last 1
$command = "C:\Users\User1\Desktop\test1.ps1 –envName1 asazure://aspaaseastus2.asazure.windows.net/mydevaas -toBeDisconnect1 No"
Look closely at the hyphen before envName1. It's actually – (en-dash) instead of - (hyphen). That's the reason envName1 is not being passed. The second param toBeDisconnect1 has it correct.
How to know the difference? - (hyphen) is shorter than – (en-dash) :)

PowerShell 3.0 behavior when getting external process exit code

I have been using this code from another post from this site:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "notepad.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
**$p.Start() | Out-Null**
#Do Other Stuff Here....
**$p.WaitForExit()**
$p.ExitCode
It has worked fine under PowerShell 2.0. The server was upgraded to PowerShell 3.0, and now the two bold like fail with:
Exception calling "Start" with "0" argument(s): "The system cannot find the
file specified"
At \\asdnsom3978\optim_windows\script_master\exportall.ps1:126 char:1
+ $p.Start() | Out-Null
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : Win32Exception
Exception calling "WaitForExit" with "0" argument(s): "No process is
associated with this object."
At \\asdnsom3978\optim_windows\script_master\exportall.ps1:128 char:1
+ $p.WaitForExit()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
Why did it broke and how do I correct it so it works for both version 2.0 and 3.0?
Hmm, I can't repro the error on my V3 system. But why are you going to all this trouble when you can just use the Start-Process command to do this e.g.:
$p = Start-Process Notepad -Wait -PassThru
$p.ExitCode
You might want to try providing a fully-qualified path to notepad.exe, like "C:\Windows\notepad.exe".

Powershell CMDLET Cross Domain Managment

I'm logged in at domain "domain1" with my account. I wish via powershell to be able to update users in domain "domain2" via my supe ruser account "suaccount" with password "password1". Trust is established between the two.
Running PowerShell 2.0 and .NET 3.5 SP1
I have gotten this far:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$context = New-Object -TypeName
System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ctype, "domain2", "OU=TestOU,DC=domain2", "suaccount", "password1"
$usr = New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal -ArgumentList $context
$usr.Name = "AM Test1"
$usr.DisplayName = "AM Test1"
$usr.GivenName = "AM"
$usr.SurName = "Test1"
$usr.SamAccountName = "AMTest1"
$usr.UserPrincipalName = "amtest1#mtest.test"
$usr.PasswordNotRequired = $false
$usr.SetPassword("errr")
$usr.Enabled = $true
$usr.Save()
Pretty new to PowerShell, any pointers? I want to edit/create users on the "other" domain so to speak.
I get the error:
"Exception calling "Save" with "0" argument(s): "General access denied error
"
At C:\Script\Sandbox\Morris PowerShell Application\includes\mo\mo.ps1:104 char:14
+ $usr.Save <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException"
Any pointers?
From comments: Try using for username this format domain2\username, and always use the FQDN for the domain. – Christian yesterday