Upload file/s on web share - powershell

On Windows, is it possible to upload a file to a webshare without use net use or New-PSDrive? (I have PowerShell 3.0 available)
Now I use:
net use Z: http://share.net/mypath/my2path/ /user:<domain\username> <password>
Or:
New-PSDrive -Name Z -PSProvider FileSystem -Root http://share.net/mypath/my2path/ -Credential domain\user

Since you did not say what type of file you wanted to upload, you may need to add the -ContentType switch to the command. Change the fileToUpload variable to be the path to your file. Otherwise, this should work:
$credentials = Get-Credential
$fileToUpload = "c:\temp\myfile.txt"
$uri = "http://share.net/mypath/my2path/"
Invoke-WebRequest -uri $uri -Method Put -Infile $fileToUpload -Credential $credentials

Related

How to store the output of the Invoke-RestMethod into a variable

I am trying to store the output of the Invoke-RestMethod into a variable and than exact the output from the variable.
Invoke-RestMethod -Method POST -Uri $exportURL -Headers $logonHeader -ContentType "application/zip" -TimeoutSec 2700 -OutFile "$PlatformZipPath\$PlatformID.zip" -ErrorAction SilentlyContinue
$URI = New-Object System.Uri("$URL_DeployPlatfoms/$Repository/$Valut/$EMV/$platfromTech/$PlatformID.zip")
$AF_PWD = ConvertTo-SecureString $JfrogAuthToken -AsPlainText -Force
$AFCREDS = New-Object System.Management.Automation.PSCredential ($Jfroguser, $AF_PWD)
$SOURCE = "$PlatformZipPath\$PlatformID.zip"
Invoke-WebRequest -Uri $URI -InFile $SOURCE -Method Put -Credential $AFCREDS
So, What this piece of code of does is export the cyberark platform and deploy to jfrog artifactory. But the invoke rest method store platform zip locally. I dont want. I want to directly deploy it to artifactory.
But i dont know how to do that. Please help me with that. Thanks in advance.

Power shell script which silently installs softwares

# Source file location
$source1 ="https://ftp.mozilla.org/pub/firefox/releases/11.0/win32/enUS/Firefox%20Setup%2011.0.exe"
$source2 ="https://www.fosshub.com/Code-Blocks.html?dwl=codeblocks-20.03-setup.exe"
$source3 ="https://github.com/x64dbg/x64dbg/releases/download/snapshot/snapshot_2021-07-01_23-17.zip"
$source4 ="https://www.python.org/ftp/python/3.9.6/python-3.9.6-amd64.exe"
$source5 ="https://www.nasm.us/pub/nasm/releasebuilds/2.15.05/win64/nasm-2.15.05-installer-x64.exe"
# Destination to save the file
$destination1 = "C:\Users\cdac\Desktop\Shravan\Softwares\firefox.exe"
$destination2 = "C:\Users\cdac\Desktop\Shravan\Softwares\codeblocks.exe"
$destination3 = "C:\Users\cdac\Desktop\Shravan\softwares\xdbg.zip"
$destination4 = "C:\Users\cdac\Desktop\Shravan\softwares\python.exe"
$destination5 = "C:\Users\cdac\Desktop\Shravan\softwares\nasm.exe"
Invoke-WebRequest -Uri $source1 -OutFile $destination1
Invoke-WebRequest -Uri $source2 -OutFile $destination2
Invoke-WebRequest -Uri $source3 -OutFile $destination3
Invoke-WebRequest -Uri $source4 -OutFile $destination4
Invoke-WebRequest -Uri $source5 -OutFile $destination5
#Installing one software
Start-Process -Wait -FilePath 'C:\Users\cdac\Desktop\Shravan\Softwares\codeblocks.exe' -ArgumentList '/silent' -PassThru
I have written Powershell script which downloads the software tools from the internet through URL and stored in a separate directory but iam not able to install all the softwares which are stored in a separate directory silently using foreach loop. kindly help me in writing script for installing all the softwares stored in a directory using foreach loop.
Thanking you
There isn't enough information to say exactly what's going wrong here - what error are you getting specifically? What behavior are you observing when you run your script? My first guess is that your foreach loop is running through installer names, not the full path like you posted in your example.
That said, if I understand what you're trying to do, here's a quick and dirty way to do what I think you're after;
# Array of installer details
[Hashtable[]]$Installers = #();
# Firefox
$Installers += #{
SoftwareName = "Firefox"
Url = "https://ftp.mozilla.org/pub/firefox/releases/11.0/win32/enUS/Firefox%20Setup%2011.0.exe"
Destination = "C:\Users\cdac\Desktop\Shravan\Softwares\firefox.exe"
Arguments = '/s'
}
#Code Blocks
$Installers += #{
SoftwareName = "CodeBlocks"
Url = "https://www.fosshub.com/Code-Blocks.html?dwl=codeblocks-20.03-setup.exe"
Destination = "C:\Users\cdac\Desktop\Shravan\Softwares\codeblocks.exe"
Arguments = '/silent'
}
function Install-Software([Hashtable]$installer) {
Write-Host "Installing $($installer.SoftwareName)"
Write-Host "Invoke-WebRequest -Uri $($installer.Url) -OutFile $($installer.Destination)"
Write-Host "Start-Process -FilePath $($installer.Destination) -ArgumentList $($installer.Arguments) -Wait"
# Remove Write Host above - uncomment the following lines:
#Invoke-WebRequest -Uri $installer.Url -OutFile $installer.Destination
#Start-Process -FilePath $installer.Destination -ArgumentList $installer.Arguments -Wait
}
foreach($installer in $Installers) {
Install-Software -installer $installer
}
I'd recommend having a look at the PSAppDeployToolkit if you're trying to package applications silently using PowerShell - this helped me a lot back when I was doing a lot of SCCM packaging.

