Running a ps1 independently works fine, however when I schedule via Task Scheduler, the task runs and outputs a 0 byte csv file.
I believe I have the scheduled task setup correctly, no quotes in Start In - program is set to powershell.exe, arguments are set to -execution policy bypass -file "C:\Temp\file.ps1"
Connect-AzureAD -Credential $MyCredential -Tenant ##########################
$dteshort = (get-date).ToString("MM-dd-yyyy")
$objectIDs = Get-AzureADGroupMember -ObjectId ######### | Select-Object objectid,displayname,mail
$groups = foreach ($objectID in $objectids) {
$user = Get-AzureADUser -ObjectId $objectid.ObjectId
Get-AzureADUserMembership -ObjectId $objectID.ObjectId | Where-Object { $_.displayname -like '*PartOfGroupName*' } |
Select-Object #{Name = 'email'; Expression = {$user.mail}}, displayname
}
#
$groups | Export-Csv -Path "D:\LocalPathToFileExport\PBI\PBI_Licenses_AsOf_$dteshort.csv" -NoTypeInformation
After adding start/stop transcript
ConvertTo-SecureString : Key not valid for use in specified state.
At C:\PSScripts\PowerBI HR Partner.ps1:5 char:143
+ ... et-Content $secUser), (Get-Content $SecFile | ConvertTo-SecureString)
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [ConvertTo-SecureString], CryptographicException
+ FullyQualifiedErrorId :
ImportSecureString_InvalidArgument_CryptographicError,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand
ConvertTo-SecureString : Key not valid for use in specified state.
At C:\PSScripts\PowerBI HR Partner.ps1:5 char:143
+ ... et-Content $secUser), (Get-Content $SecFile | ConvertTo-SecureString)
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [ConvertTo-SecureString], CryptographicExcepti
on
+ FullyQualifiedErrorId : ImportSecureString_InvalidArgument_CryptographicError,Microsoft.Pow
erShell.Commands.ConvertToSecureStringCommand
I thought this would work for authenticating to Azure AD, it does when ran manually. The password is exported from Get-Credential / ConvertFrom-SecureString and saved in password.txt
$SecFile = "C:\AzureAD\Password.txt"
$SecUser = "C:\AzureAD\UserName.txt"
$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList (Get-Content $secUser), (Get-Content $SecFile | ConvertTo-SecureString)
Connect-AzureAD -Credential $MyCredential -Tenant ########
After messing around with this, the ConvertTo-SecureString wasn't working as I expected and had to go another route to authenticate to Azure.
It's working now, thanks all for the help diagnosing this.
Related
Below is my code, I've used the same process for connecting to sftp securely. I'm getting the error at the bottom of my post. Not sure if I'm missing a step in the creation of the key and password. Thanks.
#Set the credentials
$Password = Get-Content "c:\password.txt" |
ConvertTo-SecureString -Key (Get-Content "c:\aes.key")
$Credential = New-Object System.Management.Automation.PSCredential ('serviceaccount', $Password)
# Start a new instance of Windows PowerShell using the credentials
# stored in $Credential and run the script in $scriptblock
$powershellPath = "$env:windir\system32\windowspowershell\v1.0\powershell.exe"
$process = Start-Process $powershellPath -Credential $Credential -NoNewWindow `
-ArgumentList ("-ExecutionPolicy Bypass -noninteractive -noprofile " + $scriptBlock) -PassThru
# Script to execute in the new PowerShell instance
$scriptBlock = {
Import-Module ActiveDirectory
Get-ADUser ecarlsson | Set-ADUser -Manager bbob
Read-Host
}
I tried the code above and go the password error below.
Start-Process : This command cannot be run due to the error: The user name or password is incorrect.
At\filepath \\fV3.ps1:7 char:12
+ $process = Start-Process $powershellPath -Credential $Credential -NoN ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
i'am trying to excute a shell script to an azure linux virtual machine using powershell
Why I'm i using powershell? :
The virtual machine has a Copied VHD from storage account which means it doesn't have Azure VM agent
so i can't use :
azure vm extentions
azure vm Runs
i tried also using an automation runbook with the ssh module and got those errors :
Exception calling "Connect" with "0" argument(s): "Server HMAC algorithm not found" At C:\Modules\User\SSH\SSH.psm1:68 char:5 + $SSHConnection.Connect() + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SshConnectionException
and
Exception calling "RunCommand" with "1" argument(s): "Client not connected." At C:\Modules\User\SSH\SSH.psm1:69 char:5 + $ResultObject = $SSHConnection.RunCommand($ScriptBlock.ToString() ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SshConnectionException
which is based on my understanding caused by the vm that is missing KexAlgorithms to describe which methods are supported by the SSH daemon
What i'm trying to do now is to ssh into the vm and excute the command using powershell
here is what i got now (a Powershell scripot to ssh into the vm and excute a command):
$Password = "pwd"
$User = "pwd"
$ComputerName = "ip adress"
$Command = "touch tst.txt"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
echo 'logging...'
$SessionID = New-SSHSession -ComputerName $ComputerName -Credential $Credentials #Connect Over SSH
echo 'Executing...'
$output = (Invoke-SSHCommand -Index $SessionID -Command $Command).Output
Remove-SSHSession -Name $SessionID | Out-Null
im getting this error :
Invoke-SshCommand : A parameter cannot be found that matches parameter name 'Index'.
At C:\Users\octoadmin\Desktop\sign in.ps1:11 char:30
+ $output = (Invoke-SSHCommand -Index $SessionID -Command $Command).Out ...
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-SshCommand], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Invoke-SshCommand
i looked in the internet but couldn't find anything.
apparently the ssh invoke command can't find a session with the index $SessionID
but i don't know where exactly is the problem
hope someone can guide me to the right direction.
Updating Posh-SSH worked for me with this code :
to install Posh-SSH :
Install-Module -Name Posh-SSH -RequiredVersion 2.1
The Script:
$Command = "fetch $scripturl; sh script.sh"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$ComputerName = Get-AzPublicIpAddress -ResourceGroupName $RG -Name $IPName | Select-Object -ExpandProperty ipAddress
echo 'ip is : '
echo $ComputerName
echo 'logging...'
$SessionID = New-SSHSession -ComputerName $ComputerName -AcceptKey -Credential $Credentials
echo 'Exucuting...'
$Query = (Invoke-SshCommand -SSHSession $SessionID -Command $Command).Output
echo $Query
Remove-SSHSession -Name $SessionID | Out-Null
sorry if it's a silly question. I'm trying to get the "EnableDCOM" Registry Key of all the machines on the domain and disable them. I'm kinda stuck with getting the status of the registry key.
Get-Adcomputer -Filter * | Get-itemProperty -path HKLM:\Software\Microsoft\OLE -name "EnableDCOM"
Here is the error:
Get-ItemProperty : Cannot process argument transformation on parameter 'Credential'. userName
At line:1 char:28
... -filter * | Get-ItemProperty -path HKLM:\Software\Microsoft\OLE -name ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidData: (CN=DAYGROUP-PCI...=daygroup,DC=ca:PSObject) [Get-ItemProperty], ParameterB
indingArgumentTransformationException
FullyQualifiedErrorId : ParameterArgumentTransformationError,Microsoft.PowerShell.Commands.GetItemPropertyComman
d
After trying to use the domain admin credential:
The provider does not support the use of credentials. Perform the operation again without specifying credentials.
At line:1 char:1
get-adcomputer -filter * | Get-ItemProperty -path HKLM:\Software\Micr ...
+ CategoryInfo : NotImplemented: (:) [], PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported
This code can help you. Don`t forget to specify different credential if needed.
$ADComputers = ( Get-ADComputer -Filter * ).Name
$ResultArray = #()
foreach ( $Computer in $ADComputers ){
#Maybe you need specify different credential -Credential $cred
$Value = Invoke-Command -ComputerName $Computer -ScriptBlock {
$Value = Get-ItemPropertyValue -path 'HKLM:\Software\Microsoft\OLE' -name 'EnableDCOM'
return $Value
}
$PSO = [PSCustomObject]#{
Computer = $Computer
Value = $Value
}
$ResultArray += $PSO
}
$ResultArray
This question already has answers here:
calling Invoke-Expression with Parameters in Powershell
(2 answers)
Closed 6 years ago.
I am trying to pass an object and a string variable to "Get-ADUser" commandlet using Invoke-Expression.
The credentials are built like this:
$secpasswd = ConvertTo-SecureString $pwd -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($uid, $secpasswd)
then a string is composed with additional parameters:
if ($dc)
{
$newVar = " -server $dc"
}
if ($ou)
{
$newVar = $newvar + " -Serchbase $ou"
}
and finally the following is executed
$AllADUsers = iex "Get-ADUser $newVar -Credential $($mycreds) -Filter * -Properties *" | Where-Object {$_.info -NE 'Migrated'}
but it brings up the credential dialog and an error if i just click ok
Get-ADUser : Cannot validate argument on parameter 'Credential'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:1 char:54
+ Get-ADUser -server srv-v-hh001.bwg.corp -Credential System.Management.Automatio ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
I think this is because iex is parsing $mycreds as a string, is there a way to tell Powershell this is an object?
Why do you need IEX at all? Use hashtable to build parameters for Get-ADUser and then just splat it:
$secpasswd = ConvertTo-SecureString $pwd -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($uid, $secpasswd)
$Splat = #{
Credential = $mycreds
Filter = '*'
Properties = '*'
}
if ($dc)
{
$Splat.Server = $dc
}
if ($ou)
{
$Splat.SearchBase = $ou
}
$AllADUsers = Get-ADUser #Splat | Where-Object {$_.info -NE 'Migrated'}
BTW, you have a typo in your SearchBase parameter name.
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.