PowerShell: Change desktop wallpaper on remote computer - powershell

I'm trying to modify PS script, but still cant figureout what can be wrong.
Original script:
cp "image.jpg" \\<IP>\C$
$RemoteReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('Users', "<IP>")
$WallPaper= $RemoteReg.OpenSubKey("S-1-5-21-780093305-1579027723-3042286928-500\Control Panel\Desktop",$True)
$WallPaper.SetValue("Wallpaper","C:\image.jpg")
But I need to use variable SIDs.
So I've made this script:
$hostname = Read-Host 'enter hostname of station'
$username = Read-Host 'enter username (login)'
$objUser = New-Object System.Security.Principal.NTAccount($username)
$userSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$SIDandPath = Join-Path $userSID "Control Panel\Desktop"
cp d:\pic1.jpg \\$hostname\c$
$BaseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey( 'Users' , $hostname )
$SubKey = $BaseKey.OpenSubKey($SIDandPath,$true)
$SubKey.SetValue("Wallpaper","d:\pic1.jpg")
And I'm still receiving thi error:
You cannot call a method on a null-valued expression. At
C:\Users\"username"\Scripty\change_remote_wallpaper.ps1:32 char:17
+ $SubKey.SetValue <<<< ("Wallpaper","d:\pic1.jpg")
+ CategoryInfo : InvalidOperation: (SetValue:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Any ideas what can be wrong? If I set the value of $SubKey to "1", then I receive this:
"Method invocation failed because [System.Int32] doesn't contain a
method named 'SetValue'."
So I think, that the problem is with "OpenSubKey"
Thanks for any help!!

Related

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) :)

Upload file to SharePoint

