有馬総一郎のブログ

(彼氏の事情)

2020年11月29日 02:05:12 JST - 2 minute read - Comments - PowerShell

powershellコマンドでのネットワークドライブ接続が上手く行かない

powershellコマンドでのネットワークドライブ接続が上手く行かない。とあるPowerShellのスクリプトファイル(test.PS1)内でネットワークドライブ接続を行っている。

内容としては以下のようなもの。

test.PS1

$securePass = ConvertTo-SecureString "password" -AsPlainText -Force;
$cred = New-Object System.Management.Automation.PSCredential "username", $securePass;
New-PSDrive -Persist -Name "G" -PSProvider FileSystem -Root "\\192.168.1.99\samba" -Credential $cred;

因みに上の方法は長ったらしいし、エクスプローラーからは接続したネットワークドライブが見えないので、以下の方がお薦め?である。

(new-object -ComObject WScript.Network).MapNetworkDrive("G:", "\\192.168.1.99\samba", $false, "username", "password")

ともあれ、 .ps1 ファイルを選択しての右クリック"PowerShellで実行"ではネットワークドライブ接続が上手く行くのに、コマンドプロンプトから

> powershell -ExecutionPolicy RemoteSigned -file "C:\Users\arimas\test.PS1"

と実行した場合、 ネットワークドライブ接続だけ が上手く行かない。他の処理はちゃんと動く。

なので、

> runas /savecred /user:arima "powershell -ExecutionPolicy RemoteSigned -file \"C:\Users\arimas\test.PS1\""

とユーザー指定して実行してみたけど、 ネットワークドライブ接続は 駄目だった。

結局、powershellで一度起動して

PS > Set-ExecutionPolicy RemoteSigned -Scope Process
PS > cd C:\Users\arimas
PS > .\test.PS1

とやるとネットワークドライブ接続も上手く行った。

しかし、Set-ExecutionPolicy RemoteSigned -Scope Processした後でも

  • powershell -file "C:\Users\arimas\test.PS1"
  • powershell -ExecutionPolicy RemoteSigned -file "C:\Users\arimas\test.PS1"

powershell経由だと両方も ネットワークドライブ接続は 駄目だった。