Login to power bi service online (silently i.e. without the popup) using powershell

I would like to login to Power BI Online service and remove rows from a dataset using the REST API. I have the rest of the code going fine but the login seems to not work. This is what I tried. Can someone help me please? Thank you!
$pbiUsername = "abc.xyz#xxx.com"
$pbiPassword = "Password"
$clientId = "a81b2cc1-4c97-2323-bal4-eeb21c4c6e46"
$body = #{"resource" = "https://analysis.windows.net/powerbi/api"
"client_id" = $clientId;
"grant_type" = "password";
"username" = $pbiUsername;
"password" = $pbiPassword;
"scope" = "openid"
}
$authUrl = "https://login.windows.net/common/oauth2/token/"
$authResponse = Invoke-RestMethod -Uri $authUrl –Method POST -Body $body
$headers = #{
"Content-Type" = "application/json";
"Authorization" = $authResponse.token_type + " " +
$authResponse.access_token
}
$restURL = "https://api.powerbi.com/v1.0/myorg/groups"
$restResponse = Invoke-RestMethod -Uri $restURL –Method GET -Headers $headers
"Login doesn't seems to work" doesn't give us enough information to hint you what is the problem.
I will recommend you to use the official Microsoft Power BI Cmdlets to do tasks like this. It has big advantage - you don't need to register an application to use it. Here is how your code would look like in this case:
Import-Module MicrosoftPowerBIMgmt
Import-Module MicrosoftPowerBIMgmt.Profile
$password = "Password" | ConvertTo-SecureString -asPlainText -Force
$username = "abc.xyz#xxx.com"
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
Connect-PowerBIServiceAccount -Credential $credential
Invoke-PowerBIRestMethod -Url 'groups/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/datasets/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/tables/xxxxxx/rows' -Method Delete
Disconnect-PowerBIServiceAccount
Since PowerBI now has enabled the Service Principal, you don't need to worry about the username and password and more importantly, you DON'T NEED PRO Licenses
using the Service Principal you can now able to log in without popup as well as username, password
$applicationId = "xxxxxxxx";
$securePassword = "xxxxxx" | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $securePassword
Connect-PowerBIServiceAccount -ServicePrincipal -Credential $credential -TenantId "xxxx"
The error is not handled with try catch - you still get the same error with this:
try {Connect-PowerBIServiceAccount} catch {"Boo"}
I follow the steps to fix this issue.
RESOLUTION
To resolve this issue, we need to install the correct module. It may not be the latest build, but the builds have to match in order for things to work for us. In my scenario, I installed the MicrosoftPowerBIMgmt.Workspaces 1.0.830 so that it matched the MicrosoftPowerBIMgmt.Profile.
I went to the PowerShell Gallery to get the Install-Module cmd.
https://www.powershellgallery.com/packages/MicrosoftPowerBIMgmt/1.0.326
From an Administrative Command-Prompt, type Install-Module -Name MicrosoftPowerBIMgmt.Workspaces -RequiredVersion 1.0.830
NOTE: Remember, for my lab scenario, I used the MicrosoftPowerBIMgmt.Workspaces Module. You will need to install the module that you are focused.
Once installed, close all PowerShell Windows or open a brand new PowerShell window and then type Get-Module. Now the installed modules should match.
NOTE: You have to start a new PowerShell session. If you don’t the error may not go away.
https://dastrongman.wordpress.com/2020/01/11/pbiwiki-login-with-the-power-bi-service-account/

Save-AzrWebApp func downloads a wrong SourcePath