I would like to create a program in PowerShell to upload files to Sharepoint on schedule (using Task Scheduler)
I was looking for solution and I found this interesting article.
Based on this I wrote this script below:
Import-Module Microsoft.Online.Sharepoint.Powershell -DisableNameChecking;
(System.Reflection.Assembly)::LoadWithPartialName("System.IO.MemoryStream")
Clear-Host
$cred = Get-Credential "emailaddress#domain.com"
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($cred.Username, $cred.Password)
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext("https://")
$clientCOntext.Credentials = $credentials
if (!$clientContext.ServerObjectIsNull.Value) {Write-host "Connected to site" -ForegroundColor Green}
Function UploadFileToLibrary(){
$docLib - $clientContext.Web.Lists.GetByTitle("IT Documents");
$clientContext.Load($docLib);
$clientContext.ExecuteQuery();
$rootFolder = $docLib.RootFolder
$Folder = "\\10.x.x.x\xpbuild$\IT\Level0\scresult\Upload";
$FilesInRoot = Get-ChildItem - Path $Folder | ? {$_.psIsContainer -eq $False}
Foreach ($File in ($FilesInRoot))
{
$startDTM = (Get-Date)
}Write-Host "Uploading File" $File.Name "to" $docLib.Title -ForegroundColor Blue
UploadFile $rootFolder $File $false
$endDTM = (Get-Date)
Write-Host "Total Elapsed Time : $(($endDTM-$startDTM).totalseconds) seconds"
}
Function UploadFile ($SPListFolder, $File, $CheckInRequired){
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $True
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.Url = $File
$UploadedFile = $SPListFolder.Files.Add($FileCreationInfo)
If($CheckInRequired){
$clientContext.Load($UploadedFile)
$clientContext.ExecuteQuery()
If($uploadedFile.CheckOutType -ne "none"){
$UploadedFile.CheckIn("Checked in by Administrator", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
}
}
$clientContext.Load($UploadedFile)
$clientContext.ExecuteQuery()
}
UploadFileToLibrary
When I tried to execute this I see that connection is active but I got an error:
Method invocation failed because [Microsoft.SharePoint.Client.List] does not contain a method named 'op_Subtraction'.
At C:\PowerShell\UploadSharepoint.ps1:11 char:1
+ $docLib - $clientContext.Web.Lists.GetByTitle("IT Documents");
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Subtraction:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Cannot find an overload for "Load" and the argument count: "1".
At C:\PowerShell\UploadSharepoint.ps1:12 char:1
+ $clientContext.Load($docLib);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Exception calling "ExecuteQuery" with "0" argument(s): "List 'IT Documents' does not exist at site with URL 'https://'."
At C:\PowerShell\UploadSharepoint.ps1:13 char:1
+ $clientContext.ExecuteQuery();
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ServerException
I cannot tell if any new problem occur once you fix that one, but given that the 2nd and 3rd error is caused by incorrect assignment of $docLib variable, changing - to =should resolve these three:
HERE |
$docLib = $clientContext.Web.Lists.GetByTitle("IT Documents");
# Below uses $docLib so it cannot be executed properly unless $docLib is assigned correct value
$clientContext.Load($docLib);
# And below fails as the above is not executed successfully
$clientContext.ExecuteQuery();

How to reset a Domain User Password with Remote Powershell

I want to reset my own Active Directory Password on a remote Machine (different domain).
If I use the following code snippet locally it works perfectly:
param(
[string]$oldPassword = $(Read-Host "Old password"),
[string]$newPassword = $(Read-Host "New password")
)
$ADSystemInfo = New-Object -ComObject ADSystemInfo
$type = $ADSystemInfo.GetType()
$user = [ADSI] "LDAP://$($type.InvokeMember('UserName', 'GetProperty', $null, $ADSystemInfo, $null))"
$user.ChangePassword($oldPassword, $newPassword)
Running following snippet on the remote machine fails:
$ADSystemInfo = New-Object -ComObject ADSystemInfo
$type = $ADSystemInfo.GetType()
Invoke-Command -Session $Session -ScriptBlock {
param($rtype, $RemoteADSystemInfo, $OldPassword)
$user = [ADSI] "LDAP://$($rtype.InvokeMember('UserName', 'GetProperty', $null, $RemoteADSystemInfo, $null))"
$user.ChangePassword($OldPassword , "TestPa$$w0rd"")
} -ArgumentList $type,$ADSystemInfo,$Password
Error Message: Method invocation failed because
[Deserialized.System.RuntimeType] does not contain a method named
'InvokeMember'.
+ CategoryInfo : InvalidOperation: (InvokeMember:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
+ PSComputerName : test.test.domain The following exception occurred while retrieving member "ChangePassword": "Unknown error (0x80005000)"
+ CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMember
+ PSComputerName : test.test.domain

Powershell open Ps1 if true

What am I doing wrong here? I am trying to open a second PS1 file if True but an error is thrown (shown below).
#ABOUT
#GLOBALS
$userID = "admin"
$pswrd = "test"
$name = Read-Host 'What is your username?'
$pass = Read-Host 'And your password?' #-AsSecureString | ConvertFrom-SecureString
#$script = '.\sdsSysMain.ps1'
if($name -eq $userID -and $pass -eq $pswrd) #or blank?
{
#write-host "Well done! You're in. "
#Start-Sleep -s 5
Powershell -noexit ".\sdsSysMain.ps1"
}
elseif($name -ne $userID -or $pass -ne $pswrd)
{
write-host "Login Failed... :("
}
This is the error I'm getting:
powershell.exe : The term '.\sdsSysMain.ps1' is not recognized as the name of a cmdlet, function
At C:\Users\1234\Documents\Projects\sdsSys\sdsSysLogin.ps1:19 char:15
+ Powershell <<<< -noexit ".\sdsSysMain.ps1"
+ CategoryInfo : NotSpecified: (The term '.\sds...mdlet, function:String) [],
RemoteException
+ FullyQualifiedErrorId : NativeCommandError
, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At line:1 char:17
+ .\sdsSysMain.ps1 <<<<
+ CategoryInfo : ObjectNotFound: (.\sdsSysMain.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
The error is rather self-explanatory. The script doesn't find sdsSysMain.ps1 in the current working directory. You can output the current working directory in your script like this:
(Get-Location).Path
If you want to run sdsSysMain.ps1 from the same directory as the script calling it, change this:
Powershell -noexit ".\sdsSysMain.ps1"
into this:
$scriptPath = Split-Path -Parent $script:MyInvocation.MyCommand.Path
Powershell -NoExit -File "$scriptPath\sdsSysMain.ps1"

Powershell - Secure String for Passwords and SFTP

I am trying to implement a way to use a stored secure string so that my SFTP password is not visiable in the script. For example, I'd like to generate a variable $password that could be used instead. I found the following examples online but I can't get them to work unfortunately. I've done something similar in the past but can find my notes or links to the website that explained how to complete the task.
read-host -assecurestring | convertfrom-securestring | out-file C:\securestring.txt
$pass = cat C:\securestring.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "test",$pass
Here is my script. Here is a link to the snapin if anyone is interested. http://www.k-tools.nl/index.php/sftp-in-powershell/
#Add the SFTP snap-in
Add-PSSnapin KTools.PowerShell.SFTP
#Define some variables
$sftpHost = "ftp.domain.com"
$userName = "user"
$userPassword = "password"
$localFile = "C:\bin\emp1.xlsx"
#Open the SFTP connection
$sftp = Open-SFTPServer -serverAddress $sftpHost -userName $userName -userPassword $userPassword
#Upload the local file to the root folder on the SFTP server
$sftp.Put($localFile)
#Close the SFTP connection
$sftp.Close()
Again, thanks for everyones help!
UPDATE
I tried this:
$pass = cat c:\bin\ftpcreds.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "usertest1",$pass
$sftpHost = "ftp.domain.com"
$userName = $mycred.username
$userPassword = $mycred.password
$sftp = Open-SFTPServer -serverAddress $sftpHost -userName $userName -userPassword $userPassword
$sftp.Put($localFile)
$sftp.Close()
And get this error:
Method invocation failed because [Tamir.SharpSsh.jsch.JSchException] doesn't contain a method named 'Put'.
At C:\bin\SFTP Upload Samples.ps1:21 char:1
+ $sftp.Put($localFile)
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Method invocation failed because [Tamir.SharpSsh.jsch.JSchException] doesn't contain a method named 'Close'.
At C:\bin\SFTP Upload Samples.ps1:36 char:1
+ $sftp.Close()
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Any suggestions?
Thanks!
If your SFTP is wanting to use a decrypted version of your secured password then you'll want to extract it from your $mycred by:
$userpassword = $mycred.getnetworkcredential().password.tostring()