Powershell: cannot call a method on a null-valued expression error - html

I am trying to login to a website via powershell.
Here is PS code
$username = "userhere"
$password = "passhere"
$ie = New-Object -com InternetExplorer.Application
$ie.visible=$false
$ie.navigate("http://www.desistream.tv/en/login.shtml")
while($ie.ReadyState -ne 4) {start-sleep -m 100}
$ie.document.getElementById("username").value= "$username"
$ie.document.getElementById("pass").value = "$password"
$ie.document.getElementById("loginform").submit()
start-sleep 20
$ie.Document.body | Out-File -FilePath c:\web.txt
Here is Error I get when I run script.
PS C:\Users\myname\Desktop> .\new.ps1
You cannot call a method on a null-valued expression.
At C:\Users\myname\Desktop\new.ps1:9 char:1
+ $ie.document.getElementById("loginform").submit()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PS C:\Users\myname\Desktop> http://www.desistream.tv/en/index.shtml

The page doesn't have an element with the ID "loginform".

Related

Azure DevOps PowerShell CLI - az devops invoke Call for creating inherited process

having an issue with the below code. Can anyone tell me if this is a bug or am I doing something wrong.
Code
#TODO Create process
$org = "silverscout"
$Orglong = "https://dev.azure.com/$org"
$proj = "Test"
$ProcessTemplate = #{
name = "Agile - $($proj)"
parentProcessTypeId = "adcc42ab-9882-485e-a3ed-7678f01f66bc"
referenceName = "$($proj).MyNewAgileProcess"
description = "My new process"}
$infile = "envbody.json"
Set-Content -Path $infile -Value ($envBody | ConvertTo-Json)
az devops invoke `
--area processes `
--resource processes `
--org $Orglong `
--api-version 6.0 `
--accept-media-type "application/json" `
--http-method POST --in-file $infile
ERROR:
az : ERROR: --area is not present in current organization
At line:1 char:2
+ az devops invoke `
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (ERROR: --area i...nt organization:String
) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
when I run the below I see
az devops invoke > az_devops_invoke.json
{
"area": "processes",
"id": "02cc6a73-5cfb-427d-8c8e-b49fb086e8af",
"maxVersion": 7.1,
"minVersion": 2.1,
"releasedVersion": "7.0",
"resourceName": "processes",
"resourceVersion": 2,
"routeTemplate": "_apis/work/{resource}/{processTypeId}"
}
If I try this outside of AZ CLI and use straight up API Call, it works with this call.
$createProcessURL = "$orgUrl/_apis/work/processes?api-version=6.0-preview.2"
$ProcessTemplate = #{name = "Agile - $($proj)";parentProcessTypeId = "adcc42ab-9882-485e-a3ed-7678f01f66bc";referenceName = "$($projectName).MyNewAgileProcess";description = "My new process"} | ConvertTo-Json
$response = Invoke-RestMethod -Uri $createProcessURL -Method Post -ContentType "application/json" -Headers $header -Body ($ProcessTemplate
)

"The property cannot be found on this object. Verify that the property exists." Property definitely exists

I can't figure out why I am not able to change these variables. If I type them into the console in debug mode, then it prints the values. It is also strange how I am able to change the allowedRequestors variable on line 24, but not any of the others. Does anyone know why this is happening to the other variables?
$FilePath = "C:\Users\Desktop\TestScripts\testBulkAP.csv"
$headers = & $PSScriptRoot\GetToken.ps1
## preparing create Catalog data
$accesspacakgeRequest = '{"displayName":"","description":"sddsds","isHidden":false,"catalogId":"","accessPackageResourceRoleScopes":[],"accessPackageAssignmentPolicies":[{"displayName":"Initial Policy","description":"Initial Policy","durationInDays":365,"expirationDateTime":null,"canExtend":false,"requestApprovalSettings":null,"accessReviewSettings":null,"notificationSettings":null,"additionalInfo":null,"isDenyPolicy":false,"id":"","activeAssignmentCount":0,"accessPackageId":"00000000-0000-0000-0000-000000000000","accessPackageCatalog":null,"createdDateTime":null,"modifiedDateTime":null,"createdBy":"","modifiedBy":"","countOfUsersIncludedInPolicy":null,"requestorSettings":{"acceptRequests":true,"scopeType":"NoSubjects","allowedRequestors":[],"isOnBehalfAllowed":false},"questions":[]}]}'
$emlRequestUrl = "https://graph.microsoft.com/beta/identityGovernance/entitlementManagement/accessPackages"
$accesspacakgeRequestObject = ConvertFrom-Json -InputObject $accesspacakgeRequest
$Content = Import-Csv $FilePath
foreach($assignmentData in $Content) {
$accesspacakgeRequestObject.catalogId = $assignmentData.catalogId
$accesspacakgeRequestObject.displayName = $assignmentData.displayName
$accesspacakgeRequestObject.description = $assignmentData.description
$accesspacakgeRequestObject.accessPackageAssignmentPolicies.requestorSettings.scopeType = $assignmentData.scope
if ($assignmentData.scope -eq "SpecificDirectorySubjects") {
$accesspacakgeRequestObject.accessPackageAssignmentPolicies.requestorSettings.allowedRequestors += New-Object -TypeName psobject -Property #{'#odata.type' = '#microsoft.graph.groupMembers'; 'id' = $assignmentData.groupId; 'description' = $assignmentData.groupName; 'isBackup' = 'false'}
}
$numApprovalStages = [int]$assignmentData.approvalStages
if ($numApprovalStages -gt 0) {
$accesspacakgeRequestObject.accessPackageAssignmentPolicies.requestApprovalSettings += New-Object -TypeName psobject -Property #{'approvalMode' = 'Serial'; 'isApprovalRequired' = 'true'; 'isApprovalRequiredForExtension' = 'false'; 'isRequestorJustificationRequired' = 'false'; 'approvalStages' = #()}
for ($i=1;$i -le [int]$assignmentData.approvalStages; $i++)
{
$accesspacakgeRequestObject.accessPackageAssignmentPolicies.requestApprovalSettings.approvalStages += New-Object -TypeName psobject -Property #{'approvalStageTimeOutInDays' = '14'; 'primaryApprovers' = #(); escalationApprovers = #();'isEscalationEnabled' = 'false'; 'escalationTimeInMinutes' = '0'; 'isApproverJustificationRequired' = 'true'}
$accesspacakgeRequestObject.accessPackageAssignmentPolicies.requestApprovalSettings.approvalStages.primaryApprovers += New-Object -TypeName psobject -Property #{'#odata.type' = '#microsoft.graph.singleUser'; "displayName" = ''; 'objectId' = Get-Variable -Name "assignmentData.approver$1" -ValueOnly; 'isBackup' = 'false'}
}
}
$requestbody = $accesspacakgeRequestObject | ConvertTo-Json -Depth 10
$response = Invoke-RestMethod $emlRequestUrl -Headers $headers -Method Post -Body $requestbody -UseBasicParsing -ErrorAction Continue
}
The error message is:
The property 'requestApprovalSettings' cannot be found on this object. Verify that the property exists and can be set.
At C:\Users\Desktop\TestScripts\AddAccessPackageAndPolicyWITHAPPROVER.ps1:30 char:5
+ $accesspacakgeRequestObject.accessPackageAssignmentPolicies.reque ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
The property 'approvalStages' cannot be found on this object. Verify that the property exists and can be set.
At C:\Users\Desktop\TestScripts\AddAccessPackageAndPolicyWITHAPPROVER.ps1:34 char:9
+ $accesspacakgeRequestObject.accessPackageAssignmentPolicies.r ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Get-Variable : Cannot find a variable with the name 'assignmentData.approver1'.
At C:\Users\Desktop\TestScripts\AddAccessPackageAndPolicyWITHAPPROVER.ps1:35 char:250
+ ... objectId' = Get-Variable -Name "assignmentData.approver$i" -ValueOnly ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (assignmentData.approver1:String) [Get-Variable], ItemNotFoundException
+ FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand
The property 'primaryApprovers' cannot be found on this object. Verify that the property exists and can be set.
At C:\Users\Desktop\TestScripts\AddAccessPackageAndPolicyWITHAPPROVER.ps1:35 char:250
+ ... objectId' = Get-Variable -Name "assignmentData.approver$i" -ValueOnly ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
The .accessPackageAssignmentPolicies property contains an array ([...]-enclosed in the JSON input).
Even though that array happens to contain only one element, you still need to access it by index in order to set its (only) element's properties; e.g.:
# Note the `[0]`
$accesspacakgeRequestObject.accessPackageAssignmentPolicies[0].requestorSettings.scopeType = $assignmentData.scope
Note that getting properties does not strictly require this index access, because of a feature called member-access enumeration.
This perhaps surprising asymmetry - requiring indexed access on setting - is by design, however - see this answer for more information.

PowerShell New-Object and HTML Output Issue

I am trying to create statistics for a server using PowerShell. and also learning PowerShell.
This is the code I have
Function Get-PingHost
{
[cmdletbinding()]
Param([string]$Hostname = "ServerName")
"The HostName is " + $Hostname
$status=get-wmiobject win32_pingstatus -Filter "Address='$Hostname'" | Select-Object statuscode
"The Status Code is " + $status.statuscode
if($status.statuscode -eq 0)
{
$HostNameStatusInfo = $Hostname + " is REACHABLE"
}
else
{
$HostNameStatusInfo = $Hostname + " is NOT REACHABLE"
}
New-Object -TypeName PSObject -Property $HostNameStatusInfo
**<COMMENT>** If I remove the above New-Object code is still get an incorrect output as mentioned below in the **HTML OutPut**
}
$fragments = #()
$fragments+=$top
$fragments+="<a href='javascript:toggleAll();' title='Click to toggle all sections'>Expand All/Collapse All</a>"
$Text = "SQL Server Ping Status"
$div = $Text.Replace(" ","_")
$fragments+= "<a href='javascript:toggleDiv(""$div"");' title='click to collapse or expand this section'><h2>$Text</h2></a><div id=""$div"">"
$fragments+= Get-PingHost -Hostname $Hostname | ConvertTo-Html -Fragment -As List
$fragments+="</div>"
$fragments+= $html.InnerXml
$fragments+="</div>"
$fragments+= "<p class='footer'>$(get-date)</p>"
The Output I get in HTML is:
SQL Server Ping Status
*: 31
*: 20
Error Message
ew-Object : Cannot bind parameter 'Property'. Cannot convert the "ServerName is REACHABLE" value of type "System.String" to type "System.Collections.IDictionary".
At line:38 char:45
+ New-Object -TypeName PSObject -Property $HostNameStatusInfo
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-Object], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.NewObjectCommand
Apologies... The issue has been resolved...
The code is as below: -
#GET OPERATING SYSTEM INFORMATION
Function Get-PingHost
{
[cmdletbinding()]
Param([string]$Hostname = "ServerName")
$status=get-wmiobject win32_pingstatus -Filter "Address='$Hostname'" | Select-Object statuscode
#"The Status Code is " + $status.statuscode
if($status.statuscode -eq 0)
{
$Hostname + " is <b>REACHABLE</b>"
}
else
{
$Hostname + " is <b>NOT REACHABLE</b>"
#Basically You Don't Need to assign this to the String Variable and
#then display the string variable...
}
}
#endregion
$fragments = #()
$top = ""
$fragments+=$top
$fragments+="<a href='javascript:toggleAll();' title='Click to toggle all sections'>Expand All/Collapse All</a>"
$Text = "SQL Server Ping Status"
$div = $Text.Replace(" ","_")
$fragments+= "<a href='javascript:toggleDiv(""$div"");' title='click to collapse or expand this section'><h2>$Text</h2></a><div id=""$div"">"
$fragments+= Get-PingHost -Hostname $Hostname
$fragments+="</div>"
$fragments+= $html.InnerXml
$fragments+="</div>"
$fragments+= "<p class='footer'>$(get-date)</p>"

Importing Bulk user CSV file

Been trying all day to import my CSV file to my AD on Windows Server 2012.
But keep getting all kind of errors.
The error I get is this:
"New-ADUser : Cannot validate argument on parameter 'Name'. The argument is null
or empty. Provide an argument that is n ot null or empty, and then try the
command again.
At line:3 char:90
+ ... ipalname -Name $_.name -DisplayName $_.name -GivenName $_.cn -SurName $_.sn -Dep ...
+ ~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.NewADUsery
Can't seem to find any solution to this, so some help would be great. Here is my files.
This is my script:
Import-Csv .\nb1.csv | ForEach-Object {
$userprincipalname = $_.SamAccountName + "#hirethistire.local"
New-ADUser -SamAccountName $_.SamAccountName -UserPrincipalName $userprincipalname -Name $_.name -DisplayName $_.name -GivenName $_.cn -SurName $_.sn -Department $_.Department -Path "CN_Users,DC=HireThisTire,DC=local"-AccountPassword (ConvertTo-SecureString "Microsoft~1;" -AsPlainText -force) -Enabled $true -PasswordNeverExpires $true -PassThru
}
Sample Of the CSV File:

New-ADUser is not working properly when bulk loading via .csv file

I'm running into an error where this is not picking up the password field at all... I ran the import command manually to make sure it was grabbing all of the correct data, but it errors out on the password and group info...
$Users = Import-Csv -Path "C:\NewUsers.csv"
foreach ($User in $Users)
{
$Displayname = $User.'Firstname' + " " + $User.'Lastname'
$UserFirstname = $User.'Firstname'
$UserLastname = $User.'Lastname'
$OU = $User.'OU'
$SAM = $User.'SAM'
$UPN = $User.'Firstname' + "." + $User.'Lastname' + "#" + $User.'Maildomain'
$Password = $User.'Password'
$Description = $User.'Description'
$Group = $User.'Group'
$Account = New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName $SAM -UserPrincipalName $UPN -GivenName "$UserFirstname" -Surname "$UserLastname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $false -PasswordNeverExpires $true -server esg.intl -PassThru
Add-ADGroupMember -Identity $Group -Members $Account
}
And here are the errors I'm getting even though I know the passwords are ok:
New-ADUser : The password does not meet the length, complexity, or history requirement of the domain.
At C:\Users\A-Shane.Johnson\Desktop\Bulk Add Domain Users.ps1:24 char:13
+ ... $Account = New-ADUser -Name "$Displayname" -DisplayName "$Displaynam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (CN=ESGAP PMOInt...,DC=esg,DC=intl:String) [New-ADUser], ADPasswordComplexi
tyException
+ FullyQualifiedErrorId : ActiveDirectoryServer:1325,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Add-ADGroupMember : Cannot validate argument on parameter 'Members'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
At C:\Users\A-Shane.Johnson\Desktop\Bulk Add Domain Users.ps1:26 char:46
+ Add-ADGroupMember -Identity $Group -Members $Account
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Add-ADGroupMember], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.AddADGrou
pMember
Depending on how that CSV is generated you might try double checking that there isn't an extra space in the Password column header? i.e. 'Password '. Sometimes that trips me up because it doesn't show in the excel or cmd line view easily.
I found the problem and answer. Apparently our domain has an issue when part of the username is in the password. I misunderstood that error thinking that the conversion is what was causing the issue...
I fixed the passwords and now the script runs beautifully!