I'm using Save-AzrWebApp function to downloads files from an Azure Web App.
How to do it is described here: https://blog.ipswitch.com/how-to-copy-files-from-an-azure-app-service-with-powershell
My problem is: it doesn't matter which SourcePath I set, it always downloads me files from wwwroot folder.
Code example that I use:
$syncParams = #{
SourcePath = '\wwwroot\history'
TargetPath = $TargetPath
ComputerName = "https://$Name.scm.azurewebsites.net:443/msdeploy.axd?site=$Name"
Credential = $Credential
}
Sync-Website #syncParams
Get-Item -Path $TargetPath
Actually it doesn't matter what I put into SourcePath (even not existing path) it will download content of wwwroot.
How to use it in a proper way?
If you want to download file from web app, you could use this web app kudu api via powershell.
Try the command below, it works fine on my side.
$creds = Invoke-AzureRmResourceAction -ResourceGroupName joywebapp -ResourceType Microsoft.Web/sites/config -ResourceName joywebapp2/publishingcredentials -Action list -ApiVersion 2015-08-01 -Force
$username = $creds.Properties.PublishingUserName
$password = $creds.Properties.PublishingPassword
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password)))
$apiUrl = "https://joywebapp2.scm.azurewebsites.net/api/vfs/site/wwwroot/Content/Site.css"
Invoke-RestMethod -Uri $apiUrl -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo);"If-Match"="*"} -Method GET -ContentType "multipart/form-data" -OutFile "C:\Users\joyw\Desktop\test.css"
Test result:
Update:
If you want to download a folder, you can use the Zip api in the doc I mentioned, it allows downloading folder as a zip file.
Sample command:
$creds = Invoke-AzureRmResourceAction -ResourceGroupName joywebapp -ResourceType Microsoft.Web/sites/config -ResourceName joywebapp2/publishingcredentials -Action list -ApiVersion 2015-08-01 -Force
$username = $creds.Properties.PublishingUserName
$password = $creds.Properties.PublishingPassword
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password)))
$apiUrl = "https://joywebapp2.scm.azurewebsites.net/api/zip/site/wwwroot/Scripts/"
Invoke-RestMethod -Uri $apiUrl -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo);"If-Match"="*"} -Method GET -ContentType "multipart/form-data" -OutFile "C:\Users\joyw\Desktop\Scripts.zip"
Note:The zip doesn't include the top folder itself. Make sure you include
the trailing slash, e.g, I download the Scripts folder, we need to use Scripts/ in the apiUrl.

invoke-webrequest returns 401 with Windows Authentication

I'm working on a script to login to a sharepoint 2013 site and navigate to a few pages to make sure the site is working after updates and DR drills. I'm calling Invoke-WebRequest like this:
$site = Invoke-WebRequest -uri 'https://spsite' -Credential $(Get-Credential) -SessionVariable s
when I make the call I get a 401 Unauthorized error back. I have tried using basic authentication and building out the headers like this:
$u = 'domain\user'
$p = 'password'
$header = #{ Authorization = "Basic {0}" -f [convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $u,$p))) }
$site = Invoke-WebRequest -uri 'https://spsite' -Headers $header
with the same result. I'm hoping someone could offer another way to make this connection?
so I found a way to make this work in my situation and wanted to post the basics in case someone else runs into this.
I found that when the exception is thrown you can get the actual response from the web server from the exception object like this:
try{
$site = Invoke-WebRequest -uri 'https://spsite' -Credential $(Get-Credential) -SessionVariable s
}
catch{
$site = $_.Exception.Response
}
after that I was able to manipulate the $site variable to follow the redirection and submit the credentials as needed.
Use Export-PSCredential and Import-PSCredential from WFTools - you'll only have to enter your credentials once per box, and it will last as long as your password doesn't change: https://github.com/RamblingCookieMonster/PowerShell
Install-Module -Name WFTools -RequiredVersion 0.1.44
Import-Module WFTools;
$getCredentialMessage = "Please provide your Windows credentials";
$importedCredential = Import-PSCredential;
if ($importedCredential) {
Write-Host -ForegroundColor Yellow "Imported your cached credential."
while (-not $(Test-Credential -Credential $credential)) {
Write-Host -ForegroundColor Yellow "Your cached credentials are not valid. Please re-enter."
$credential = Get-Credential -Message $getCredentialMessage;
}
$credential = $importedCredential;
}
else {
$credential = Get-Credential -Message $getCredentialMessage;
while (-not $(Test-Credential -Credential $credential)) {
$credential = Get-Credential -Message $getCredentialMessage;
}
Export-PSCredential $credential;
}
# Here is where the magic happens
$site = Invoke-WebRequest -uri 'https://spsite' -Credential $credential